[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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   * @global wpdb   $wpdb               WordPress database abstraction object.
  29   *
  30   * @param array       $credentials {
  31   *     Optional. User info in order to sign on.
  32   *
  33   *     @type string $user_login    Username.
  34   *     @type string $user_password User password.
  35   *     @type bool   $remember      Whether to 'remember' the user. Increases the time
  36   *                                 that the cookie will be kept. Default false.
  37   * }
  38   * @param string|bool $secure_cookie Optional. Whether to use secure cookie.
  39   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  40   */
  41  function wp_signon( $credentials = array(), $secure_cookie = '' ) {
  42      global $auth_secure_cookie, $wpdb;
  43  
  44      if ( empty( $credentials ) ) {
  45          $credentials = array(
  46              'user_login'    => '',
  47              'user_password' => '',
  48              'remember'      => false,
  49          );
  50  
  51          if ( ! empty( $_POST['log'] ) && is_string( $_POST['log'] ) ) {
  52              $credentials['user_login'] = wp_unslash( $_POST['log'] );
  53          }
  54          if ( ! empty( $_POST['pwd'] ) && is_string( $_POST['pwd'] ) ) {
  55              $credentials['user_password'] = $_POST['pwd'];
  56          }
  57          if ( ! empty( $_POST['rememberme'] ) ) {
  58              $credentials['remember'] = $_POST['rememberme'];
  59          }
  60      }
  61  
  62      if ( ! empty( $credentials['remember'] ) ) {
  63          $credentials['remember'] = true;
  64      } else {
  65          $credentials['remember'] = false;
  66      }
  67  
  68      /**
  69       * Fires before the user is authenticated.
  70       *
  71       * The variables passed to the callbacks are passed by reference,
  72       * and can be modified by callback functions.
  73       *
  74       * @since 1.5.1
  75       *
  76       * @todo Decide whether to deprecate the wp_authenticate action.
  77       *
  78       * @param string $user_login    Username (passed by reference).
  79       * @param string $user_password User password (passed by reference).
  80       */
  81      do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
  82  
  83      if ( '' === $secure_cookie ) {
  84          $secure_cookie = is_ssl();
  85      }
  86  
  87      /**
  88       * Filters whether to use a secure sign-on cookie.
  89       *
  90       * @since 3.1.0
  91       *
  92       * @param bool  $secure_cookie Whether to use a secure sign-on cookie.
  93       * @param array $credentials {
  94       *     Array of entered sign-on data.
  95       *
  96       *     @type string $user_login    Username.
  97       *     @type string $user_password Password entered.
  98       *     @type bool   $remember      Whether to 'remember' the user. Increases the time
  99       *                                 that the cookie will be kept. Default false.
 100       * }
 101       */
 102      $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
 103  
 104      // XXX ugly hack to pass this to wp_authenticate_cookie().
 105      $auth_secure_cookie = $secure_cookie;
 106  
 107      add_filter( 'authenticate', 'wp_authenticate_cookie', 30, 3 );
 108  
 109      $user = wp_authenticate( $credentials['user_login'], $credentials['user_password'] );
 110  
 111      if ( is_wp_error( $user ) ) {
 112          return $user;
 113      }
 114  
 115      wp_set_auth_cookie( $user->ID, $credentials['remember'], $secure_cookie );
 116  
 117      // Clear `user_activation_key` after a successful login.
 118      if ( ! empty( $user->user_activation_key ) ) {
 119          $wpdb->update(
 120              $wpdb->users,
 121              array(
 122                  'user_activation_key' => '',
 123              ),
 124              array( 'ID' => $user->ID )
 125          );
 126  
 127          $user->user_activation_key = '';
 128      }
 129  
 130      /**
 131       * Fires after the user has successfully logged in.
 132       *
 133       * @since 1.5.0
 134       *
 135       * @param string  $user_login Username.
 136       * @param WP_User $user       WP_User object of the logged-in user.
 137       */
 138      do_action( 'wp_login', $user->user_login, $user );
 139  
 140      return $user;
 141  }
 142  
 143  /**
 144   * Authenticates a user, confirming the username and password are valid.
 145   *
 146   * @since 2.8.0
 147   *
 148   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object from a previous callback. Default null.
 149   * @param string                $username Username for authentication.
 150   * @param string                $password Password for authentication.
 151   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 152   */
 153  function wp_authenticate_username_password(
 154      $user,
 155      $username,
 156      #[\SensitiveParameter]
 157      $password
 158  ) {
 159      if ( $user instanceof WP_User ) {
 160          return $user;
 161      }
 162  
 163      if ( empty( $username ) || empty( $password ) ) {
 164          if ( is_wp_error( $user ) ) {
 165              return $user;
 166          }
 167  
 168          $error = new WP_Error();
 169  
 170          if ( empty( $username ) ) {
 171              $error->add( 'empty_username', __( '<strong>Error:</strong> The username field is empty.' ) );
 172          }
 173  
 174          if ( empty( $password ) ) {
 175              $error->add( 'empty_password', __( '<strong>Error:</strong> The password field is empty.' ) );
 176          }
 177  
 178          return $error;
 179      }
 180  
 181      $user = get_user_by( 'login', $username );
 182  
 183      if ( ! $user ) {
 184          return new WP_Error(
 185              'invalid_username',
 186              sprintf(
 187                  /* translators: %s: User name. */
 188                  __( '<strong>Error:</strong> The username <strong>%s</strong> is not registered on this site. If you are unsure of your username, try your email address instead.' ),
 189                  esc_html( $username )
 190              )
 191          );
 192      }
 193  
 194      /**
 195       * Filters whether the given user can be authenticated with the provided password.
 196       *
 197       * @since 2.5.0
 198       *
 199       * @param WP_User|WP_Error $user     WP_User or WP_Error object if a previous
 200       *                                   callback failed authentication.
 201       * @param string           $password Password to check against the user.
 202       */
 203      $user = apply_filters( 'wp_authenticate_user', $user, $password );
 204      if ( is_wp_error( $user ) ) {
 205          return $user;
 206      }
 207  
 208      $valid = wp_check_password( $password, $user->user_pass, $user->ID );
 209  
 210      if ( ! $valid ) {
 211          return new WP_Error(
 212              'incorrect_password',
 213              sprintf(
 214                  /* translators: %s: User name. */
 215                  __( '<strong>Error:</strong> The password you entered for the username %s is incorrect.' ),
 216                  '<strong>' . esc_html( $username ) . '</strong>'
 217              ) .
 218              ' <a href="' . wp_lostpassword_url() . '">' .
 219              __( 'Lost your password?' ) .
 220              '</a>'
 221          );
 222      }
 223  
 224      if ( wp_password_needs_rehash( $user->user_pass, $user->ID ) ) {
 225          wp_set_password( $password, $user->ID );
 226      }
 227  
 228      return $user;
 229  }
 230  
 231  /**
 232   * Authenticates a user using the email and password.
 233   *
 234   * @since 4.5.0
 235   *
 236   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object if a previous
 237   *                                        callback failed authentication.
 238   * @param string                $email    Email address for authentication.
 239   * @param string                $password Password for authentication.
 240   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 241   */
 242  function wp_authenticate_email_password(
 243      $user,
 244      $email,
 245      #[\SensitiveParameter]
 246      $password
 247  ) {
 248      if ( $user instanceof WP_User ) {
 249          return $user;
 250      }
 251  
 252      if ( empty( $email ) || empty( $password ) ) {
 253          if ( is_wp_error( $user ) ) {
 254              return $user;
 255          }
 256  
 257          $error = new WP_Error();
 258  
 259          if ( empty( $email ) ) {
 260              // Uses 'empty_username' for back-compat with wp_signon().
 261              $error->add( 'empty_username', __( '<strong>Error:</strong> The email field is empty.' ) );
 262          }
 263  
 264          if ( empty( $password ) ) {
 265              $error->add( 'empty_password', __( '<strong>Error:</strong> The password field is empty.' ) );
 266          }
 267  
 268          return $error;
 269      }
 270  
 271      if ( ! is_email( $email ) ) {
 272          return $user;
 273      }
 274  
 275      $user = get_user_by( 'email', $email );
 276  
 277      if ( ! $user ) {
 278          return new WP_Error(
 279              'invalid_email',
 280              __( 'Unknown email address. Check again or try your username.' )
 281          );
 282      }
 283  
 284      /** This filter is documented in wp-includes/user.php */
 285      $user = apply_filters( 'wp_authenticate_user', $user, $password );
 286  
 287      if ( is_wp_error( $user ) ) {
 288          return $user;
 289      }
 290  
 291      $valid = wp_check_password( $password, $user->user_pass, $user->ID );
 292  
 293      if ( ! $valid ) {
 294          return new WP_Error(
 295              'incorrect_password',
 296              sprintf(
 297                  /* translators: %s: Email address. */
 298                  __( '<strong>Error:</strong> The password you entered for the email address %s is incorrect.' ),
 299                  '<strong>' . esc_html( $email ) . '</strong>'
 300              ) .
 301              ' <a href="' . wp_lostpassword_url() . '">' .
 302              __( 'Lost your password?' ) .
 303              '</a>'
 304          );
 305      }
 306  
 307      if ( wp_password_needs_rehash( $user->user_pass, $user->ID ) ) {
 308          wp_set_password( $password, $user->ID );
 309      }
 310  
 311      return $user;
 312  }
 313  
 314  /**
 315   * Authenticates the user using the WordPress auth cookie.
 316   *
 317   * @since 2.8.0
 318   *
 319   * @global string $auth_secure_cookie
 320   *
 321   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object from a previous callback. Default null.
 322   * @param string                $username Username. If not empty, cancels the cookie authentication.
 323   * @param string                $password Password. If not empty, cancels the cookie authentication.
 324   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 325   */
 326  function wp_authenticate_cookie(
 327      $user,
 328      $username,
 329      #[\SensitiveParameter]
 330      $password
 331  ) {
 332      global $auth_secure_cookie;
 333  
 334      if ( $user instanceof WP_User ) {
 335          return $user;
 336      }
 337  
 338      if ( empty( $username ) && empty( $password ) ) {
 339          $user_id = wp_validate_auth_cookie();
 340          if ( $user_id ) {
 341              return new WP_User( $user_id );
 342          }
 343  
 344          if ( $auth_secure_cookie ) {
 345              $auth_cookie = SECURE_AUTH_COOKIE;
 346          } else {
 347              $auth_cookie = AUTH_COOKIE;
 348          }
 349  
 350          if ( ! empty( $_COOKIE[ $auth_cookie ] ) ) {
 351              return new WP_Error( 'expired_session', __( 'Please log in again.' ) );
 352          }
 353  
 354          // If the cookie is not set, be silent.
 355      }
 356  
 357      return $user;
 358  }
 359  
 360  /**
 361   * Authenticates the user using an application password.
 362   *
 363   * @since 5.6.0
 364   *
 365   * @param WP_User|WP_Error|null $input_user WP_User or WP_Error object if a previous
 366   *                                          callback failed authentication.
 367   * @param string                $username   Username for authentication.
 368   * @param string                $password   Password for authentication.
 369   * @return WP_User|WP_Error|null WP_User on success, WP_Error on failure, null if
 370   *                               null is passed in and this isn't an API request.
 371   */
 372  function wp_authenticate_application_password(
 373      $input_user,
 374      $username,
 375      #[\SensitiveParameter]
 376      $password
 377  ) {
 378      if ( $input_user instanceof WP_User ) {
 379          return $input_user;
 380      }
 381  
 382      if ( ! WP_Application_Passwords::is_in_use() ) {
 383          return $input_user;
 384      }
 385  
 386      // The 'REST_REQUEST' check here may happen too early for the constant to be available.
 387      $is_api_request = ( ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) );
 388  
 389      /**
 390       * Filters whether this is an API request that Application Passwords can be used on.
 391       *
 392       * By default, Application Passwords is available for the REST API and XML-RPC.
 393       *
 394       * @since 5.6.0
 395       *
 396       * @param bool $is_api_request If this is an acceptable API request.
 397       */
 398      $is_api_request = apply_filters( 'application_password_is_api_request', $is_api_request );
 399  
 400      if ( ! $is_api_request ) {
 401          return $input_user;
 402      }
 403  
 404      $error = null;
 405      $user  = get_user_by( 'login', $username );
 406  
 407      if ( ! $user && is_email( $username ) ) {
 408          $user = get_user_by( 'email', $username );
 409      }
 410  
 411      // If the login name is invalid, short circuit.
 412      if ( ! $user ) {
 413          if ( is_email( $username ) ) {
 414              $error = new WP_Error(
 415                  'invalid_email',
 416                  __( '<strong>Error:</strong> Unknown email address. Check again or try your username.' )
 417              );
 418          } else {
 419              $error = new WP_Error(
 420                  'invalid_username',
 421                  __( '<strong>Error:</strong> Unknown username. Check again or try your email address.' )
 422              );
 423          }
 424      } elseif ( ! wp_is_application_passwords_available() ) {
 425          $error = new WP_Error(
 426              'application_passwords_disabled',
 427              __( 'Application passwords are not available.' )
 428          );
 429      } elseif ( ! wp_is_application_passwords_available_for_user( $user ) ) {
 430          $error = new WP_Error(
 431              'application_passwords_disabled_for_user',
 432              __( 'Application passwords are not available for your account. Please contact the site administrator for assistance.' )
 433          );
 434      }
 435  
 436      if ( $error ) {
 437          /**
 438           * Fires when an application password failed to authenticate the user.
 439           *
 440           * @since 5.6.0
 441           *
 442           * @param WP_Error $error The authentication error.
 443           */
 444          do_action( 'application_password_failed_authentication', $error );
 445  
 446          return $error;
 447      }
 448  
 449      /*
 450       * Strips out anything non-alphanumeric. This is so passwords can be used with
 451       * or without spaces to indicate the groupings for readability.
 452       *
 453       * Generated application passwords are exclusively alphanumeric.
 454       */
 455      $password = preg_replace( '/[^a-z\d]/i', '', $password );
 456  
 457      $hashed_passwords = WP_Application_Passwords::get_user_application_passwords( $user->ID );
 458  
 459      foreach ( $hashed_passwords as $key => $item ) {
 460          if ( ! WP_Application_Passwords::check_password( $password, $item['password'] ) ) {
 461              continue;
 462          }
 463  
 464          $error = new WP_Error();
 465  
 466          /**
 467           * Fires when an application password has been successfully checked as valid.
 468           *
 469           * This allows for plugins to add additional constraints to prevent an application password from being used.
 470           *
 471           * @since 5.6.0
 472           *
 473           * @param WP_Error $error    The error object.
 474           * @param WP_User  $user     The user authenticating.
 475           * @param array    $item     The details about the application password.
 476           * @param string   $password The raw supplied password.
 477           */
 478          do_action( 'wp_authenticate_application_password_errors', $error, $user, $item, $password );
 479  
 480          if ( $error->has_errors() ) {
 481              /** This action is documented in wp-includes/user.php */
 482              do_action( 'application_password_failed_authentication', $error );
 483  
 484              return $error;
 485          }
 486  
 487          WP_Application_Passwords::record_application_password_usage( $user->ID, $item['uuid'] );
 488  
 489          /**
 490           * Fires after an application password was used for authentication.
 491           *
 492           * @since 5.6.0
 493           *
 494           * @param WP_User $user The user who was authenticated.
 495           * @param array   $item The application password used.
 496           */
 497          do_action( 'application_password_did_authenticate', $user, $item );
 498  
 499          return $user;
 500      }
 501  
 502      $error = new WP_Error(
 503          'incorrect_password',
 504          __( 'The provided password is an invalid application password.' )
 505      );
 506  
 507      /** This action is documented in wp-includes/user.php */
 508      do_action( 'application_password_failed_authentication', $error );
 509  
 510      return $error;
 511  }
 512  
 513  /**
 514   * Validates the application password credentials passed via Basic Authentication.
 515   *
 516   * @since 5.6.0
 517   *
 518   * @param int|false $input_user User ID if one has been determined, false otherwise.
 519   * @return int|false The authenticated user ID if successful, false otherwise.
 520   */
 521  function wp_validate_application_password( $input_user ) {
 522      // Don't authenticate twice.
 523      if ( ! empty( $input_user ) ) {
 524          return $input_user;
 525      }
 526  
 527      if ( ! wp_is_application_passwords_available() ) {
 528          return $input_user;
 529      }
 530  
 531      // Both $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] must be set in order to attempt authentication.
 532      if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
 533          return $input_user;
 534      }
 535  
 536      $authenticated = wp_authenticate_application_password( null, $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] );
 537  
 538      if ( $authenticated instanceof WP_User ) {
 539          return $authenticated->ID;
 540      }
 541  
 542      // If it wasn't a user what got returned, just pass on what we had received originally.
 543      return $input_user;
 544  }
 545  
 546  /**
 547   * For Multisite blogs, checks if the authenticated user has been marked as a
 548   * spammer, or if the user's primary blog has been marked as spam.
 549   *
 550   * @since 3.7.0
 551   *
 552   * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
 553   * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
 554   */
 555  function wp_authenticate_spam_check( $user ) {
 556      if ( $user instanceof WP_User && is_multisite() ) {
 557          /**
 558           * Filters whether the user has been marked as a spammer.
 559           *
 560           * @since 3.7.0
 561           *
 562           * @param bool    $spammed Whether the user is considered a spammer.
 563           * @param WP_User $user    User to check against.
 564           */
 565          $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy( $user ), $user );
 566  
 567          if ( $spammed ) {
 568              return new WP_Error( 'spammer_account', __( '<strong>Error:</strong> Your account has been marked as a spammer.' ) );
 569          }
 570      }
 571      return $user;
 572  }
 573  
 574  /**
 575   * Validates the logged-in cookie.
 576   *
 577   * Checks the logged-in cookie if the previous auth cookie could not be
 578   * validated and parsed.
 579   *
 580   * This is a callback for the {@see 'determine_current_user'} filter, rather than API.
 581   *
 582   * @since 3.9.0
 583   *
 584   * @param int|false $user_id The user ID (or false) as received from
 585   *                           the `determine_current_user` filter.
 586   * @return int|false User ID if validated, false otherwise. If a user ID from
 587   *                   an earlier filter callback is received, that value is returned.
 588   */
 589  function wp_validate_logged_in_cookie( $user_id ) {
 590      if ( $user_id ) {
 591          return $user_id;
 592      }
 593  
 594      if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
 595          return false;
 596      }
 597  
 598      return wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
 599  }
 600  
 601  /**
 602   * Gets the number of posts a user has written.
 603   *
 604   * @since 3.0.0
 605   * @since 4.1.0 Added `$post_type` argument.
 606   * @since 4.3.0 Added `$public_only` argument. Added the ability to pass an array
 607   *              of post types to `$post_type`.
 608   *
 609   * @global wpdb $wpdb WordPress database abstraction object.
 610   *
 611   * @param int          $userid      User ID.
 612   * @param array|string $post_type   Optional. Single post type or array of post types to count the number of posts for. Default 'post'.
 613   * @param bool         $public_only Optional. Whether to only return counts for public posts. Default false.
 614   * @return string Number of posts the user has written in this post type.
 615   */
 616  function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
 617      global $wpdb;
 618  
 619      $post_type = array_unique( (array) $post_type );
 620      sort( $post_type );
 621  
 622      $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
 623      $query = "SELECT COUNT(*) FROM $wpdb->posts $where";
 624  
 625      $last_changed = wp_cache_get_last_changed( 'posts' );
 626      $cache_key    = 'count_user_posts:' . md5( $query );
 627      $count        = wp_cache_get_salted( $cache_key, 'post-queries', $last_changed );
 628      if ( false === $count ) {
 629          $count = $wpdb->get_var( $query );
 630          wp_cache_set_salted( $cache_key, $count, 'post-queries', $last_changed );
 631      }
 632  
 633      /**
 634       * Filters the number of posts a user has written.
 635       *
 636       * @since 2.7.0
 637       * @since 4.1.0 Added `$post_type` argument.
 638       * @since 4.3.1 Added `$public_only` argument.
 639       *
 640       * @param string       $count       The user's post count as a numeric string.
 641       * @param int          $userid      User ID.
 642       * @param string|array $post_type   Single post type or array of post types to count the number of posts for.
 643       * @param bool         $public_only Whether to limit counted posts to public posts.
 644       */
 645      return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
 646  }
 647  
 648  /**
 649   * Gets the number of posts written by a list of users.
 650   *
 651   * @since 3.0.0
 652   * @since 6.9.0 The results are now cached.
 653   *
 654   * @global wpdb $wpdb WordPress database abstraction object.
 655   *
 656   * @param int[]           $users       Array of user IDs.
 657   * @param string|string[] $post_type   Optional. Single post type or array of post types to check. Defaults to 'post'.
 658   * @param bool            $public_only Optional. Only return counts for public posts.  Defaults to false.
 659   * @return array<int, string> Amount of posts each user has written, as strings, keyed by user ID.
 660   */
 661  function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
 662      global $wpdb;
 663  
 664      if ( empty( $users ) || ! is_array( $users ) ) {
 665          return array();
 666      }
 667  
 668      /**
 669       * Filters whether to short-circuit performing the post counts.
 670       *
 671       * When filtering, return an array of posts counts as strings, keyed
 672       * by the user ID.
 673       *
 674       * @since 6.8.0
 675       *
 676       * @param string[]|null   $count       The post counts. Return a non-null value to short-circuit.
 677       * @param int[]           $users       Array of user IDs.
 678       * @param string|string[] $post_type   Single post type or array of post types to check.
 679       * @param bool            $public_only Whether to only return counts for public posts.
 680       */
 681      $pre = apply_filters( 'pre_count_many_users_posts', null, $users, $post_type, $public_only );
 682      if ( null !== $pre ) {
 683          return $pre;
 684      }
 685  
 686      // Cleanup the users array. Remove duplicates and sort for consistent ordering.
 687      $users = array_unique( array_filter( array_map( 'intval', $users ) ) );
 688      sort( $users );
 689  
 690      // Cleanup the post type argument. Remove duplicates and sort for consistent ordering.
 691      $post_type = array_unique( (array) $post_type );
 692      sort( $post_type );
 693  
 694      $userlist    = implode( ',', $users );
 695      $where       = get_posts_by_author_sql( $post_type, true, null, $public_only );
 696      $query       = "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author";
 697      $cache_key   = 'count_many_users_posts:' . md5( $query );
 698      $cache_salts = array( wp_cache_get_last_changed( 'posts' ), wp_cache_get_last_changed( 'users' ) );
 699      $count       = wp_cache_get_salted( $cache_key, 'post-queries', $cache_salts );
 700  
 701      if ( false === $count ) {
 702          $result = $wpdb->get_results( $query, ARRAY_N );
 703  
 704          $count = array_fill_keys( $users, 0 );
 705          foreach ( $result as $row ) {
 706              $count[ $row[0] ] = $row[1];
 707          }
 708  
 709          wp_cache_set_salted( $cache_key, $count, 'post-queries', $cache_salts, HOUR_IN_SECONDS );
 710      }
 711  
 712      return $count;
 713  }
 714  
 715  //
 716  // User option functions.
 717  //
 718  
 719  /**
 720   * Gets the current user's ID.
 721   *
 722   * @since MU (3.0.0)
 723   *
 724   * @return int The current user's ID, or 0 if no user is logged in.
 725   */
 726  function get_current_user_id() {
 727      if ( ! function_exists( 'wp_get_current_user' ) ) {
 728          return 0;
 729      }
 730      $user = wp_get_current_user();
 731      return (int) $user->ID;
 732  }
 733  
 734  /**
 735   * Retrieves user option that can be either per Site or per Network.
 736   *
 737   * If the user ID is not given, then the current user will be used instead. If
 738   * the user ID is given, then the user data will be retrieved. The filter for
 739   * the result, will also pass the original option name and finally the user data
 740   * object as the third parameter.
 741   *
 742   * The option will first check for the per site name and then the per Network name.
 743   *
 744   * @since 2.0.0
 745   *
 746   * @global wpdb $wpdb WordPress database abstraction object.
 747   *
 748   * @param string $option     User option name.
 749   * @param int    $user       Optional. User ID.
 750   * @param string $deprecated Use get_option() to check for an option in the options table.
 751   * @return mixed User option value on success, false on failure.
 752   */
 753  function get_user_option( $option, $user = 0, $deprecated = '' ) {
 754      global $wpdb;
 755  
 756      if ( ! empty( $deprecated ) ) {
 757          _deprecated_argument( __FUNCTION__, '3.0.0' );
 758      }
 759  
 760      if ( empty( $user ) ) {
 761          $user = get_current_user_id();
 762      }
 763  
 764      $user = get_userdata( $user );
 765      if ( ! $user ) {
 766          return false;
 767      }
 768  
 769      $prefix = $wpdb->get_blog_prefix();
 770      if ( $user->has_prop( $prefix . $option ) ) { // Blog-specific.
 771          $result = $user->get( $prefix . $option );
 772      } elseif ( $user->has_prop( $option ) ) { // User-specific and cross-blog.
 773          $result = $user->get( $option );
 774      } else {
 775          $result = false;
 776      }
 777  
 778      /**
 779       * Filters a specific user option value.
 780       *
 781       * The dynamic portion of the hook name, `$option`, refers to the user option name.
 782       *
 783       * @since 2.5.0
 784       *
 785       * @param mixed   $result Value for the user's option.
 786       * @param string  $option Name of the option being retrieved.
 787       * @param WP_User $user   WP_User object of the user whose option is being retrieved.
 788       */
 789      return apply_filters( "get_user_option_{$option}", $result, $option, $user );
 790  }
 791  
 792  /**
 793   * Updates user option with global blog capability.
 794   *
 795   * User options are just like user metadata except that they have support for
 796   * global blog options. If the 'is_global' parameter is false, which it is by default,
 797   * it will prepend the WordPress table prefix to the option name.
 798   *
 799   * Deletes the user option if $newvalue is empty.
 800   *
 801   * @since 2.0.0
 802   *
 803   * @global wpdb $wpdb WordPress database abstraction object.
 804   *
 805   * @param int    $user_id     User ID.
 806   * @param string $option_name User option name.
 807   * @param mixed  $newvalue    User option value.
 808   * @param bool   $is_global   Optional. Whether option name is global or blog specific.
 809   *                            Default false (blog specific).
 810   * @return int|bool User meta ID if the option didn't exist, true on successful update,
 811   *                  false on failure.
 812   */
 813  function update_user_option( $user_id, $option_name, $newvalue, $is_global = false ) {
 814      global $wpdb;
 815  
 816      if ( ! $is_global ) {
 817          $option_name = $wpdb->get_blog_prefix() . $option_name;
 818      }
 819  
 820      return update_user_meta( $user_id, $option_name, $newvalue );
 821  }
 822  
 823  /**
 824   * Deletes user option with global blog capability.
 825   *
 826   * User options are just like user metadata except that they have support for
 827   * global blog options. If the 'is_global' parameter is false, which it is by default,
 828   * it will prepend the WordPress table prefix to the option name.
 829   *
 830   * @since 3.0.0
 831   *
 832   * @global wpdb $wpdb WordPress database abstraction object.
 833   *
 834   * @param int    $user_id     User ID
 835   * @param string $option_name User option name.
 836   * @param bool   $is_global   Optional. Whether option name is global or blog specific.
 837   *                            Default false (blog specific).
 838   * @return bool True on success, false on failure.
 839   */
 840  function delete_user_option( $user_id, $option_name, $is_global = false ) {
 841      global $wpdb;
 842  
 843      if ( ! $is_global ) {
 844          $option_name = $wpdb->get_blog_prefix() . $option_name;
 845      }
 846  
 847      return delete_user_meta( $user_id, $option_name );
 848  }
 849  
 850  /**
 851   * Retrieves user info by user ID.
 852   *
 853   * @since 6.7.0
 854   *
 855   * @param int $user_id User ID.
 856   * @return WP_User|false WP_User object on success, false on failure.
 857   *
 858   * @phpstan-return ( $user_id is int<min, 0> ? false : WP_User|false )
 859   */
 860  function get_user( $user_id ) {
 861      return get_user_by( 'id', $user_id );
 862  }
 863  
 864  /**
 865   * Retrieves list of users matching criteria.
 866   *
 867   * @since 3.1.0
 868   *
 869   * @see WP_User_Query
 870   *
 871   * @param array $args Optional. Arguments to retrieve users. See WP_User_Query::prepare_query()
 872   *                    for more information on accepted arguments.
 873   * @return array List of users.
 874   *
 875   * @phpstan-return (
 876   *     $args is array{ fields: 'all'|'all_with_meta', ... } ? array<int, WP_User> : (
 877   *         $args is array{ fields: 'ID'|'id', ... } ? list<numeric-string> : (
 878   *             $args is array{ fields: non-empty-string|non-empty-array<array-key, string>, ... } ? array<int, mixed> : array<int, WP_User>
 879   *         )
 880   *     )
 881   * )
 882   */
 883  function get_users( $args = array() ) {
 884  
 885      $args                = wp_parse_args( $args );
 886      $args['count_total'] = false;
 887  
 888      $user_search = new WP_User_Query( $args );
 889  
 890      return (array) $user_search->get_results();
 891  }
 892  
 893  /**
 894   * Lists all the users of the site, with several options available.
 895   *
 896   * @since 5.9.0
 897   *
 898   * @param string|array $args {
 899   *     Optional. Array or string of default arguments.
 900   *
 901   *     @type string $orderby       How to sort the users. Accepts 'nicename', 'email', 'url', 'registered',
 902   *                                 'user_nicename', 'user_email', 'user_url', 'user_registered', 'name',
 903   *                                 'display_name', 'post_count', 'ID', 'meta_value', 'user_login'. Default 'name'.
 904   *     @type string $order         Sorting direction for $orderby. Accepts 'ASC', 'DESC'. Default 'ASC'.
 905   *     @type int    $number        Maximum users to return or display. Default empty (all users).
 906   *     @type bool   $exclude_admin Whether to exclude the 'admin' account, if it exists. Default true.
 907   *     @type bool   $show_fullname Whether to show the user's full name. Default false.
 908   *     @type string $feed          If not empty, show a link to the user's feed and use this text as the alt
 909   *                                 parameter of the link. Default empty.
 910   *     @type string $feed_image    If not empty, show a link to the user's feed and use this image URL as
 911   *                                 clickable anchor. Default empty.
 912   *     @type string $feed_type     The feed type to link to, such as 'rss2'. Defaults to default feed type.
 913   *     @type bool   $echo          Whether to output the result or instead return it. Default true.
 914   *     @type string $style         If 'list', each user is wrapped in an `<li>` element, otherwise the users
 915   *                                 will be separated by commas.
 916   *     @type bool   $html          Whether to list the items in HTML form or plaintext. Default true.
 917   *     @type string $exclude       An array, comma-, or space-separated list of user IDs to exclude. Default empty.
 918   *     @type string $include       An array, comma-, or space-separated list of user IDs to include. Default empty.
 919   * }
 920   * @return string|void The output if 'echo' is false, nothing otherwise.
 921   * @phpstan-return (
 922   *     $args is array{ echo: false|0|''|'0', ... }
 923   *         ? string
 924   *         : ( $args is ''|'0'|array ? void : string|null )
 925   * )
 926   */
 927  function wp_list_users( $args = array() ) {
 928      $defaults = array(
 929          'orderby'       => 'name',
 930          'order'         => 'ASC',
 931          'number'        => '',
 932          'exclude_admin' => true,
 933          'show_fullname' => false,
 934          'feed'          => '',
 935          'feed_image'    => '',
 936          'feed_type'     => '',
 937          'echo'          => true,
 938          'style'         => 'list',
 939          'html'          => true,
 940          'exclude'       => '',
 941          'include'       => '',
 942      );
 943  
 944      $parsed_args = wp_parse_args( $args, $defaults );
 945  
 946      $return = '';
 947  
 948      $query_args           = wp_array_slice_assoc( $parsed_args, array( 'orderby', 'order', 'number', 'exclude', 'include' ) );
 949      $query_args['fields'] = 'ids';
 950  
 951      /**
 952       * Filters the query arguments for the list of all users of the site.
 953       *
 954       * @since 6.1.0
 955       *
 956       * @param array $query_args  The query arguments for get_users().
 957       * @param array $parsed_args The arguments passed to wp_list_users() combined with the defaults.
 958       */
 959      $query_args = apply_filters( 'wp_list_users_args', $query_args, $parsed_args );
 960  
 961      $users = get_users( $query_args );
 962  
 963      foreach ( $users as $user_id ) {
 964          $user = get_userdata( $user_id );
 965  
 966          if ( $parsed_args['exclude_admin'] && 'admin' === $user->display_name ) {
 967              continue;
 968          }
 969  
 970          if ( $parsed_args['show_fullname'] && '' !== $user->first_name && '' !== $user->last_name ) {
 971              $name = sprintf(
 972                  /* translators: 1: User's first name, 2: Last name. */
 973                  _x( '%1$s %2$s', 'Display name based on first name and last name' ),
 974                  $user->first_name,
 975                  $user->last_name
 976              );
 977          } else {
 978              $name = $user->display_name;
 979          }
 980  
 981          if ( ! $parsed_args['html'] ) {
 982              $return .= $name . ', ';
 983  
 984              continue; // No need to go further to process HTML.
 985          }
 986  
 987          if ( 'list' === $parsed_args['style'] ) {
 988              $return .= '<li>';
 989          }
 990  
 991          $row = $name;
 992  
 993          if ( ! empty( $parsed_args['feed_image'] ) || ! empty( $parsed_args['feed'] ) ) {
 994              $row .= ' ';
 995              if ( empty( $parsed_args['feed_image'] ) ) {
 996                  $row .= '(';
 997              }
 998  
 999              $row .= '<a href="' . get_author_feed_link( $user->ID, $parsed_args['feed_type'] ) . '"';
1000  
1001              $alt = '';
1002              if ( ! empty( $parsed_args['feed'] ) ) {
1003                  $alt  = ' alt="' . esc_attr( $parsed_args['feed'] ) . '"';
1004                  $name = $parsed_args['feed'];
1005              }
1006  
1007              $row .= '>';
1008  
1009              if ( ! empty( $parsed_args['feed_image'] ) ) {
1010                  $row .= '<img src="' . esc_url( $parsed_args['feed_image'] ) . '" style="border: none;"' . $alt . ' />';
1011              } else {
1012                  $row .= $name;
1013              }
1014  
1015              $row .= '</a>';
1016  
1017              if ( empty( $parsed_args['feed_image'] ) ) {
1018                  $row .= ')';
1019              }
1020          }
1021  
1022          $return .= $row;
1023          $return .= ( 'list' === $parsed_args['style'] ) ? '</li>' : ', ';
1024      }
1025  
1026      $return = rtrim( $return, ', ' );
1027  
1028      if ( ! $parsed_args['echo'] ) {
1029          return $return;
1030      }
1031  
1032      echo $return;
1033  }
1034  
1035  /**
1036   * Gets the sites a user belongs to.
1037   *
1038   * @since 3.0.0
1039   * @since 4.7.0 Converted to use `get_sites()`.
1040   *
1041   * @global wpdb $wpdb WordPress database abstraction object.
1042   *
1043   * @param int  $user_id User ID
1044   * @param bool $all     Whether to retrieve all sites, or only sites that are not
1045   *                      marked as deleted, archived, or spam.
1046   * @return object[] A list of the user's sites. An empty array if the user doesn't exist
1047   *                  or belongs to no sites.
1048   */
1049  function get_blogs_of_user( $user_id, $all = false ) {
1050      global $wpdb;
1051  
1052      $user_id = (int) $user_id;
1053  
1054      // Logged out users can't have sites.
1055      if ( empty( $user_id ) ) {
1056          return array();
1057      }
1058  
1059      /**
1060       * Filters the list of a user's sites before it is populated.
1061       *
1062       * Returning a non-null value from the filter will effectively short circuit
1063       * get_blogs_of_user(), returning that value instead.
1064       *
1065       * @since 4.6.0
1066       *
1067       * @param null|object[] $sites   An array of site objects of which the user is a member.
1068       * @param int           $user_id User ID.
1069       * @param bool          $all     Whether the returned array should contain all sites, including
1070       *                               those marked 'deleted', 'archived', or 'spam'. Default false.
1071       */
1072      $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );
1073  
1074      if ( null !== $sites ) {
1075          return $sites;
1076      }
1077  
1078      $keys = get_user_meta( $user_id );
1079      if ( empty( $keys ) ) {
1080          return array();
1081      }
1082  
1083      if ( ! is_multisite() ) {
1084          $site_id                        = get_current_blog_id();
1085          $sites                          = array( $site_id => new stdClass() );
1086          $sites[ $site_id ]->userblog_id = $site_id;
1087          $sites[ $site_id ]->blogname    = get_option( 'blogname' );
1088          $sites[ $site_id ]->domain      = '';
1089          $sites[ $site_id ]->path        = '';
1090          $sites[ $site_id ]->site_id     = 1;
1091          $sites[ $site_id ]->siteurl     = get_option( 'siteurl' );
1092          $sites[ $site_id ]->archived    = 0;
1093          $sites[ $site_id ]->spam        = 0;
1094          $sites[ $site_id ]->deleted     = 0;
1095          return $sites;
1096      }
1097  
1098      $site_ids = array();
1099  
1100      if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
1101          $site_ids[] = 1;
1102          unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
1103      }
1104  
1105      $keys = array_keys( $keys );
1106  
1107      foreach ( $keys as $key ) {
1108          if ( ! str_ends_with( $key, 'capabilities' ) ) {
1109              continue;
1110          }
1111          if ( $wpdb->base_prefix && ! str_starts_with( $key, $wpdb->base_prefix ) ) {
1112              continue;
1113          }
1114          $site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
1115          if ( ! is_numeric( $site_id ) ) {
1116              continue;
1117          }
1118  
1119          $site_ids[] = (int) $site_id;
1120      }
1121  
1122      $sites = array();
1123  
1124      if ( ! empty( $site_ids ) ) {
1125          $args = array(
1126              'number'   => '',
1127              'site__in' => $site_ids,
1128          );
1129          if ( ! $all ) {
1130              $args['archived'] = 0;
1131              $args['spam']     = 0;
1132              $args['deleted']  = 0;
1133          }
1134  
1135          $_sites = get_sites( $args );
1136  
1137          foreach ( $_sites as $site ) {
1138              $sites[ $site->id ] = (object) array(
1139                  'userblog_id' => $site->id,
1140                  'blogname'    => $site->blogname,
1141                  'domain'      => $site->domain,
1142                  'path'        => $site->path,
1143                  'site_id'     => $site->network_id,
1144                  'siteurl'     => $site->siteurl,
1145                  'archived'    => $site->archived,
1146                  'mature'      => $site->mature,
1147                  'spam'        => $site->spam,
1148                  'deleted'     => $site->deleted,
1149              );
1150          }
1151      }
1152  
1153      /**
1154       * Filters the list of sites a user belongs to.
1155       *
1156       * @since MU (3.0.0)
1157       *
1158       * @param object[] $sites   An array of site objects belonging to the user.
1159       * @param int      $user_id User ID.
1160       * @param bool     $all     Whether the returned sites array should contain all sites, including
1161       *                          those flagged for deletion, archived, or marked as spam.
1162       */
1163      return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
1164  }
1165  
1166  /**
1167   * Finds out whether a user is a member of a given blog.
1168   *
1169   * @since MU (3.0.0)
1170   * @since 7.1.0 Introduced the {@see 'is_user_member_of_blog'} filter.
1171   *
1172   * @global wpdb $wpdb WordPress database abstraction object.
1173   *
1174   * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
1175   * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
1176   * @return bool
1177   */
1178  function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
1179      global $wpdb;
1180  
1181      $user_id = (int) $user_id;
1182      $blog_id = (int) $blog_id;
1183  
1184      if ( empty( $user_id ) ) {
1185          $user_id = get_current_user_id();
1186      }
1187  
1188      /*
1189       * Technically not needed, but does save calls to get_site() and get_user_meta()
1190       * in the event that the function is called when a user isn't logged in.
1191       */
1192      if ( empty( $user_id ) ) {
1193          return false;
1194      } else {
1195          $user = get_userdata( $user_id );
1196          if ( ! $user instanceof WP_User ) {
1197              return false;
1198          }
1199      }
1200  
1201      if ( ! is_multisite() ) {
1202          return true;
1203      }
1204  
1205      if ( empty( $blog_id ) ) {
1206          $blog_id = get_current_blog_id();
1207      }
1208  
1209      $blog = get_site( $blog_id );
1210  
1211      if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
1212          return false;
1213      }
1214  
1215      if ( 1 === $blog_id ) {
1216          $capabilities_key = $wpdb->base_prefix . 'capabilities';
1217      } else {
1218          $capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
1219      }
1220  
1221      $has_cap   = get_user_meta( $user_id, $capabilities_key, true );
1222      $is_member = is_array( $has_cap );
1223  
1224      /**
1225       * Filters whether the user is a member of a given blog.
1226       *
1227       * This filter only runs when the user and blog have both been resolved
1228       * to valid records on a multisite installation; it is not invoked for
1229       * logged-out requests, unknown users, or archived/spammed/deleted sites.
1230       *
1231       * @since 7.1.0
1232       *
1233       * @param bool $is_member Whether the user is a member of the blog.
1234       * @param int  $user_id   The user ID being checked.
1235       * @param int  $blog_id   The blog ID being checked.
1236       */
1237      return (bool) apply_filters( 'is_user_member_of_blog', $is_member, $user_id, $blog_id );
1238  }
1239  
1240  /**
1241   * Adds meta data to a user.
1242   *
1243   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
1244   *
1245   * @since 3.0.0
1246   *
1247   * @param int    $user_id    User ID.
1248   * @param string $meta_key   Metadata name.
1249   * @param mixed  $meta_value Metadata value. Arrays and objects are stored as serialized data and
1250   *                           will be returned as the same type when retrieved. Other data types will
1251   *                           be stored as strings in the database:
1252   *                           - false is stored and retrieved as an empty string ('')
1253   *                           - true is stored and retrieved as '1'
1254   *                           - numbers (both integer and float) are stored and retrieved as strings
1255   *                           Must be serializable if non-scalar.
1256   * @param bool   $unique     Optional. Whether the same key should not be added.
1257   *                           Default false.
1258   * @return int|false Meta ID on success, false on failure.
1259   */
1260  function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
1261      return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
1262  }
1263  
1264  /**
1265   * Removes metadata matching criteria from a user.
1266   *
1267   * You can match based on the key, or key and value. Removing based on key and
1268   * value, will keep from removing duplicate metadata with the same key. It also
1269   * allows removing all metadata matching key, if needed.
1270   *
1271   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
1272   *
1273   * @since 3.0.0
1274   *
1275   * @link https://developer.wordpress.org/reference/functions/delete_user_meta/
1276   *
1277   * @param int    $user_id    User ID
1278   * @param string $meta_key   Metadata name.
1279   * @param mixed  $meta_value Optional. Metadata value. If provided,
1280   *                           rows will only be removed that match the value.
1281   *                           Must be serializable if non-scalar. Default empty.
1282   * @return bool True on success, false on failure.
1283   *
1284   * @phpstan-param positive-int $user_id
1285   */
1286  function delete_user_meta( $user_id, $meta_key, $meta_value = '' ) {
1287      return delete_metadata( 'user', $user_id, $meta_key, $meta_value );
1288  }
1289  
1290  /**
1291   * Retrieves user meta field for a user.
1292   *
1293   * @since 3.0.0
1294   *
1295   * @link https://developer.wordpress.org/reference/functions/get_user_meta/
1296   *
1297   * @param int    $user_id User ID.
1298   * @param string $key     Optional. The meta key to retrieve. By default,
1299   *                        returns data for all keys.
1300   * @param bool   $single  Optional. Whether to return a single value.
1301   *                        This parameter has no effect if `$key` is not specified.
1302   *                        Default false.
1303   * @return mixed An array of values if `$single` is false.
1304   *               The value of meta data field if `$single` is true.
1305   *               False for an invalid `$user_id` (non-numeric, zero, or negative value).
1306   *               An empty array if a valid but non-existing user ID is passed and `$single` is false.
1307   *               An empty string if a valid but non-existing user ID is passed and `$single` is true.
1308   *               Note: Non-serialized values are returned as strings:
1309   *               - false values are returned as empty strings ('')
1310   *               - true values are returned as '1'
1311   *               - numbers (both integer and float) are returned as strings
1312   *               Arrays and objects retain their original type.
1313   *               These conversions apply to stored values. A default value registered
1314   *               with {@see register_meta()} is never stored, so it is returned with
1315   *               the type it was registered with, which may be an integer, float, or
1316   *               boolean.
1317   *
1318   * @phpstan-return (
1319   *     $key is ''|'0'
1320   *         ? array<array-key, list<string>>|false
1321   *         : ( $single is true
1322   *             ? mixed
1323   *             : list<mixed>|false )
1324   * )
1325   */
1326  function get_user_meta( $user_id, $key = '', $single = false ) {
1327      return get_metadata( 'user', $user_id, $key, $single );
1328  }
1329  
1330  /**
1331   * Updates user meta field based on user ID.
1332   *
1333   * Use the $prev_value parameter to differentiate between meta fields with the
1334   * same key and user ID.
1335   *
1336   * If the meta field for the user does not exist, it will be added.
1337   *
1338   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
1339   *
1340   * @since 3.0.0
1341   *
1342   * @link https://developer.wordpress.org/reference/functions/update_user_meta/
1343   *
1344   * @param int    $user_id    User ID.
1345   * @param string $meta_key   Metadata key.
1346   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
1347   * @param mixed  $prev_value Optional. Previous value to check before updating.
1348   *                           If specified, only update existing metadata entries with
1349   *                           this value. Otherwise, update all entries. Default empty.
1350   * @return int|bool Meta ID if the key didn't exist, true on successful update,
1351   *                  false on failure or if the value passed to the function
1352   *                  is the same as the one that is already in the database.
1353   */
1354  function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
1355      return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
1356  }
1357  
1358  /**
1359   * Counts number of users who have each of the user roles.
1360   *
1361   * Assumes there are neither duplicated nor orphaned capabilities meta_values.
1362   * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
1363   * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
1364   * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
1365   *
1366   * @since 3.0.0
1367   * @since 4.4.0 The number of users with no role is now included in the `none` element.
1368   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
1369   *
1370   * @global wpdb $wpdb WordPress database abstraction object.
1371   *
1372   * @param string   $strategy Optional. The computational strategy to use when counting the users.
1373   *                           Accepts either 'time' or 'memory'. Default 'time'.
1374   * @param int|null $site_id  Optional. The site ID to count users for. Defaults to the current site.
1375   * @return array {
1376   *     User counts.
1377   *
1378   *     @type int   $total_users Total number of users on the site.
1379   *     @type int[] $avail_roles Array of user counts keyed by user role.
1380   * }
1381   */
1382  function count_users( $strategy = 'time', $site_id = null ) {
1383      global $wpdb;
1384  
1385      // Initialize.
1386      if ( ! $site_id ) {
1387          $site_id = get_current_blog_id();
1388      }
1389  
1390      /**
1391       * Filters the user count before queries are run.
1392       *
1393       * Return a non-null value to cause count_users() to return early.
1394       *
1395       * @since 5.1.0
1396       *
1397       * @param null|array $result   The value to return instead. Default null to continue with the query.
1398       * @param string     $strategy Optional. The computational strategy to use when counting the users.
1399       *                             Accepts either 'time' or 'memory'. Default 'time'.
1400       * @param int        $site_id  The site ID to count users for.
1401       */
1402      $pre = apply_filters( 'pre_count_users', null, $strategy, $site_id );
1403  
1404      if ( null !== $pre ) {
1405          return $pre;
1406      }
1407  
1408      $blog_prefix = $wpdb->get_blog_prefix( $site_id );
1409      $result      = array();
1410  
1411      if ( 'time' === $strategy ) {
1412          if ( is_multisite() && get_current_blog_id() !== $site_id ) {
1413              switch_to_blog( $site_id );
1414              $avail_roles = wp_roles()->get_names();
1415              restore_current_blog();
1416          } else {
1417              $avail_roles = wp_roles()->get_names();
1418          }
1419  
1420          // Build a CPU-intensive query that will return concise information.
1421          $select_count = array();
1422          foreach ( $avail_roles as $this_role => $name ) {
1423              $select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );
1424          }
1425          $select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
1426          $select_count   = implode( ', ', $select_count );
1427  
1428          // Add the meta_value index to the selection list, then run the query.
1429          $row = $wpdb->get_row(
1430              "
1431              SELECT {$select_count}, COUNT(*)
1432              FROM {$wpdb->usermeta}
1433              INNER JOIN {$wpdb->users} ON user_id = ID
1434              WHERE meta_key = '{$blog_prefix}capabilities'
1435          ",
1436              ARRAY_N
1437          );
1438  
1439          // Run the previous loop again to associate results with role names.
1440          $col         = 0;
1441          $role_counts = array();
1442          foreach ( $avail_roles as $this_role => $name ) {
1443              $count = (int) $row[ $col++ ];
1444              if ( $count > 0 ) {
1445                  $role_counts[ $this_role ] = $count;
1446              }
1447          }
1448  
1449          $role_counts['none'] = (int) $row[ $col++ ];
1450  
1451          // Get the meta_value index from the end of the result set.
1452          $total_users = (int) $row[ $col ];
1453  
1454          $result['total_users'] = $total_users;
1455          $result['avail_roles'] =& $role_counts;
1456      } else {
1457          $avail_roles = array(
1458              'none' => 0,
1459          );
1460  
1461          $users_of_blog = $wpdb->get_col(
1462              "
1463              SELECT meta_value
1464              FROM {$wpdb->usermeta}
1465              INNER JOIN {$wpdb->users} ON user_id = ID
1466              WHERE meta_key = '{$blog_prefix}capabilities'
1467          "
1468          );
1469  
1470          foreach ( $users_of_blog as $caps_meta ) {
1471              $b_roles = maybe_unserialize( $caps_meta );
1472              if ( ! is_array( $b_roles ) ) {
1473                  continue;
1474              }
1475              if ( empty( $b_roles ) ) {
1476                  ++$avail_roles['none'];
1477              }
1478              foreach ( $b_roles as $b_role => $val ) {
1479                  if ( isset( $avail_roles[ $b_role ] ) ) {
1480                      ++$avail_roles[ $b_role ];
1481                  } else {
1482                      $avail_roles[ $b_role ] = 1;
1483                  }
1484              }
1485          }
1486  
1487          $result['total_users'] = count( $users_of_blog );
1488          $result['avail_roles'] =& $avail_roles;
1489      }
1490  
1491      return $result;
1492  }
1493  
1494  /**
1495   * Returns the number of active users in your installation.
1496   *
1497   * Note that on a large site the count may be cached and only updated twice daily.
1498   *
1499   * @since MU (3.0.0)
1500   * @since 4.8.0 The `$network_id` parameter has been added.
1501   * @since 6.0.0 Moved to wp-includes/user.php.
1502   *
1503   * @param int|null $network_id ID of the network. Defaults to the current network.
1504   * @return int Number of active users on the network.
1505   */
1506  function get_user_count( $network_id = null ) {
1507      if ( ! is_multisite() && null !== $network_id ) {
1508          _doing_it_wrong(
1509              __FUNCTION__,
1510              sprintf(
1511                  /* translators: %s: $network_id */
1512                  __( 'Unable to pass %s if not using multisite.' ),
1513                  '<code>$network_id</code>'
1514              ),
1515              '6.0.0'
1516          );
1517      }
1518  
1519      return (int) get_network_option( $network_id, 'user_count', -1 );
1520  }
1521  
1522  /**
1523   * Updates the total count of users on the site if live user counting is enabled.
1524   *
1525   * @since 6.0.0
1526   *
1527   * @param int|null $network_id ID of the network. Defaults to the current network.
1528   * @return bool Whether the update was successful.
1529   */
1530  function wp_maybe_update_user_counts( $network_id = null ) {
1531      if ( ! is_multisite() && null !== $network_id ) {
1532          _doing_it_wrong(
1533              __FUNCTION__,
1534              sprintf(
1535                  /* translators: %s: $network_id */
1536                  __( 'Unable to pass %s if not using multisite.' ),
1537                  '<code>$network_id</code>'
1538              ),
1539              '6.0.0'
1540          );
1541      }
1542  
1543      $is_small_network = ! wp_is_large_user_count( $network_id );
1544      /** This filter is documented in wp-includes/ms-functions.php */
1545      if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) ) {
1546          return false;
1547      }
1548  
1549      return wp_update_user_counts( $network_id );
1550  }
1551  
1552  /**
1553   * Updates the total count of users on the site.
1554   *
1555   * @global wpdb $wpdb WordPress database abstraction object.
1556   * @since 6.0.0
1557   *
1558   * @param int|null $network_id ID of the network. Defaults to the current network.
1559   * @return bool Whether the update was successful.
1560   */
1561  function wp_update_user_counts( $network_id = null ) {
1562      global $wpdb;
1563  
1564      if ( ! is_multisite() && null !== $network_id ) {
1565          _doing_it_wrong(
1566              __FUNCTION__,
1567              sprintf(
1568                  /* translators: %s: $network_id */
1569                  __( 'Unable to pass %s if not using multisite.' ),
1570                  '<code>$network_id</code>'
1571              ),
1572              '6.0.0'
1573          );
1574      }
1575  
1576      $query = "SELECT COUNT(ID) as c FROM $wpdb->users";
1577      if ( is_multisite() ) {
1578          $query .= " WHERE spam = '0' AND deleted = '0'";
1579      }
1580  
1581      $count = $wpdb->get_var( $query );
1582  
1583      return update_network_option( $network_id, 'user_count', $count );
1584  }
1585  
1586  /**
1587   * Schedules a recurring recalculation of the total count of users.
1588   *
1589   * @since 6.0.0
1590   */
1591  function wp_schedule_update_user_counts() {
1592      if ( ! is_main_site() ) {
1593          return;
1594      }
1595  
1596      if ( ! wp_next_scheduled( 'wp_update_user_counts' ) && ! wp_installing() ) {
1597          wp_schedule_event( time(), 'twicedaily', 'wp_update_user_counts' );
1598      }
1599  }
1600  
1601  /**
1602   * Determines whether the site has a large number of users.
1603   *
1604   * The default criteria for a large site is more than 10,000 users.
1605   *
1606   * @since 6.0.0
1607   *
1608   * @param int|null $network_id ID of the network. Defaults to the current network.
1609   * @return bool Whether the site has a large number of users.
1610   */
1611  function wp_is_large_user_count( $network_id = null ) {
1612      if ( ! is_multisite() && null !== $network_id ) {
1613          _doing_it_wrong(
1614              __FUNCTION__,
1615              sprintf(
1616                  /* translators: %s: $network_id */
1617                  __( 'Unable to pass %s if not using multisite.' ),
1618                  '<code>$network_id</code>'
1619              ),
1620              '6.0.0'
1621          );
1622      }
1623  
1624      $count = get_user_count( $network_id );
1625  
1626      /**
1627       * Filters whether the site is considered large, based on its number of users.
1628       *
1629       * @since 6.0.0
1630       *
1631       * @param bool     $is_large_user_count Whether the site has a large number of users.
1632       * @param int      $count               The total number of users.
1633       * @param int|null $network_id          ID of the network. `null` represents the current network.
1634       */
1635      return apply_filters( 'wp_is_large_user_count', $count > 10000, $count, $network_id );
1636  }
1637  
1638  //
1639  // Private helper functions.
1640  //
1641  
1642  /**
1643   * Sets up global user vars.
1644   *
1645   * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
1646   *
1647   * @since 2.0.4
1648   *
1649   * @global string  $user_login    The user username for logging in
1650   * @global WP_User $userdata      User data.
1651   * @global int     $user_level    The level of the user
1652   * @global int     $user_ID       The ID of the user
1653   * @global string  $user_email    The email address of the user
1654   * @global string  $user_url      The url in the user's profile
1655   * @global string  $user_identity The display name of the user
1656   *
1657   * @param int $for_user_id Optional. User ID to set up global data. Default 0.
1658   */
1659  function setup_userdata( $for_user_id = 0 ) {
1660      global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
1661  
1662      if ( ! $for_user_id ) {
1663          $for_user_id = get_current_user_id();
1664      }
1665      $user = get_userdata( $for_user_id );
1666  
1667      if ( ! $user ) {
1668          $user_ID       = 0;
1669          $user_level    = 0;
1670          $userdata      = null;
1671          $user_login    = '';
1672          $user_email    = '';
1673          $user_url      = '';
1674          $user_identity = '';
1675          return;
1676      }
1677  
1678      $user_ID       = (int) $user->ID;
1679      $user_level    = (int) $user->user_level;
1680      $userdata      = $user;
1681      $user_login    = $user->user_login;
1682      $user_email    = $user->user_email;
1683      $user_url      = $user->user_url;
1684      $user_identity = $user->display_name;
1685  }
1686  
1687  /**
1688   * Creates dropdown HTML content of users.
1689   *
1690   * The content can either be displayed, which it is by default, or retrieved by
1691   * setting the 'echo' argument to false. The 'include' and 'exclude' arguments
1692   * are optional; if they are not specified, all users will be displayed. Only one
1693   * can be used in a single call, either 'include' or 'exclude', but not both.
1694   *
1695   * @since 2.3.0
1696   * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
1697   * @since 4.7.0 Added the 'role', 'role__in', and 'role__not_in' parameters.
1698   * @since 5.9.0 Added the 'capability', 'capability__in', and 'capability__not_in' parameters.
1699   *              Deprecated the 'who' parameter.
1700   *
1701   * @param array|string $args {
1702   *     Optional. Array or string of arguments to generate a drop-down of users.
1703   *     See WP_User_Query::prepare_query() for additional available arguments.
1704   *
1705   *     @type string          $show_option_all         Text to show as the drop-down default (all).
1706   *                                                    Default empty.
1707   *     @type string          $show_option_none        Text to show as the drop-down default when no
1708   *                                                    users were found. Default empty.
1709   *     @type int|string      $option_none_value       Value to use for `$show_option_none` when no users
1710   *                                                    were found. Default -1.
1711   *     @type string          $hide_if_only_one_author Whether to skip generating the drop-down
1712   *                                                    if only one user was found. Default empty.
1713   *     @type string          $orderby                 Field to order found users by. Accepts user fields.
1714   *                                                    Default 'display_name'.
1715   *     @type string          $order                   Whether to order users in ascending or descending
1716   *                                                    order. Accepts 'ASC' (ascending) or 'DESC' (descending).
1717   *                                                    Default 'ASC'.
1718   *     @type int[]|string    $include                 Array or comma-separated list of user IDs to include.
1719   *                                                    Default empty.
1720   *     @type int[]|string    $exclude                 Array or comma-separated list of user IDs to exclude.
1721   *                                                    Default empty.
1722   *     @type bool|int        $multi                   Whether to skip the ID attribute on the 'select' element.
1723   *                                                    Accepts 1|true or 0|false. Default 0|false.
1724   *     @type string          $show                    User data to display. If the selected item is empty
1725   *                                                    then the 'user_login' will be displayed in parentheses.
1726   *                                                    Accepts any user field, or 'display_name_with_login' to show
1727   *                                                    the display name with user_login in parentheses.
1728   *                                                    Default 'display_name'.
1729   *     @type int|bool        $echo                    Whether to echo or return the drop-down. Accepts 1|true (echo)
1730   *                                                    or 0|false (return). Default 1|true.
1731   *     @type int             $selected                Which user ID should be selected. Default 0.
1732   *     @type bool            $include_selected        Whether to always include the selected user ID in the drop-
1733   *                                                    down. Default false.
1734   *     @type string          $name                    Name attribute of select element. Default 'user'.
1735   *     @type string          $id                      ID attribute of the select element. Default is the value of `$name`.
1736   *     @type string          $class                   Class attribute of the select element. Default empty.
1737   *     @type int             $blog_id                 ID of blog (Multisite only). Default is ID of the current blog.
1738   *     @type string          $who                     Deprecated, use `$capability` instead.
1739   *                                                    Which type of users to query. Accepts only an empty string or
1740   *                                                    'authors'. Default empty (all users).
1741   *     @type string|string[] $role                    An array or a comma-separated list of role names that users
1742   *                                                    must match to be included in results. Note that this is
1743   *                                                    an inclusive list: users must match *each* role. Default empty.
1744   *     @type string[]        $role__in                An array of role names. Matched users must have at least one
1745   *                                                    of these roles. Default empty array.
1746   *     @type string[]        $role__not_in            An array of role names to exclude. Users matching one or more
1747   *                                                    of these roles will not be included in results. Default empty array.
1748   *     @type string|string[] $capability              An array or a comma-separated list of capability names that users
1749   *                                                    must match to be included in results. Note that this is
1750   *                                                    an inclusive list: users must match *each* capability.
1751   *                                                    Does NOT work for capabilities not in the database or filtered
1752   *                                                    via {@see 'map_meta_cap'}. Default empty.
1753   *     @type string[]        $capability__in          An array of capability names. Matched users must have at least one
1754   *                                                    of these capabilities.
1755   *                                                    Does NOT work for capabilities not in the database or filtered
1756   *                                                    via {@see 'map_meta_cap'}. Default empty array.
1757   *     @type string[]        $capability__not_in      An array of capability names to exclude. Users matching one or more
1758   *                                                    of these capabilities will not be included in results.
1759   *                                                    Does NOT work for capabilities not in the database or filtered
1760   *                                                    via {@see 'map_meta_cap'}. Default empty array.
1761   * }
1762   * @return string HTML dropdown list of users.
1763   */
1764  function wp_dropdown_users( $args = '' ) {
1765      $defaults = array(
1766          'show_option_all'         => '',
1767          'show_option_none'        => '',
1768          'hide_if_only_one_author' => '',
1769          'orderby'                 => 'display_name',
1770          'order'                   => 'ASC',
1771          'include'                 => '',
1772          'exclude'                 => '',
1773          'multi'                   => 0,
1774          'show'                    => 'display_name',
1775          'echo'                    => 1,
1776          'selected'                => 0,
1777          'name'                    => 'user',
1778          'class'                   => '',
1779          'id'                      => '',
1780          'blog_id'                 => get_current_blog_id(),
1781          'who'                     => '',
1782          'include_selected'        => false,
1783          'option_none_value'       => -1,
1784          'role'                    => '',
1785          'role__in'                => array(),
1786          'role__not_in'            => array(),
1787          'capability'              => '',
1788          'capability__in'          => array(),
1789          'capability__not_in'      => array(),
1790      );
1791  
1792      $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
1793  
1794      $parsed_args = wp_parse_args( $args, $defaults );
1795  
1796      $query_args = wp_array_slice_assoc(
1797          $parsed_args,
1798          array(
1799              'blog_id',
1800              'include',
1801              'exclude',
1802              'orderby',
1803              'order',
1804              'who',
1805              'role',
1806              'role__in',
1807              'role__not_in',
1808              'capability',
1809              'capability__in',
1810              'capability__not_in',
1811          )
1812      );
1813  
1814      $fields = array( 'ID', 'user_login' );
1815  
1816      $show = ! empty( $parsed_args['show'] ) ? $parsed_args['show'] : 'display_name';
1817      if ( 'display_name_with_login' === $show ) {
1818          $fields[] = 'display_name';
1819      } else {
1820          $fields[] = $show;
1821      }
1822  
1823      $query_args['fields'] = $fields;
1824  
1825      $show_option_all   = $parsed_args['show_option_all'];
1826      $show_option_none  = $parsed_args['show_option_none'];
1827      $option_none_value = $parsed_args['option_none_value'];
1828  
1829      /**
1830       * Filters the query arguments for the list of users in the dropdown.
1831       *
1832       * @since 4.4.0
1833       *
1834       * @param array $query_args  The query arguments for get_users().
1835       * @param array $parsed_args The arguments passed to wp_dropdown_users() combined with the defaults.
1836       */
1837      $query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $parsed_args );
1838  
1839      $users = get_users( $query_args );
1840  
1841      $output = '';
1842      if ( ! empty( $users ) && ( empty( $parsed_args['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
1843          $name = esc_attr( $parsed_args['name'] );
1844          if ( $parsed_args['multi'] && ! $parsed_args['id'] ) {
1845              $id = '';
1846          } else {
1847              $id = $parsed_args['id'] ? " id='" . esc_attr( $parsed_args['id'] ) . "'" : " id='$name'";
1848          }
1849          $output = "<select name='{$name}'{$id} class='" . $parsed_args['class'] . "'>\n";
1850  
1851          if ( $show_option_all ) {
1852              $output .= "\t<option value='0'>$show_option_all</option>\n";
1853          }
1854  
1855          if ( $show_option_none ) {
1856              $_selected = selected( $option_none_value, $parsed_args['selected'], false );
1857              $output   .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
1858          }
1859  
1860          if ( $parsed_args['include_selected'] && ( $parsed_args['selected'] > 0 ) ) {
1861              $found_selected          = false;
1862              $parsed_args['selected'] = (int) $parsed_args['selected'];
1863  
1864              foreach ( (array) $users as $user ) {
1865                  $user->ID = (int) $user->ID;
1866                  if ( $user->ID === $parsed_args['selected'] ) {
1867                      $found_selected = true;
1868                  }
1869              }
1870  
1871              if ( ! $found_selected ) {
1872                  $selected_user = get_userdata( $parsed_args['selected'] );
1873                  if ( $selected_user ) {
1874                      $users[] = $selected_user;
1875                  }
1876              }
1877          }
1878  
1879          foreach ( (array) $users as $user ) {
1880              if ( 'display_name_with_login' === $show ) {
1881                  /* translators: 1: User's display name, 2: User login. */
1882                  $display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
1883              } elseif ( ! empty( $user->$show ) ) {
1884                  $display = $user->$show;
1885              } else {
1886                  $display = '(' . $user->user_login . ')';
1887              }
1888  
1889              $_selected = selected( $user->ID, $parsed_args['selected'], false );
1890              $output   .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
1891          }
1892  
1893          $output .= '</select>';
1894      }
1895  
1896      /**
1897       * Filters the wp_dropdown_users() HTML output.
1898       *
1899       * @since 2.3.0
1900       *
1901       * @param string $output HTML output generated by wp_dropdown_users().
1902       */
1903      $html = apply_filters( 'wp_dropdown_users', $output );
1904  
1905      if ( $parsed_args['echo'] ) {
1906          echo $html;
1907      }
1908      return $html;
1909  }
1910  
1911  /**
1912   * Sanitizes user field based on context.
1913   *
1914   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1915   * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1916   * when calling filters.
1917   *
1918   * @since 2.3.0
1919   *
1920   * @param string $field   The user Object field name.
1921   * @param mixed  $value   The user Object value.
1922   * @param int    $user_id User ID.
1923   * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1924   *                        'attribute' and 'js'.
1925   * @return mixed Sanitized value.
1926   */
1927  function sanitize_user_field( $field, $value, $user_id, $context ) {
1928      $int_fields = array( 'ID' );
1929      if ( in_array( $field, $int_fields, true ) ) {
1930          $value = (int) $value;
1931      }
1932  
1933      if ( 'raw' === $context ) {
1934          return $value;
1935      }
1936  
1937      if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
1938          return $value;
1939      }
1940  
1941      $prefixed = str_contains( $field, 'user_' );
1942  
1943      if ( 'edit' === $context ) {
1944          if ( $prefixed ) {
1945  
1946              /** This filter is documented in wp-includes/post.php */
1947              $value = apply_filters( "edit_{$field}", $value, $user_id );
1948          } else {
1949  
1950              /**
1951               * Filters a user field value in the 'edit' context.
1952               *
1953               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1954               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1955               *
1956               * @since 2.9.0
1957               *
1958               * @param mixed $value   Value of the prefixed user field.
1959               * @param int   $user_id User ID.
1960               */
1961              $value = apply_filters( "edit_user_{$field}", $value, $user_id );
1962          }
1963  
1964          if ( 'description' === $field ) {
1965              $value = esc_html( $value ); // textarea_escaped?
1966          } else {
1967              $value = esc_attr( $value );
1968          }
1969      } elseif ( 'db' === $context ) {
1970          if ( $prefixed ) {
1971              /** This filter is documented in wp-includes/post.php */
1972              $value = apply_filters( "pre_{$field}", $value );
1973          } else {
1974  
1975              /**
1976               * Filters the value of a user field in the 'db' context.
1977               *
1978               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1979               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1980               *
1981               * @since 2.9.0
1982               *
1983               * @param mixed $value Value of the prefixed user field.
1984               */
1985              $value = apply_filters( "pre_user_{$field}", $value );
1986          }
1987      } else {
1988          // Use display filters by default.
1989          if ( $prefixed ) {
1990  
1991              /** This filter is documented in wp-includes/post.php */
1992              $value = apply_filters( "{$field}", $value, $user_id, $context );
1993          } else {
1994  
1995              /**
1996               * Filters the value of a user field in a standard context.
1997               *
1998               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1999               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
2000               *
2001               * @since 2.9.0
2002               *
2003               * @param mixed  $value   The user object value to sanitize.
2004               * @param int    $user_id User ID.
2005               * @param string $context The context to filter within.
2006               */
2007              $value = apply_filters( "user_{$field}", $value, $user_id, $context );
2008          }
2009      }
2010  
2011      if ( 'user_url' === $field ) {
2012          $value = esc_url( $value );
2013      }
2014  
2015      if ( 'attribute' === $context ) {
2016          $value = esc_attr( $value );
2017      } elseif ( 'js' === $context ) {
2018          $value = esc_js( $value );
2019      }
2020  
2021      // Restore the type for integer fields after esc_attr().
2022      if ( in_array( $field, $int_fields, true ) ) {
2023          $value = (int) $value;
2024      }
2025  
2026      return $value;
2027  }
2028  
2029  /**
2030   * Updates all user caches.
2031   *
2032   * @since 3.0.0
2033   *
2034   * @param object|WP_User $user User object or database row to be cached
2035   * @return void|false Void on success, false on failure.
2036   */
2037  function update_user_caches( $user ) {
2038      if ( $user instanceof WP_User ) {
2039          if ( ! $user->exists() ) {
2040              return false;
2041          }
2042  
2043          $user = $user->data;
2044      }
2045  
2046      wp_cache_add( $user->ID, $user, 'users' );
2047      wp_cache_add( $user->user_login, $user->ID, 'userlogins' );
2048      wp_cache_add( $user->user_nicename, $user->ID, 'userslugs' );
2049  
2050      if ( ! empty( $user->user_email ) ) {
2051          wp_cache_add( $user->user_email, $user->ID, 'useremail' );
2052      }
2053  }
2054  
2055  /**
2056   * Cleans all user caches.
2057   *
2058   * @since 3.0.0
2059   * @since 4.4.0 'clean_user_cache' action was added.
2060   * @since 6.2.0 User metadata caches are now cleared.
2061   *
2062   * @param WP_User|int $user User object or ID to be cleaned from the cache
2063   */
2064  function clean_user_cache( $user ) {
2065      if ( is_numeric( $user ) ) {
2066          $user = new WP_User( $user );
2067      }
2068  
2069      if ( ! $user->exists() ) {
2070          return;
2071      }
2072  
2073      wp_cache_delete( $user->ID, 'users' );
2074      wp_cache_delete( $user->user_login, 'userlogins' );
2075      wp_cache_delete( $user->user_nicename, 'userslugs' );
2076  
2077      if ( ! empty( $user->user_email ) ) {
2078          wp_cache_delete( $user->user_email, 'useremail' );
2079      }
2080  
2081      wp_cache_delete( $user->ID, 'user_meta' );
2082      wp_cache_set_users_last_changed();
2083  
2084      /**
2085       * Fires immediately after the given user's cache is cleaned.
2086       *
2087       * @since 4.4.0
2088       *
2089       * @param int     $user_id User ID.
2090       * @param WP_User $user    User object.
2091       */
2092      do_action( 'clean_user_cache', $user->ID, $user );
2093  }
2094  
2095  /**
2096   * Determines whether the given username exists.
2097   *
2098   * For more information on this and similar theme functions, check out
2099   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
2100   * Conditional Tags} article in the Theme Developer Handbook.
2101   *
2102   * @since 2.0.0
2103   *
2104   * @param string $username The username to check for existence.
2105   * @return int|false The user ID on success, false on failure.
2106   */
2107  function username_exists( $username ) {
2108      $user = get_user_by( 'login', $username );
2109      if ( $user ) {
2110          $user_id = $user->ID;
2111      } else {
2112          $user_id = false;
2113      }
2114  
2115      /**
2116       * Filters whether the given username exists.
2117       *
2118       * @since 4.9.0
2119       *
2120       * @param int|false $user_id  The user ID associated with the username,
2121       *                            or false if the username does not exist.
2122       * @param string    $username The username to check for existence.
2123       */
2124      return apply_filters( 'username_exists', $user_id, $username );
2125  }
2126  
2127  /**
2128   * Determines whether the given email exists.
2129   *
2130   * For more information on this and similar theme functions, check out
2131   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
2132   * Conditional Tags} article in the Theme Developer Handbook.
2133   *
2134   * @since 2.1.0
2135   *
2136   * @param string $email The email to check for existence.
2137   * @return int|false The user ID on success, false on failure.
2138   */
2139  function email_exists( $email ) {
2140      $user = get_user_by( 'email', $email );
2141      if ( $user ) {
2142          $user_id = $user->ID;
2143      } else {
2144          $user_id = false;
2145      }
2146  
2147      /**
2148       * Filters whether the given email exists.
2149       *
2150       * @since 5.6.0
2151       *
2152       * @param int|false $user_id The user ID associated with the email,
2153       *                           or false if the email does not exist.
2154       * @param string    $email   The email to check for existence.
2155       */
2156      return apply_filters( 'email_exists', $user_id, $email );
2157  }
2158  
2159  /**
2160   * Checks whether a username is valid.
2161   *
2162   * @since 2.0.1
2163   * @since 4.4.0 Empty sanitized usernames are now considered invalid.
2164   *
2165   * @param string $username Username.
2166   * @return bool Whether username given is valid.
2167   */
2168  function validate_username( $username ) {
2169      $sanitized = sanitize_user( $username, true );
2170      $valid     = ( $sanitized === $username && ! empty( $sanitized ) );
2171  
2172      /**
2173       * Filters whether the provided username is valid.
2174       *
2175       * @since 2.0.1
2176       *
2177       * @param bool   $valid    Whether given username is valid.
2178       * @param string $username Username to check.
2179       */
2180      return apply_filters( 'validate_username', $valid, $username );
2181  }
2182  
2183  /**
2184   * Inserts a user into the database.
2185   *
2186   * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
2187   * 'ID', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl',
2188   * 'user_registered', 'user_activation_key', 'spam', and 'role'. The filters have the prefix
2189   * 'pre_user_' followed by the field name. An example using 'description' would have the filter
2190   * called 'pre_user_description' that can be hooked into.
2191   *
2192   * @since 2.0.0
2193   * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
2194   *              methods for new installations. See wp_get_user_contact_methods().
2195   * @since 4.7.0 The `locale` field can be passed to `$userdata`.
2196   * @since 5.3.0 The `user_activation_key` field can be passed to `$userdata`.
2197   * @since 5.3.0 The `spam` field can be passed to `$userdata` (Multisite only).
2198   * @since 5.9.0 The `meta_input` field can be passed to `$userdata` to allow addition of user meta data.
2199   *
2200   * @global wpdb $wpdb WordPress database abstraction object.
2201   *
2202   * @param array|object|WP_User $userdata {
2203   *     An array, object, or WP_User object of user data arguments.
2204   *
2205   *     @type int    $ID                   User ID. If supplied, the user will be updated.
2206   *     @type string $user_pass            The plain-text user password for new users.
2207   *                                        Hashed password for existing users.
2208   *     @type string $user_login           The user's login username.
2209   *     @type string $user_nicename        The URL-friendly user name.
2210   *     @type string $user_url             The user URL.
2211   *     @type string $user_email           The user email address.
2212   *     @type string $display_name         The user's display name.
2213   *                                        Default is the user's username.
2214   *     @type string $nickname             The user's nickname.
2215   *                                        Default is the user's username.
2216   *     @type string $first_name           The user's first name. For new users, will be used
2217   *                                        to build the first part of the user's display name
2218   *                                        if `$display_name` is not specified.
2219   *     @type string $last_name            The user's last name. For new users, will be used
2220   *                                        to build the second part of the user's display name
2221   *                                        if `$display_name` is not specified.
2222   *     @type string $description          The user's biographical description.
2223   *     @type string $rich_editing         Whether to enable the rich-editor for the user.
2224   *                                        Accepts 'true' or 'false' as a string literal,
2225   *                                        not boolean. Default 'true'.
2226   *     @type string $syntax_highlighting  Whether to enable the rich code editor for the user.
2227   *                                        Accepts 'true' or 'false' as a string literal,
2228   *                                        not boolean. Default 'true'.
2229   *     @type string $comment_shortcuts    Whether to enable comment moderation keyboard
2230   *                                        shortcuts for the user. Accepts 'true' or 'false'
2231   *                                        as a string literal, not boolean. Default 'false'.
2232   *     @type string $admin_color          Admin color scheme for the user. Default 'modern'.
2233   *     @type bool   $use_ssl              Whether the user should always access the admin over
2234   *                                        https. Default false.
2235   *     @type string $user_registered      Date the user registered in UTC. Format is 'Y-m-d H:i:s'.
2236   *     @type string $user_activation_key  Password reset key. Default empty.
2237   *     @type bool   $spam                 Multisite only. Whether the user is marked as spam.
2238   *                                        Default false.
2239   *     @type string $show_admin_bar_front Whether to display the Admin Bar for the user
2240   *                                        on the site's front end. Accepts 'true' or 'false'
2241   *                                        as a string literal, not boolean. Default 'true'.
2242   *     @type string $role                 User's role.
2243   *     @type string $locale               User's locale. Default empty.
2244   *     @type array  $meta_input           Array of custom user meta values keyed by meta key.
2245   *                                        Default empty.
2246   * }
2247   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
2248   *                      be created.
2249   */
2250  function wp_insert_user( $userdata ) {
2251      global $wpdb;
2252  
2253      if ( $userdata instanceof stdClass ) {
2254          $userdata = get_object_vars( $userdata );
2255      } elseif ( $userdata instanceof WP_User ) {
2256          $userdata = $userdata->to_array();
2257      } elseif ( $userdata instanceof Traversable ) {
2258          $userdata = iterator_to_array( $userdata );
2259      } elseif ( $userdata instanceof ArrayAccess ) {
2260          $userdata_obj = $userdata;
2261          $userdata     = array();
2262          foreach (
2263              array(
2264                  'ID',
2265                  'user_pass',
2266                  'user_login',
2267                  'user_nicename',
2268                  'user_url',
2269                  'user_email',
2270                  'display_name',
2271                  'nickname',
2272                  'first_name',
2273                  'last_name',
2274                  'description',
2275                  'rich_editing',
2276                  'syntax_highlighting',
2277                  'infinite_scrolling',
2278                  'comment_shortcuts',
2279                  'admin_color',
2280                  'use_ssl',
2281                  'user_registered',
2282                  'user_activation_key',
2283                  'spam',
2284                  'show_admin_bar_front',
2285                  'role',
2286                  'locale',
2287                  'meta_input',
2288              ) as $key
2289          ) {
2290              if ( isset( $userdata_obj[ $key ] ) ) {
2291                  $userdata[ $key ] = $userdata_obj[ $key ];
2292              }
2293          }
2294      } else {
2295          $userdata = (array) $userdata;
2296      }
2297  
2298      // Are we updating or creating?
2299      if ( ! empty( $userdata['ID'] ) ) {
2300          $user_id       = (int) $userdata['ID'];
2301          $update        = true;
2302          $old_user_data = get_userdata( $user_id );
2303  
2304          if ( ! $old_user_data ) {
2305              return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2306          }
2307  
2308          // Slash current user email to compare it later with slashed new user email.
2309          $old_user_data->user_email = wp_slash( $old_user_data->user_email );
2310  
2311          // Hashed in wp_update_user(), plaintext if called directly.
2312          $user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
2313      } else {
2314          $update = false;
2315  
2316          if ( empty( $userdata['user_pass'] ) ) {
2317              wp_trigger_error(
2318                  __FUNCTION__,
2319                  __( 'The user_pass field is required when creating a new user. The user will need to reset their password before logging in.' ),
2320                  E_USER_WARNING
2321              );
2322  
2323              // Set the password as an empty string to force the password reset flow.
2324              $userdata['user_pass'] = '';
2325          }
2326  
2327          // Hash the password.
2328          $user_pass = wp_hash_password( $userdata['user_pass'] );
2329      }
2330  
2331      $sanitized_user_login = sanitize_user( $userdata['user_login'] ?? '', true );
2332  
2333      /**
2334       * Filters a username after it has been sanitized.
2335       *
2336       * This filter is called before the user is created or updated.
2337       *
2338       * @since 2.0.3
2339       *
2340       * @param string $sanitized_user_login Username after it has been sanitized.
2341       */
2342      $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
2343  
2344      // Remove any non-printable chars from the login string to see if we have ended up with an empty username.
2345      $user_login = trim( $pre_user_login );
2346  
2347      // user_login must be between 0 and 60 characters.
2348      if ( empty( $user_login ) ) {
2349          return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
2350      } elseif ( mb_strlen( $user_login ) > 60 ) {
2351          return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
2352      }
2353  
2354      if ( ! $update && username_exists( $user_login ) ) {
2355          return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
2356      }
2357  
2358      /**
2359       * Filters the list of disallowed usernames.
2360       *
2361       * @since 4.4.0
2362       *
2363       * @param array $usernames Array of disallowed usernames.
2364       */
2365      $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
2366  
2367      if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
2368          return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
2369      }
2370  
2371      /*
2372       * If a nicename is provided, remove unsafe user characters before using it.
2373       * Otherwise build a nicename from the user_login.
2374       */
2375      if ( ! empty( $userdata['user_nicename'] ) ) {
2376          $user_nicename = sanitize_user( $userdata['user_nicename'], true );
2377      } else {
2378          $user_nicename = mb_substr( $user_login, 0, 50 );
2379      }
2380  
2381      $user_nicename = sanitize_title( $user_nicename );
2382  
2383      /**
2384       * Filters a user's nicename before the user is created or updated.
2385       *
2386       * @since 2.0.3
2387       *
2388       * @param string $user_nicename The user's nicename.
2389       */
2390      $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
2391  
2392      // Check if the sanitized nicename is empty.
2393      if ( empty( $user_nicename ) ) {
2394          return new WP_Error( 'empty_user_nicename', __( 'Cannot create a user with an empty nicename.' ) );
2395      } elseif ( mb_strlen( $user_nicename ) > 50 ) {
2396          return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
2397      }
2398  
2399      $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 ) );
2400  
2401      if ( $user_nicename_check ) {
2402          $suffix = 2;
2403          while ( $user_nicename_check ) {
2404              // user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
2405              $base_length         = 49 - mb_strlen( $suffix );
2406              $alt_user_nicename   = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
2407              $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 ) );
2408              ++$suffix;
2409          }
2410          $user_nicename = $alt_user_nicename;
2411      }
2412  
2413      $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
2414  
2415      /**
2416       * Filters a user's email before the user is created or updated.
2417       *
2418       * @since 2.0.3
2419       *
2420       * @param string $raw_user_email The user's email.
2421       */
2422      $user_email = apply_filters( 'pre_user_email', $raw_user_email );
2423  
2424      /*
2425       * If there is no update, just check for `email_exists`. If there is an update,
2426       * check if current email and new email are the same, and check `email_exists`
2427       * accordingly.
2428       */
2429      if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
2430          && ! defined( 'WP_IMPORTING' )
2431          && email_exists( $user_email )
2432      ) {
2433          return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
2434      }
2435  
2436      $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
2437  
2438      /**
2439       * Filters a user's URL before the user is created or updated.
2440       *
2441       * @since 2.0.3
2442       *
2443       * @param string $raw_user_url The user's URL.
2444       */
2445      $user_url = apply_filters( 'pre_user_url', $raw_user_url );
2446  
2447      if ( mb_strlen( $user_url ) > 100 ) {
2448          return new WP_Error( 'user_url_too_long', __( 'User URL may not be longer than 100 characters.' ) );
2449      }
2450  
2451      $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
2452  
2453      $user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];
2454  
2455      if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
2456          return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
2457      }
2458  
2459      $spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];
2460  
2461      // Store values to save in user meta.
2462      $meta = array();
2463  
2464      $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
2465  
2466      /**
2467       * Filters a user's nickname before the user is created or updated.
2468       *
2469       * @since 2.0.3
2470       *
2471       * @param string $nickname The user's nickname.
2472       */
2473      $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
2474  
2475      $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
2476  
2477      /**
2478       * Filters a user's first name before the user is created or updated.
2479       *
2480       * @since 2.0.3
2481       *
2482       * @param string $first_name The user's first name.
2483       */
2484      $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
2485  
2486      $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
2487  
2488      /**
2489       * Filters a user's last name before the user is created or updated.
2490       *
2491       * @since 2.0.3
2492       *
2493       * @param string $last_name The user's last name.
2494       */
2495      $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
2496  
2497      if ( empty( $userdata['display_name'] ) ) {
2498          if ( $update ) {
2499              $display_name = $user_login;
2500          } elseif ( $meta['first_name'] && $meta['last_name'] ) {
2501              $display_name = sprintf(
2502                  /* translators: 1: User's first name, 2: Last name. */
2503                  _x( '%1$s %2$s', 'Display name based on first name and last name' ),
2504                  $meta['first_name'],
2505                  $meta['last_name']
2506              );
2507          } elseif ( $meta['first_name'] ) {
2508              $display_name = $meta['first_name'];
2509          } elseif ( $meta['last_name'] ) {
2510              $display_name = $meta['last_name'];
2511          } else {
2512              $display_name = $user_login;
2513          }
2514      } else {
2515          $display_name = $userdata['display_name'];
2516      }
2517  
2518      /**
2519       * Filters a user's display name before the user is created or updated.
2520       *
2521       * @since 2.0.3
2522       *
2523       * @param string $display_name The user's display name.
2524       */
2525      $display_name = apply_filters( 'pre_user_display_name', $display_name );
2526  
2527      $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
2528  
2529      /**
2530       * Filters a user's description before the user is created or updated.
2531       *
2532       * @since 2.0.3
2533       *
2534       * @param string $description The user's description.
2535       */
2536      $meta['description'] = apply_filters( 'pre_user_description', $description );
2537  
2538      $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
2539  
2540      $meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];
2541  
2542      $meta['infinite_scrolling'] = empty( $userdata['infinite_scrolling'] ) ? 'true' : $userdata['infinite_scrolling'];
2543  
2544      $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
2545  
2546      $admin_color         = empty( $userdata['admin_color'] ) ? 'modern' : $userdata['admin_color'];
2547      $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
2548  
2549      $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? '0' : '1';
2550  
2551      $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
2552  
2553      $meta['locale'] = $userdata['locale'] ?? '';
2554  
2555      $compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
2556      $data      = wp_unslash( $compacted );
2557  
2558      if ( ! $update ) {
2559          $data = $data + compact( 'user_login' );
2560      }
2561  
2562      if ( is_multisite() ) {
2563          $data = $data + compact( 'spam' );
2564      }
2565  
2566      /**
2567       * Filters user data before the record is created or updated.
2568       *
2569       * It only includes data in the users table, not any user metadata.
2570       *
2571       * @since 4.9.0
2572       * @since 5.8.0 The `$userdata` parameter was added.
2573       * @since 6.8.0 The user's password is now hashed using bcrypt by default instead of phpass.
2574       *
2575       * @param array    $data {
2576       *     Values and keys for the user.
2577       *
2578       *     @type string $user_login      The user's login. Only included if $update == false
2579       *     @type string $user_pass       The user's password.
2580       *     @type string $user_email      The user's email.
2581       *     @type string $user_url        The user's url.
2582       *     @type string $user_nicename   The user's nice name. Defaults to a URL-safe version of user's login.
2583       *     @type string $display_name    The user's display name.
2584       *     @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
2585       *                                   the current UTC timestamp.
2586       * }
2587       * @param bool     $update   Whether the user is being updated rather than created.
2588       * @param int|null $user_id  ID of the user to be updated, or NULL if the user is being created.
2589       * @param array    $userdata The raw array of data passed to wp_insert_user().
2590       */
2591      $data = apply_filters( 'wp_pre_insert_user_data', $data, $update, ( $update ? $user_id : null ), $userdata );
2592  
2593      if ( empty( $data ) || ! is_array( $data ) ) {
2594          return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
2595      }
2596  
2597      if ( $update ) {
2598          if ( $user_email !== $old_user_data->user_email || $user_pass !== $old_user_data->user_pass ) {
2599              $data['user_activation_key'] = '';
2600          }
2601          $wpdb->update( $wpdb->users, $data, array( 'ID' => $user_id ) );
2602      } else {
2603          $wpdb->insert( $wpdb->users, $data );
2604          $user_id = (int) $wpdb->insert_id;
2605      }
2606  
2607      $user = new WP_User( $user_id );
2608  
2609      if ( ! $update ) {
2610          /** This action is documented in wp-includes/pluggable.php */
2611          do_action( 'wp_set_password', $userdata['user_pass'], $user_id, $user );
2612      }
2613  
2614      /**
2615       * Filters a user's meta values and keys immediately after the user is created or updated
2616       * and before any user meta is inserted or updated.
2617       *
2618       * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
2619       *
2620       * For custom meta fields, see the {@see 'insert_custom_user_meta'} filter.
2621       *
2622       * @since 4.4.0
2623       * @since 5.8.0 The `$userdata` parameter was added.
2624       *
2625       * @param array   $meta {
2626       *     Default meta values and keys for the user.
2627       *
2628       *     @type string   $nickname             The user's nickname. Default is the user's username.
2629       *     @type string   $first_name           The user's first name.
2630       *     @type string   $last_name            The user's last name.
2631       *     @type string   $description          The user's description.
2632       *     @type string   $rich_editing         Whether to enable the rich-editor for the user. Default 'true'.
2633       *     @type string   $syntax_highlighting  Whether to enable the rich code editor for the user. Default 'true'.
2634       *     @type string   $comment_shortcuts    Whether to enable keyboard shortcuts for the user. Default 'false'.
2635       *     @type string   $admin_color          The color scheme for a user's admin screen. Default 'modern'.
2636       *     @type int|bool $use_ssl              Whether to force SSL on the user's admin area. 0|false if SSL
2637       *                                          is not forced.
2638       *     @type string   $show_admin_bar_front Whether to show the admin bar on the front end for the user.
2639       *                                          Default 'true'.
2640       *     @type string   $locale               User's locale. Default empty.
2641       * }
2642       * @param WP_User $user     User object.
2643       * @param bool    $update   Whether the user is being updated rather than created.
2644       * @param array   $userdata The raw array of data passed to wp_insert_user().
2645       */
2646      $meta = apply_filters( 'insert_user_meta', $meta, $user, $update, $userdata );
2647  
2648      $custom_meta = array();
2649      if ( array_key_exists( 'meta_input', $userdata ) && is_array( $userdata['meta_input'] ) && ! empty( $userdata['meta_input'] ) ) {
2650          $custom_meta = $userdata['meta_input'];
2651      }
2652  
2653      /**
2654       * Filters a user's custom meta values and keys immediately after the user is created or updated
2655       * and before any user meta is inserted or updated.
2656       *
2657       * For non-custom meta fields, see the {@see 'insert_user_meta'} filter.
2658       *
2659       * @since 5.9.0
2660       *
2661       * @param array   $custom_meta Array of custom user meta values keyed by meta key.
2662       * @param WP_User $user        User object.
2663       * @param bool    $update      Whether the user is being updated rather than created.
2664       * @param array   $userdata    The raw array of data passed to wp_insert_user().
2665       */
2666      $custom_meta = apply_filters( 'insert_custom_user_meta', $custom_meta, $user, $update, $userdata );
2667  
2668      $meta = array_merge( $meta, $custom_meta );
2669  
2670      if ( $update ) {
2671          // Update user meta.
2672          foreach ( $meta as $key => $value ) {
2673              update_user_meta( $user_id, $key, $value );
2674          }
2675      } else {
2676          // Add user meta.
2677          foreach ( $meta as $key => $value ) {
2678              add_user_meta( $user_id, $key, $value );
2679          }
2680      }
2681  
2682      foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
2683          if ( isset( $userdata[ $key ] ) ) {
2684              update_user_meta( $user_id, $key, $userdata[ $key ] );
2685          }
2686      }
2687  
2688      if ( isset( $userdata['role'] ) ) {
2689          $user->set_role( $userdata['role'] );
2690      } elseif ( ! $update ) {
2691          $user->set_role( get_option( 'default_role' ) );
2692      }
2693  
2694      clean_user_cache( $user_id );
2695  
2696      if ( $update ) {
2697          /**
2698           * Fires immediately after an existing user is updated.
2699           *
2700           * @since 2.0.0
2701           * @since 5.8.0 The `$userdata` parameter was added.
2702           *
2703           * @param int     $user_id       User ID.
2704           * @param WP_User $old_user_data Object containing user's data prior to update.
2705           * @param array   $userdata      The raw array of data passed to wp_insert_user().
2706           */
2707          do_action( 'profile_update', $user_id, $old_user_data, $userdata );
2708  
2709          if ( isset( $userdata['spam'] ) && $userdata['spam'] !== $old_user_data->spam ) {
2710              if ( '1' === $userdata['spam'] ) {
2711                  /**
2712                   * Fires after the user is marked as a SPAM user.
2713                   *
2714                   * @since 3.0.0
2715                   *
2716                   * @param int $user_id ID of the user marked as SPAM.
2717                   */
2718                  do_action( 'make_spam_user', $user_id );
2719              } else {
2720                  /**
2721                   * Fires after the user is marked as a HAM user. Opposite of SPAM.
2722                   *
2723                   * @since 3.0.0
2724                   *
2725                   * @param int $user_id ID of the user marked as HAM.
2726                   */
2727                  do_action( 'make_ham_user', $user_id );
2728              }
2729          }
2730      } else {
2731          /**
2732           * Fires immediately after a new user is registered.
2733           *
2734           * @since 1.5.0
2735           * @since 5.8.0 The `$userdata` parameter was added.
2736           *
2737           * @param int   $user_id  User ID.
2738           * @param array $userdata The raw array of data passed to wp_insert_user().
2739           */
2740          do_action( 'user_register', $user_id, $userdata );
2741      }
2742  
2743      return $user_id;
2744  }
2745  
2746  /**
2747   * Updates a user in the database.
2748   *
2749   * It is possible to update a user's password by specifying the 'user_pass'
2750   * value in the $userdata parameter array.
2751   *
2752   * If current user's password is being updated, then the cookies will be
2753   * cleared.
2754   *
2755   * @since 2.0.0
2756   *
2757   * @see wp_insert_user() For what fields can be set in $userdata.
2758   *
2759   * @param array|object|WP_User $userdata An array of user data or a user object of type stdClass or WP_User.
2760   * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
2761   */
2762  function wp_update_user( $userdata ) {
2763      if ( $userdata instanceof stdClass ) {
2764          $userdata = get_object_vars( $userdata );
2765      } elseif ( $userdata instanceof WP_User ) {
2766          $userdata = $userdata->to_array();
2767      }
2768  
2769      $userdata_raw = $userdata;
2770  
2771      $user_id = (int) ( $userdata['ID'] ?? 0 );
2772      if ( ! $user_id ) {
2773          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2774      }
2775  
2776      // First, get all of the original fields.
2777      $user_obj = get_userdata( $user_id );
2778      if ( ! $user_obj ) {
2779          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2780      }
2781  
2782      $user = $user_obj->to_array();
2783  
2784      // Add additional custom fields.
2785      foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
2786          $user[ $key ] = get_user_meta( $user_id, $key, true );
2787      }
2788  
2789      // Escape data pulled from DB.
2790      $user = add_magic_quotes( $user );
2791  
2792      if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
2793          // If password is changing, hash it now.
2794          $plaintext_pass        = $userdata['user_pass'];
2795          $userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
2796  
2797          /** This action is documented in wp-includes/pluggable.php */
2798          do_action( 'wp_set_password', $plaintext_pass, $user_id, $user_obj );
2799  
2800          /**
2801           * Filters whether to send the password change email.
2802           *
2803           * @since 4.3.0
2804           *
2805           * @see wp_insert_user() For `$user` and `$userdata` fields.
2806           *
2807           * @param bool  $send     Whether to send the email.
2808           * @param array $user     The original user array.
2809           * @param array $userdata The updated user array.
2810           */
2811          $send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
2812      }
2813  
2814      if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
2815          /**
2816           * Filters whether to send the email change email.
2817           *
2818           * @since 4.3.0
2819           *
2820           * @see wp_insert_user() For `$user` and `$userdata` fields.
2821           *
2822           * @param bool  $send     Whether to send the email.
2823           * @param array $user     The original user array.
2824           * @param array $userdata The updated user array.
2825           */
2826          $send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
2827      }
2828  
2829      clean_user_cache( $user_obj );
2830  
2831      // Merge old and new fields with new fields overwriting old ones.
2832      $userdata = array_merge( $user, $userdata );
2833      $user_id  = wp_insert_user( $userdata );
2834  
2835      if ( is_wp_error( $user_id ) ) {
2836          return $user_id;
2837      }
2838  
2839      $blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
2840  
2841      $switched_locale = false;
2842      if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
2843          $switched_locale = switch_to_user_locale( $user_id );
2844      }
2845  
2846      if ( ! empty( $send_password_change_email ) ) {
2847          /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2848          $pass_change_text = __(
2849              'Hi ###USERNAME###,
2850  
2851  This notice confirms that your password was changed on ###SITENAME###.
2852  
2853  If you did not change your password, please contact the Site Administrator at
2854  ###ADMIN_EMAIL###
2855  
2856  This email has been sent to ###EMAIL###
2857  
2858  Regards,
2859  All at ###SITENAME###
2860  ###SITEURL###'
2861          );
2862  
2863          $pass_change_email = array(
2864              'to'      => $user['user_email'],
2865              /* translators: Password change notification email subject. %s: Site title. */
2866              'subject' => __( '[%s] Password Changed' ),
2867              'message' => $pass_change_text,
2868              'headers' => '',
2869          );
2870  
2871          /**
2872           * Filters the contents of the email sent when the user's password is changed.
2873           *
2874           * @since 4.3.0
2875           *
2876           * @param array $pass_change_email {
2877           *     Used to build wp_mail().
2878           *
2879           *     @type string $to      The intended recipients. Add emails in a comma separated string.
2880           *     @type string $subject The subject of the email.
2881           *     @type string $message The content of the email.
2882           *         The following strings have a special meaning and will get replaced dynamically:
2883           *          - `###USERNAME###`    The current user's username.
2884           *          - `###ADMIN_EMAIL###` The admin email in case this was unexpected.
2885           *          - `###EMAIL###`       The user's email address.
2886           *          - `###SITENAME###`    The name of the site.
2887           *          - `###SITEURL###`     The URL to the site.
2888           *     @type string $headers Headers. Add headers in a newline (\r\n) separated string.
2889           * }
2890           * @param array $user     The original user array.
2891           * @param array $userdata The updated user array.
2892           */
2893          $pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
2894  
2895          $pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
2896          $pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
2897          $pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
2898          $pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
2899          $pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
2900  
2901          wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
2902      }
2903  
2904      if ( ! empty( $send_email_change_email ) ) {
2905          /* translators: Do not translate USERNAME, ADMIN_EMAIL, NEW_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2906          $email_change_text = __(
2907              'Hi ###USERNAME###,
2908  
2909  This notice confirms that your email address on ###SITENAME### was changed to ###NEW_EMAIL###.
2910  
2911  If you did not change your email, please contact the Site Administrator at
2912  ###ADMIN_EMAIL###
2913  
2914  This email has been sent to ###EMAIL###
2915  
2916  Regards,
2917  All at ###SITENAME###
2918  ###SITEURL###'
2919          );
2920  
2921          $email_change_email = array(
2922              'to'      => $user['user_email'],
2923              /* translators: Email change notification email subject. %s: Site title. */
2924              'subject' => __( '[%s] Email Changed' ),
2925              'message' => $email_change_text,
2926              'headers' => '',
2927          );
2928  
2929          /**
2930           * Filters the contents of the email sent when the user's email is changed.
2931           *
2932           * @since 4.3.0
2933           *
2934           * @param array $email_change_email {
2935           *     Used to build wp_mail().
2936           *
2937           *     @type string $to      The intended recipients.
2938           *     @type string $subject The subject of the email.
2939           *     @type string $message The content of the email.
2940           *         The following strings have a special meaning and will get replaced dynamically:
2941           *          - `###USERNAME###`    The current user's username.
2942           *          - `###ADMIN_EMAIL###` The admin email in case this was unexpected.
2943           *          - `###NEW_EMAIL###`   The new email address.
2944           *          - `###EMAIL###`       The old email address.
2945           *          - `###SITENAME###`    The name of the site.
2946           *          - `###SITEURL###`     The URL to the site.
2947           *     @type string $headers Headers.
2948           * }
2949           * @param array $user     The original user array.
2950           * @param array $userdata The updated user array.
2951           */
2952          $email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
2953  
2954          $email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
2955          $email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
2956          $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $userdata['user_email'], $email_change_email['message'] );
2957          $email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
2958          $email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
2959          $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
2960  
2961          wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
2962      }
2963  
2964      if ( $switched_locale ) {
2965          restore_previous_locale();
2966      }
2967  
2968      // Update the cookies if the password changed.
2969      $current_user = wp_get_current_user();
2970      if ( $current_user->ID === $user_id ) {
2971          if ( isset( $plaintext_pass ) ) {
2972              /*
2973               * Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
2974               * If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
2975               */
2976              $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
2977              /** This filter is documented in wp-includes/pluggable.php */
2978              $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $user_id, false );
2979  
2980              wp_clear_auth_cookie();
2981  
2982              $remember = false;
2983              $token    = '';
2984  
2985              if ( false !== $logged_in_cookie ) {
2986                  $token = $logged_in_cookie['token'];
2987              }
2988  
2989              if ( false !== $logged_in_cookie && ( (int) $logged_in_cookie['expiration'] - time() ) > $default_cookie_life ) {
2990                  $remember = true;
2991              }
2992  
2993              wp_set_auth_cookie( $user_id, $remember, '', $token );
2994          }
2995      }
2996  
2997      /**
2998       * Fires after the user has been updated and emails have been sent.
2999       *
3000       * @since 6.3.0
3001       *
3002       * @param int   $user_id      The ID of the user that was just updated.
3003       * @param array $userdata     The array of user data that was updated.
3004       * @param array $userdata_raw The unedited array of user data that was updated.
3005       */
3006      do_action( 'wp_update_user', $user_id, $userdata, $userdata_raw );
3007  
3008      return $user_id;
3009  }
3010  
3011  /**
3012   * Provides a simpler way of inserting a user into the database.
3013   *
3014   * Creates a new user with just the username, password, and email. For more
3015   * complex user creation use wp_insert_user() to specify more information.
3016   *
3017   * @since 2.0.0
3018   *
3019   * @see wp_insert_user() More complete way to create a new user.
3020   *
3021   * @param string $username The user's username.
3022   * @param string $password The user's password.
3023   * @param string $email    Optional. The user's email. Default empty.
3024   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
3025   *                      be created.
3026   */
3027  function wp_create_user(
3028      $username,
3029      #[\SensitiveParameter]
3030      $password,
3031      $email = ''
3032  ) {
3033      $user_login = wp_slash( $username );
3034      $user_email = wp_slash( $email );
3035      $user_pass  = $password;
3036  
3037      $userdata = compact( 'user_login', 'user_email', 'user_pass' );
3038      return wp_insert_user( $userdata );
3039  }
3040  
3041  /**
3042   * Returns a list of meta keys to be (maybe) populated in wp_update_user().
3043   *
3044   * The list of keys returned via this function are dependent on the presence
3045   * of those keys in the user meta data to be set.
3046   *
3047   * @since 3.3.0
3048   * @access private
3049   *
3050   * @param WP_User $user WP_User instance.
3051   * @return string[] List of user keys to be populated in wp_update_user().
3052   */
3053  function _get_additional_user_keys( $user ) {
3054      $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'syntax_highlighting', 'infinite_scrolling', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale' );
3055      return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
3056  }
3057  
3058  /**
3059   * Sets up the user contact methods.
3060   *
3061   * Default contact methods were removed for new installations in WordPress 3.6
3062   * and completely removed from the codebase in WordPress 6.9.
3063   *
3064   * Use the {@see 'user_contactmethods'} filter to add or remove contact methods.
3065   *
3066   * @since 3.7.0
3067   * @since 6.9.0 Removed references to `aim`, `jabber`, and `yim` contact methods.
3068   *
3069   * @param WP_User|null $user Optional. WP_User object.
3070   * @return string[] Array of contact method labels keyed by contact method.
3071   */
3072  function wp_get_user_contact_methods( $user = null ) {
3073      $methods = array();
3074  
3075      /**
3076       * Filters the user contact methods.
3077       *
3078       * @since 2.9.0
3079       *
3080       * @param string[]     $methods Array of contact method labels keyed by contact method.
3081       * @param WP_User|null $user    WP_User object or null if none was provided.
3082       */
3083      return apply_filters( 'user_contactmethods', $methods, $user );
3084  }
3085  
3086  /**
3087   * The old private function for setting up user contact methods.
3088   *
3089   * Use wp_get_user_contact_methods() instead.
3090   *
3091   * @since 2.9.0
3092   * @access private
3093   *
3094   * @param WP_User|null $user Optional. WP_User object. Default null.
3095   * @return string[] Array of contact method labels keyed by contact method.
3096   */
3097  function _wp_get_user_contactmethods( $user = null ) {
3098      return wp_get_user_contact_methods( $user );
3099  }
3100  
3101  /**
3102   * Gets the text suggesting how to create strong passwords.
3103   *
3104   * @since 4.1.0
3105   *
3106   * @return string The password hint text.
3107   */
3108  function wp_get_password_hint() {
3109      $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; ).' );
3110  
3111      /**
3112       * Filters the text describing the site's password complexity policy.
3113       *
3114       * @since 4.1.0
3115       *
3116       * @param string $hint The password hint text.
3117       */
3118      return apply_filters( 'password_hint', $hint );
3119  }
3120  
3121  /**
3122   * Creates, stores, then returns a password reset key for user.
3123   *
3124   * @since 4.4.0
3125   *
3126   * @param WP_User $user User to retrieve password reset key for.
3127   * @return string|WP_Error Password reset key on success. WP_Error on error.
3128   */
3129  function get_password_reset_key( $user ) {
3130      if ( ! ( $user instanceof WP_User ) ) {
3131          return new WP_Error( 'invalidcombo', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
3132      }
3133  
3134      /**
3135       * Fires before a new password is retrieved.
3136       *
3137       * Use the {@see 'retrieve_password'} hook instead.
3138       *
3139       * @since 1.5.0
3140       * @deprecated 1.5.1 Misspelled. Use {@see 'retrieve_password'} hook instead.
3141       *
3142       * @param string $user_login The user login name.
3143       */
3144      do_action_deprecated( 'retreive_password', array( $user->user_login ), '1.5.1', 'retrieve_password' );
3145  
3146      /**
3147       * Fires before a new password is retrieved.
3148       *
3149       * @since 1.5.1
3150       *
3151       * @param string $user_login The user login name.
3152       */
3153      do_action( 'retrieve_password', $user->user_login );
3154  
3155      $password_reset_allowed = wp_is_password_reset_allowed_for_user( $user );
3156      if ( ! $password_reset_allowed ) {
3157          return new WP_Error( 'no_password_reset', __( 'Password reset is not allowed for this user' ) );
3158      } elseif ( is_wp_error( $password_reset_allowed ) ) {
3159          return $password_reset_allowed;
3160      }
3161  
3162      // Generate something random for a password reset key.
3163      $key = wp_generate_password( 20, false );
3164  
3165      /**
3166       * Fires when a password reset key is generated.
3167       *
3168       * @since 2.5.0
3169       *
3170       * @param string $user_login The username for the user.
3171       * @param string $key        The generated password reset key.
3172       */
3173      do_action( 'retrieve_password_key', $user->user_login, $key );
3174  
3175      $hashed = time() . ':' . wp_fast_hash( $key );
3176  
3177      $key_saved = wp_update_user(
3178          array(
3179              'ID'                  => $user->ID,
3180              'user_activation_key' => $hashed,
3181          )
3182      );
3183  
3184      if ( is_wp_error( $key_saved ) ) {
3185          return $key_saved;
3186      }
3187  
3188      return $key;
3189  }
3190  
3191  /**
3192   * Retrieves a user row based on password reset key and login.
3193   *
3194   * A key is considered 'expired' if it exactly matches the value of the
3195   * user_activation_key field, rather than being matched after going through the
3196   * hashing process. This field is now hashed; old values are no longer accepted
3197   * but have a different WP_Error code so good user feedback can be provided.
3198   *
3199   * @since 3.1.0
3200   *
3201   * @param string $key       The password reset key.
3202   * @param string $login     The user login.
3203   * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
3204   */
3205  function check_password_reset_key(
3206      #[\SensitiveParameter]
3207      $key,
3208      $login
3209  ) {
3210      $key = preg_replace( '/[^a-z0-9]/i', '', $key );
3211  
3212      if ( empty( $key ) || ! is_string( $key ) ) {
3213          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3214      }
3215  
3216      if ( empty( $login ) || ! is_string( $login ) ) {
3217          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3218      }
3219  
3220      $user = get_user_by( 'login', $login );
3221  
3222      if ( ! $user ) {
3223          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3224      }
3225  
3226      /**
3227       * Filters the expiration time of password reset keys.
3228       *
3229       * @since 4.3.0
3230       *
3231       * @param int $expiration The expiration time in seconds.
3232       */
3233      $expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );
3234  
3235      if ( str_contains( $user->user_activation_key, ':' ) ) {
3236          list( $pass_request_time, $pass_key ) = explode( ':', $user->user_activation_key, 2 );
3237          $expiration_time                      = $pass_request_time + $expiration_duration;
3238      } else {
3239          $pass_key        = $user->user_activation_key;
3240          $expiration_time = false;
3241      }
3242  
3243      if ( ! $pass_key ) {
3244          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3245      }
3246  
3247      $hash_is_correct = wp_verify_fast_hash( $key, $pass_key );
3248  
3249      if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
3250          return $user;
3251      } elseif ( $hash_is_correct && $expiration_time ) {
3252          // Key has an expiration time that's passed.
3253          return new WP_Error( 'expired_key', __( 'Invalid key.' ) );
3254      }
3255  
3256      if ( hash_equals( $user->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
3257          $return  = new WP_Error( 'expired_key', __( 'Invalid key.' ) );
3258          $user_id = $user->ID;
3259  
3260          /**
3261           * Filters the return value of check_password_reset_key() when an
3262           * old-style key or an expired key is used.
3263           *
3264           * Prior to 3.7, plain-text keys were stored in the database.
3265           *
3266           * @since 3.7.0
3267           * @since 4.3.0 Previously key hashes were stored without an expiration time.
3268           *
3269           * @param WP_Error $return  A WP_Error object denoting an expired key.
3270           *                          Return a WP_User object to validate the key.
3271           * @param int      $user_id The matched user ID.
3272           */
3273          return apply_filters( 'password_reset_key_expired', $return, $user_id );
3274      }
3275  
3276      return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3277  }
3278  
3279  /**
3280   * Handles sending a password retrieval email to a user.
3281   *
3282   * @since 2.5.0
3283   * @since 5.7.0 Added `$user_login` parameter.
3284   *
3285   * @global wpdb $wpdb WordPress database abstraction object.
3286   *
3287   * @param string $user_login Optional. Username to send a password retrieval email for.
3288   *                           Defaults to `$_POST['user_login']` if not set.
3289   * @return true|WP_Error True when finished, WP_Error object on error.
3290   */
3291  function retrieve_password( $user_login = '' ) {
3292      $errors    = new WP_Error();
3293      $user_data = false;
3294  
3295      // Use the passed $user_login if available, otherwise use $_POST['user_login'].
3296      if ( ! $user_login && ! empty( $_POST['user_login'] ) && is_string( $_POST['user_login'] ) ) {
3297          $user_login = $_POST['user_login'];
3298      }
3299  
3300      $user_login = trim( wp_unslash( $user_login ) );
3301  
3302      if ( empty( $user_login ) ) {
3303          $errors->add( 'empty_username', __( '<strong>Error:</strong> Please enter a username or email address.' ) );
3304      } elseif ( strpos( $user_login, '@' ) ) {
3305          $user_data = get_user_by( 'email', $user_login );
3306  
3307          if ( empty( $user_data ) ) {
3308              $user_data = get_user_by( 'login', $user_login );
3309          }
3310  
3311          if ( empty( $user_data ) ) {
3312              $errors->add( 'invalid_email', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
3313          }
3314      } else {
3315          $user_data = get_user_by( 'login', $user_login );
3316      }
3317  
3318      /**
3319       * Filters the user data during a password reset request.
3320       *
3321       * Allows, for example, custom validation using data other than username or email address.
3322       *
3323       * @since 5.7.0
3324       *
3325       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
3326       * @param WP_Error      $errors    A WP_Error object containing any errors generated
3327       *                                 by using invalid credentials.
3328       */
3329      $user_data = apply_filters( 'lostpassword_user_data', $user_data, $errors );
3330  
3331      /**
3332       * Fires before errors are returned from a password reset request.
3333       *
3334       * @since 2.1.0
3335       * @since 4.4.0 Added the `$errors` parameter.
3336       * @since 5.4.0 Added the `$user_data` parameter.
3337       *
3338       * @param WP_Error      $errors    A WP_Error object containing any errors generated
3339       *                                 by using invalid credentials.
3340       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
3341       */
3342      do_action( 'lostpassword_post', $errors, $user_data );
3343  
3344      /**
3345       * Filters the errors encountered on a password reset request.
3346       *
3347       * The filtered WP_Error object may, for example, contain errors for an invalid
3348       * username or email address. A WP_Error object should always be returned,
3349       * but may or may not contain errors.
3350       *
3351       * If any errors are present in $errors, this will abort the password reset request.
3352       *
3353       * @since 5.5.0
3354       *
3355       * @param WP_Error      $errors    A WP_Error object containing any errors generated
3356       *                                 by using invalid credentials.
3357       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
3358       */
3359      $errors = apply_filters( 'lostpassword_errors', $errors, $user_data );
3360  
3361      if ( $errors->has_errors() ) {
3362          return $errors;
3363      }
3364  
3365      if ( ! $user_data ) {
3366          $errors->add( 'invalidcombo', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
3367          return $errors;
3368      }
3369  
3370      /**
3371       * Filters whether to send the retrieve password email.
3372       *
3373       * Return false to disable sending the email.
3374       *
3375       * @since 6.0.0
3376       *
3377       * @param bool    $send       Whether to send the email.
3378       * @param string  $user_login The username for the user.
3379       * @param WP_User $user_data  WP_User object.
3380       */
3381      if ( ! apply_filters( 'send_retrieve_password_email', true, $user_login, $user_data ) ) {
3382          return true;
3383      }
3384  
3385      // Redefining user_login ensures we return the right case in the email.
3386      $user_login = $user_data->user_login;
3387      $user_email = $user_data->user_email;
3388      $key        = get_password_reset_key( $user_data );
3389  
3390      if ( is_wp_error( $key ) ) {
3391          return $key;
3392      }
3393  
3394      // Localize password reset message content for user.
3395      $locale = get_user_locale( $user_data );
3396  
3397      $switched_locale = switch_to_user_locale( $user_data->ID );
3398  
3399      if ( is_multisite() ) {
3400          $site_name = get_network()->site_name;
3401      } else {
3402          /*
3403           * The blogname option is escaped with esc_html on the way into the database
3404           * in sanitize_option. We want to reverse this for the plain text arena of emails.
3405           */
3406          $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
3407      }
3408  
3409      $message = __( 'Someone has requested a password reset for the following account:' ) . "\r\n\r\n";
3410      /* translators: %s: Site name. */
3411      $message .= sprintf( __( 'Site Name: %s' ), $site_name ) . "\r\n\r\n";
3412      /* translators: %s: User login. */
3413      $message .= sprintf( __( 'Username: %s' ), $user_login ) . "\r\n\r\n";
3414      $message .= __( 'If this was a mistake, ignore this email and nothing will happen.' ) . "\r\n\r\n";
3415      $message .= __( 'To reset your password, visit the following address:' ) . "\r\n\r\n";
3416  
3417      /*
3418       * Since some user login names end in a period, this could produce ambiguous URLs that
3419       * end in a period. To avoid the ambiguity, ensure that the login is not the last query
3420       * arg in the URL. If moving it to the end, a trailing period will need to be escaped.
3421       *
3422       * @see https://core.trac.wordpress.org/tickets/42957
3423       */
3424      $message .= network_site_url( 'wp-login.php?login=' . rawurlencode( $user_login ) . "&key=$key&action=rp", 'login' ) . '&wp_lang=' . $locale . "\r\n\r\n";
3425  
3426      if ( ! is_user_logged_in() ) {
3427          $requester_ip = $_SERVER['REMOTE_ADDR'];
3428          if ( $requester_ip ) {
3429              $message .= sprintf(
3430                  /* translators: %s: IP address of password reset requester. */
3431                  __( 'This password reset request originated from the IP address %s.' ),
3432                  $requester_ip
3433              ) . "\r\n";
3434          }
3435      }
3436  
3437      /* translators: Password reset notification email subject. %s: Site title. */
3438      $title = sprintf( __( '[%s] Password Reset' ), $site_name );
3439  
3440      /**
3441       * Filters the subject of the password reset email.
3442       *
3443       * @since 2.8.0
3444       * @since 4.4.0 Added the `$user_login` and `$user_data` parameters.
3445       *
3446       * @param string  $title      Email subject.
3447       * @param string  $user_login The username for the user.
3448       * @param WP_User $user_data  WP_User object.
3449       */
3450      $title = apply_filters( 'retrieve_password_title', $title, $user_login, $user_data );
3451  
3452      /**
3453       * Filters the message body of the password reset mail.
3454       *
3455       * If the filtered message is empty, the password reset email will not be sent.
3456       *
3457       * @since 2.8.0
3458       * @since 4.1.0 Added `$user_login` and `$user_data` parameters.
3459       *
3460       * @param string  $message    Email message.
3461       * @param string  $key        The activation key.
3462       * @param string  $user_login The username for the user.
3463       * @param WP_User $user_data  WP_User object.
3464       */
3465      $message = apply_filters( 'retrieve_password_message', $message, $key, $user_login, $user_data );
3466  
3467      // Short-circuit on falsey $message value for backwards compatibility.
3468      if ( ! $message ) {
3469          return true;
3470      }
3471  
3472      /*
3473       * Wrap the single notification email arguments in an array
3474       * to pass them to the retrieve_password_notification_email filter.
3475       */
3476      $defaults = array(
3477          'to'      => $user_email,
3478          'subject' => $title,
3479          'message' => $message,
3480          'headers' => '',
3481      );
3482  
3483      /**
3484       * Filters the contents of the reset password notification email sent to the user.
3485       *
3486       * @since 6.0.0
3487       *
3488       * @param array   $defaults {
3489       *     The default notification email arguments. Used to build wp_mail().
3490       *
3491       *     @type string $to      The intended recipient - user email address.
3492       *     @type string $subject The subject of the email.
3493       *     @type string $message The body of the email.
3494       *     @type string $headers The headers of the email.
3495       * }
3496       * @param string  $key        The activation key.
3497       * @param string  $user_login The username for the user.
3498       * @param WP_User $user_data  WP_User object.
3499       */
3500      $notification_email = apply_filters( 'retrieve_password_notification_email', $defaults, $key, $user_login, $user_data );
3501  
3502      if ( $switched_locale ) {
3503          restore_previous_locale();
3504      }
3505  
3506      if ( is_array( $notification_email ) ) {
3507          // Force key order and merge defaults in case any value is missing in the filtered array.
3508          $notification_email = array_merge( $defaults, $notification_email );
3509      } else {
3510          $notification_email = $defaults;
3511      }
3512  
3513      list( $to, $subject, $message, $headers ) = array_values( $notification_email );
3514  
3515      $subject = wp_specialchars_decode( $subject );
3516  
3517      if ( ! wp_mail( $to, $subject, $message, $headers ) ) {
3518          $errors->add(
3519              'retrieve_password_email_failure',
3520              sprintf(
3521                  /* translators: %s: Documentation URL. */
3522                  __( '<strong>Error:</strong> The email could not be sent. Your site may not be correctly configured to send emails. <a href="%s">Get support for resetting your password</a>.' ),
3523                  esc_url( __( 'https://wordpress.org/documentation/article/reset-your-password/' ) )
3524              )
3525          );
3526          return $errors;
3527      }
3528  
3529      return true;
3530  }
3531  
3532  /**
3533   * Handles resetting the user's password.
3534   *
3535   * @since 2.5.0
3536   *
3537   * @param WP_User $user     The user
3538   * @param string  $new_pass New password for the user in plaintext
3539   */
3540  function reset_password(
3541      $user,
3542      #[\SensitiveParameter]
3543      $new_pass
3544  ) {
3545      /**
3546       * Fires before the user's password is reset.
3547       *
3548       * @since 1.5.0
3549       *
3550       * @param WP_User $user     The user.
3551       * @param string  $new_pass New user password.
3552       */
3553      do_action( 'password_reset', $user, $new_pass );
3554  
3555      wp_set_password( $new_pass, $user->ID );
3556      update_user_meta( $user->ID, 'default_password_nag', false );
3557  
3558      /**
3559       * Fires after the user's password is reset.
3560       *
3561       * @since 4.4.0
3562       *
3563       * @param WP_User $user     The user.
3564       * @param string  $new_pass New user password.
3565       */
3566      do_action( 'after_password_reset', $user, $new_pass );
3567  }
3568  
3569  /**
3570   * Handles registering a new user.
3571   *
3572   * @since 2.5.0
3573   *
3574   * @param string $user_login User's username for logging in
3575   * @param string $user_email User's email address to send password and add
3576   * @return int|WP_Error Either user's ID or error on failure.
3577   */
3578  function register_new_user( $user_login, $user_email ) {
3579      $errors = new WP_Error();
3580  
3581      $sanitized_user_login = sanitize_user( $user_login );
3582      /**
3583       * Filters the email address of a user being registered.
3584       *
3585       * @since 2.1.0
3586       *
3587       * @param string $user_email The email address of the new user.
3588       */
3589      $user_email = apply_filters( 'user_registration_email', $user_email );
3590  
3591      // Check the username.
3592      if ( '' === $sanitized_user_login ) {
3593          $errors->add( 'empty_username', __( '<strong>Error:</strong> Please enter a username.' ) );
3594      } elseif ( ! validate_username( $user_login ) ) {
3595          $errors->add( 'invalid_username', __( '<strong>Error:</strong> This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
3596          $sanitized_user_login = '';
3597      } elseif ( username_exists( $sanitized_user_login ) ) {
3598          $errors->add( 'username_exists', __( '<strong>Error:</strong> This username is already registered. Please choose another one.' ) );
3599      } else {
3600          /** This filter is documented in wp-includes/user.php */
3601          $illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() );
3602          if ( in_array( strtolower( $sanitized_user_login ), array_map( 'strtolower', $illegal_user_logins ), true ) ) {
3603              $errors->add( 'invalid_username', __( '<strong>Error:</strong> Sorry, that username is not allowed.' ) );
3604          }
3605      }
3606  
3607      // Check the email address.
3608      if ( '' === $user_email ) {
3609          $errors->add( 'empty_email', __( '<strong>Error:</strong> Please type your email address.' ) );
3610      } elseif ( ! is_email( $user_email ) ) {
3611          $errors->add( 'invalid_email', __( '<strong>Error:</strong> The email address is not correct.' ) );
3612          $user_email = '';
3613      } elseif ( email_exists( $user_email ) ) {
3614          $errors->add(
3615              'email_exists',
3616              sprintf(
3617                  /* translators: %s: Link to the login page. */
3618                  __( '<strong>Error:</strong> This email address is already registered. <a href="%s">Log in</a> with this address or choose another one.' ),
3619                  esc_url( wp_login_url() )
3620              )
3621          );
3622      }
3623  
3624      /**
3625       * Fires when submitting registration form data, before the user is created.
3626       *
3627       * @since 2.1.0
3628       *
3629       * @param string   $sanitized_user_login The submitted username after being sanitized.
3630       * @param string   $user_email           The submitted email.
3631       * @param WP_Error $errors               Contains any errors with submitted username and email,
3632       *                                       e.g., an empty field, an invalid username or email,
3633       *                                       or an existing username or email.
3634       */
3635      do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
3636  
3637      /**
3638       * Filters the errors encountered when a new user is being registered.
3639       *
3640       * The filtered WP_Error object may, for example, contain errors for an invalid
3641       * or existing username or email address. A WP_Error object should always be returned,
3642       * but may or may not contain errors.
3643       *
3644       * If any errors are present in $errors, this will abort the user's registration.
3645       *
3646       * @since 2.1.0
3647       *
3648       * @param WP_Error $errors               A WP_Error object containing any errors encountered
3649       *                                       during registration.
3650       * @param string   $sanitized_user_login User's username after it has been sanitized.
3651       * @param string   $user_email           User's email.
3652       */
3653      $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
3654  
3655      if ( $errors->has_errors() ) {
3656          return $errors;
3657      }
3658  
3659      $user_pass = wp_generate_password( 12, false );
3660      $user_id   = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
3661      if ( ! $user_id || is_wp_error( $user_id ) ) {
3662          $errors->add(
3663              'registerfail',
3664              sprintf(
3665                  /* translators: %s: Admin email address. */
3666                  __( '<strong>Error:</strong> Could not register you&hellip; please contact the <a href="mailto:%s">site admin</a>!' ),
3667                  esc_attr( get_option( 'admin_email' ) )
3668              )
3669          );
3670          return $errors;
3671      }
3672  
3673      update_user_meta( $user_id, 'default_password_nag', true ); // Set up the password change nag.
3674  
3675      if ( ! empty( $_COOKIE['wp_lang'] ) ) {
3676          $wp_lang = sanitize_text_field( $_COOKIE['wp_lang'] );
3677          if ( in_array( $wp_lang, get_available_languages(), true ) ) {
3678              update_user_meta( $user_id, 'locale', $wp_lang ); // Set user locale if defined on registration.
3679          }
3680      }
3681  
3682      /**
3683       * Fires after a new user registration has been recorded.
3684       *
3685       * @since 4.4.0
3686       *
3687       * @param int $user_id ID of the newly registered user.
3688       */
3689      do_action( 'register_new_user', $user_id );
3690  
3691      return $user_id;
3692  }
3693  
3694  /**
3695   * Initiates email notifications related to the creation of new users.
3696   *
3697   * Notifications are sent both to the site admin and to the newly created user.
3698   *
3699   * @since 4.4.0
3700   * @since 4.6.0 Converted the `$notify` parameter to accept 'user' for sending
3701   *              notifications only to the user created.
3702   *
3703   * @param int    $user_id ID of the newly created user.
3704   * @param string $notify  Optional. Type of notification that should happen. Accepts 'admin'
3705   *                        or an empty string (admin only), 'user', or 'both' (admin and user).
3706   *                        Default 'both'.
3707   */
3708  function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
3709      wp_new_user_notification( $user_id, null, $notify );
3710  }
3711  
3712  /**
3713   * Retrieves the current session token from the logged_in cookie.
3714   *
3715   * @since 4.0.0
3716   *
3717   * @return string Token.
3718   */
3719  function wp_get_session_token() {
3720      $cookie = wp_parse_auth_cookie( '', 'logged_in' );
3721      return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
3722  }
3723  
3724  /**
3725   * Retrieves a list of sessions for the current user.
3726   *
3727   * @since 4.0.0
3728   *
3729   * @return array Array of sessions.
3730   */
3731  function wp_get_all_sessions() {
3732      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3733      return $manager->get_all();
3734  }
3735  
3736  /**
3737   * Removes the current session token from the database.
3738   *
3739   * @since 4.0.0
3740   */
3741  function wp_destroy_current_session() {
3742      $token = wp_get_session_token();
3743      if ( $token ) {
3744          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3745          $manager->destroy( $token );
3746      }
3747  }
3748  
3749  /**
3750   * Removes all but the current session token for the current user for the database.
3751   *
3752   * @since 4.0.0
3753   */
3754  function wp_destroy_other_sessions() {
3755      $token = wp_get_session_token();
3756      if ( $token ) {
3757          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3758          $manager->destroy_others( $token );
3759      }
3760  }
3761  
3762  /**
3763   * Removes all session tokens for the current user from the database.
3764   *
3765   * @since 4.0.0
3766   */
3767  function wp_destroy_all_sessions() {
3768      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3769      $manager->destroy_all();
3770  }
3771  
3772  /**
3773   * Gets the user IDs of all users with no role on this site.
3774   *
3775   * @since 4.4.0
3776   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
3777   *
3778   * @global wpdb $wpdb WordPress database abstraction object.
3779   *
3780   * @param int|null $site_id Optional. The site ID to get users with no role for. Defaults to the current site.
3781   * @return string[] Array of user IDs as strings.
3782   */
3783  function wp_get_users_with_no_role( $site_id = null ) {
3784      global $wpdb;
3785  
3786      if ( ! $site_id ) {
3787          $site_id = get_current_blog_id();
3788      }
3789  
3790      $prefix = $wpdb->get_blog_prefix( $site_id );
3791  
3792      if ( is_multisite() && get_current_blog_id() !== $site_id ) {
3793          switch_to_blog( $site_id );
3794          $role_names = wp_roles()->get_names();
3795          restore_current_blog();
3796      } else {
3797          $role_names = wp_roles()->get_names();
3798      }
3799  
3800      $regex = implode( '|', array_keys( $role_names ) );
3801      $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex );
3802      $users = $wpdb->get_col(
3803          $wpdb->prepare(
3804              "SELECT user_id
3805              FROM $wpdb->usermeta
3806              WHERE meta_key = '{$prefix}capabilities'
3807              AND meta_value NOT REGEXP %s",
3808              $regex
3809          )
3810      );
3811  
3812      return $users;
3813  }
3814  
3815  /**
3816   * Retrieves the current user object.
3817   *
3818   * Will set the current user, if the current user is not set. The current user
3819   * will be set to the logged-in person. If no user is logged-in, then it will
3820   * set the current user to 0, which is invalid and won't have any permissions.
3821   *
3822   * This function is used by the pluggable functions wp_get_current_user() and
3823   * get_currentuserinfo(), the latter of which is deprecated but used for backward
3824   * compatibility.
3825   *
3826   * @since 4.5.0
3827   * @access private
3828   *
3829   * @see wp_get_current_user()
3830   * @global WP_User $current_user Checks if the current user is set.
3831   *
3832   * @return WP_User Current WP_User instance.
3833   */
3834  function _wp_get_current_user() {
3835      global $current_user;
3836  
3837      if ( ! empty( $current_user ) ) {
3838          if ( $current_user instanceof WP_User ) {
3839              return $current_user;
3840          }
3841  
3842          // Upgrade stdClass to WP_User.
3843          if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
3844              $cur_id       = $current_user->ID;
3845              $current_user = null;
3846              wp_set_current_user( $cur_id );
3847              return $current_user;
3848          }
3849  
3850          // $current_user has a junk value. Force to WP_User with ID 0.
3851          $current_user = null;
3852          wp_set_current_user( 0 );
3853          return $current_user;
3854      }
3855  
3856      if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
3857          wp_set_current_user( 0 );
3858          return $current_user;
3859      }
3860  
3861      /**
3862       * Filters the current user.
3863       *
3864       * The default filters use this to determine the current user from the
3865       * request's cookies, if available.
3866       *
3867       * Returning a value of false will effectively short-circuit setting
3868       * the current user.
3869       *
3870       * @since 3.9.0
3871       *
3872       * @param int|false $user_id User ID if one has been determined, false otherwise.
3873       */
3874      $user_id = apply_filters( 'determine_current_user', false );
3875      if ( ! $user_id ) {
3876          wp_set_current_user( 0 );
3877          return $current_user;
3878      }
3879  
3880      wp_set_current_user( $user_id );
3881  
3882      return $current_user;
3883  }
3884  
3885  /**
3886   * Sends a confirmation request email when a change of user email address is attempted.
3887   *
3888   * @since 3.0.0
3889   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
3890   * @since 7.0.3 Added the `$user_id` parameter, which is sent with the `personal_options_update` action.
3891   *
3892   * @global WP_Error $errors WP_Error object.
3893   *
3894   * @param int $user_id Optional. The ID of the user whose email is being changed. Defaults to `$_POST['user_id']` if set, otherwise 0.
3895   */
3896  function send_confirmation_on_profile_email( $user_id = 0 ) {
3897      global $errors;
3898  
3899      // Maintain backward compatibility for those relying on a check based on $_POST['user_id'].
3900      if ( ! $user_id && isset( $_POST['user_id'] ) ) {
3901          $user_id = absint( $_POST['user_id'] );
3902      }
3903  
3904      $current_user = wp_get_current_user();
3905      if ( ! is_object( $errors ) ) {
3906          $errors = new WP_Error();
3907      }
3908  
3909      if ( 0 === $current_user->ID || $current_user->ID !== (int) $user_id ) {
3910          return false;
3911      }
3912  
3913      if ( $current_user->user_email !== $_POST['email'] ) {
3914          if ( ! is_email( $_POST['email'] ) ) {
3915              $errors->add(
3916                  'user_email',
3917                  __( '<strong>Error:</strong> The email address is not correct.' ),
3918                  array(
3919                      'form-field' => 'email',
3920                  )
3921              );
3922  
3923              $_POST['email'] = addslashes( $current_user->user_email );
3924              return;
3925          }
3926  
3927          if ( email_exists( $_POST['email'] ) ) {
3928              $errors->add(
3929                  'user_email',
3930                  __( '<strong>Error:</strong> The email address is already used.' ),
3931                  array(
3932                      'form-field' => 'email',
3933                  )
3934              );
3935              delete_user_meta( $current_user->ID, '_new_email' );
3936  
3937              $_POST['email'] = addslashes( $current_user->user_email );
3938              return;
3939          }
3940  
3941          $hash           = md5( $_POST['email'] . time() . wp_rand() );
3942          $new_user_email = array(
3943              'hash'     => $hash,
3944              'newemail' => $_POST['email'],
3945          );
3946          update_user_meta( $current_user->ID, '_new_email', $new_user_email );
3947  
3948          $sitename = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
3949  
3950          /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
3951          $email_text = __(
3952              'Howdy ###USERNAME###,
3953  
3954  You recently requested to have the email address on your account changed.
3955  
3956  If this is correct, please click on the following link to change it:
3957  ###ADMIN_URL###
3958  
3959  You can safely ignore and delete this email if you do not want to
3960  take this action.
3961  
3962  This email has been sent to ###EMAIL###
3963  
3964  Regards,
3965  All at ###SITENAME###
3966  ###SITEURL###'
3967          );
3968  
3969          /**
3970           * Filters the text of the email sent when a change of user email address is attempted.
3971           *
3972           * The following strings have a special meaning and will get replaced dynamically:
3973           *
3974           *  - `###USERNAME###`  The current user's username.
3975           *  - `###ADMIN_URL###` The link to click on to confirm the email change.
3976           *  - `###EMAIL###`     The new email.
3977           *  - `###SITENAME###`  The name of the site.
3978           *  - `###SITEURL###`   The URL to the site.
3979           *
3980           * @since MU (3.0.0)
3981           * @since 4.9.0 This filter is no longer Multisite specific.
3982           *
3983           * @param string $email_text     Text in the email.
3984           * @param array  $new_user_email {
3985           *     Data relating to the new user email address.
3986           *
3987           *     @type string $hash     The secure hash used in the confirmation link URL.
3988           *     @type string $newemail The proposed new email address.
3989           * }
3990           */
3991          $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email );
3992  
3993          $content = str_replace( '###USERNAME###', $current_user->user_login, $content );
3994          $content = str_replace( '###ADMIN_URL###', esc_url( self_admin_url( 'profile.php?newuseremail=' . $hash ) ), $content );
3995          $content = str_replace( '###EMAIL###', $_POST['email'], $content );
3996          $content = str_replace( '###SITENAME###', $sitename, $content );
3997          $content = str_replace( '###SITEURL###', home_url(), $content );
3998  
3999          /* translators: New email address notification email subject. %s: Site title. */
4000          wp_mail( $_POST['email'], sprintf( __( '[%s] Email Change Request' ), $sitename ), $content );
4001  
4002          $_POST['email'] = $current_user->user_email;
4003      }
4004  }
4005  
4006  /**
4007   * Adds an admin notice alerting the user to check for confirmation request email
4008   * after email address change.
4009   *
4010   * @since 3.0.0
4011   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
4012   *
4013   * @global string $pagenow The filename of the current screen.
4014   */
4015  function new_user_email_admin_notice() {
4016      global $pagenow;
4017  
4018      if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) ) {
4019          $email = get_user_meta( get_current_user_id(), '_new_email', true );
4020          if ( $email ) {
4021              $message = sprintf(
4022                  /* translators: %s: New email address. */
4023                  __( 'Your email address has not been updated yet. Please check your inbox at %s for a confirmation email.' ),
4024                  '<code>' . esc_html( $email['newemail'] ) . '</code>'
4025              );
4026              wp_admin_notice( $message, array( 'type' => 'info' ) );
4027          }
4028      }
4029  }
4030  
4031  /**
4032   * Gets all personal data request types.
4033   *
4034   * @since 4.9.6
4035   * @access private
4036   *
4037   * @return string[] List of core privacy action types.
4038   */
4039  function _wp_privacy_action_request_types() {
4040      return array(
4041          'export_personal_data',
4042          'remove_personal_data',
4043      );
4044  }
4045  
4046  /**
4047   * Registers the personal data exporter for users.
4048   *
4049   * @since 4.9.6
4050   *
4051   * @param array[] $exporters An array of personal data exporters.
4052   * @return array[] An array of personal data exporters.
4053   */
4054  function wp_register_user_personal_data_exporter( $exporters ) {
4055      $exporters['wordpress-user'] = array(
4056          'exporter_friendly_name' => __( 'WordPress User' ),
4057          'callback'               => 'wp_user_personal_data_exporter',
4058      );
4059  
4060      return $exporters;
4061  }
4062  
4063  /**
4064   * Finds and exports personal data associated with an email address from the user and user_meta table.
4065   *
4066   * @since 4.9.6
4067   * @since 5.4.0 Added 'Community Events Location' group to the export data.
4068   * @since 5.4.0 Added 'Session Tokens' group to the export data.
4069   *
4070   * @param string $email_address  The user's email address.
4071   * @return array {
4072   *     An array of personal data.
4073   *
4074   *     @type array[] $data An array of personal data arrays.
4075   *     @type bool    $done Whether the exporter is finished.
4076   * }
4077   */
4078  function wp_user_personal_data_exporter( $email_address ) {
4079      $email_address = trim( $email_address );
4080  
4081      $data_to_export = array();
4082  
4083      $user = get_user_by( 'email', $email_address );
4084  
4085      if ( ! $user ) {
4086          return array(
4087              'data' => array(),
4088              'done' => true,
4089          );
4090      }
4091  
4092      $user_meta = get_user_meta( $user->ID );
4093  
4094      $user_props_to_export = array(
4095          'ID'              => __( 'User ID' ),
4096          'user_login'      => __( 'User Login Name' ),
4097          'user_nicename'   => __( 'User Nice Name' ),
4098          'user_email'      => __( 'User Email' ),
4099          'user_url'        => __( 'User URL' ),
4100          'user_registered' => __( 'User Registration Date' ),
4101          'display_name'    => __( 'User Display Name' ),
4102          'nickname'        => __( 'User Nickname' ),
4103          'first_name'      => __( 'User First Name' ),
4104          'last_name'       => __( 'User Last Name' ),
4105          'description'     => __( 'User Description' ),
4106      );
4107  
4108      $user_data_to_export = array();
4109  
4110      foreach ( $user_props_to_export as $key => $name ) {
4111          $value = '';
4112  
4113          switch ( $key ) {
4114              case 'ID':
4115              case 'user_login':
4116              case 'user_nicename':
4117              case 'user_email':
4118              case 'user_url':
4119              case 'user_registered':
4120              case 'display_name':
4121                  $value = $user->data->$key;
4122                  break;
4123              case 'nickname':
4124              case 'first_name':
4125              case 'last_name':
4126              case 'description':
4127                  $value = $user_meta[ $key ][0];
4128                  break;
4129          }
4130  
4131          if ( ! empty( $value ) ) {
4132              $user_data_to_export[] = array(
4133                  'name'  => $name,
4134                  'value' => $value,
4135              );
4136          }
4137      }
4138  
4139      // Get the list of reserved names.
4140      $reserved_names = array_values( $user_props_to_export );
4141  
4142      /**
4143       * Filters the user's profile data for the privacy exporter.
4144       *
4145       * @since 5.4.0
4146       *
4147       * @param array    $additional_user_profile_data {
4148       *     An array of name-value pairs of additional user data items. Default empty array.
4149       *
4150       *     @type string $name  The user-facing name of an item name-value pair,e.g. 'IP Address'.
4151       *     @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'.
4152       * }
4153       * @param WP_User  $user           The user whose data is being exported.
4154       * @param string[] $reserved_names An array of reserved names. Any item in `$additional_user_data`
4155       *                                 that uses one of these for its `name` will not be included in the export.
4156       */
4157      $_extra_data = apply_filters( 'wp_privacy_additional_user_profile_data', array(), $user, $reserved_names );
4158  
4159      if ( is_array( $_extra_data ) && ! empty( $_extra_data ) ) {
4160          // Remove items that use reserved names.
4161          $extra_data = array_filter(
4162              $_extra_data,
4163              static function ( $item ) use ( $reserved_names ) {
4164                  return ! in_array( $item['name'], $reserved_names, true );
4165              }
4166          );
4167  
4168          if ( count( $extra_data ) !== count( $_extra_data ) ) {
4169              _doing_it_wrong(
4170                  __FUNCTION__,
4171                  sprintf(
4172                      /* translators: %s: wp_privacy_additional_user_profile_data */
4173                      __( 'Filter %s returned items with reserved names.' ),
4174                      '<code>wp_privacy_additional_user_profile_data</code>'
4175                  ),
4176                  '5.4.0'
4177              );
4178          }
4179  
4180          if ( ! empty( $extra_data ) ) {
4181              $user_data_to_export = array_merge( $user_data_to_export, $extra_data );
4182          }
4183      }
4184  
4185      $data_to_export[] = array(
4186          'group_id'          => 'user',
4187          'group_label'       => __( 'User' ),
4188          'group_description' => __( 'User&#8217;s profile data.' ),
4189          'item_id'           => "user-{$user->ID}",
4190          'data'              => $user_data_to_export,
4191      );
4192  
4193      if ( isset( $user_meta['community-events-location'] ) ) {
4194          $location = maybe_unserialize( $user_meta['community-events-location'][0] );
4195  
4196          $location_props_to_export = array(
4197              'description' => __( 'City' ),
4198              'country'     => __( 'Country' ),
4199              'latitude'    => __( 'Latitude' ),
4200              'longitude'   => __( 'Longitude' ),
4201              'ip'          => __( 'IP' ),
4202          );
4203  
4204          $location_data_to_export = array();
4205  
4206          foreach ( $location_props_to_export as $key => $name ) {
4207              if ( ! empty( $location[ $key ] ) ) {
4208                  $location_data_to_export[] = array(
4209                      'name'  => $name,
4210                      'value' => $location[ $key ],
4211                  );
4212              }
4213          }
4214  
4215          $data_to_export[] = array(
4216              'group_id'          => 'community-events-location',
4217              'group_label'       => __( 'Community Events Location' ),
4218              'group_description' => __( 'User&#8217;s location data used for the Community Events in the WordPress Events and News dashboard widget.' ),
4219              'item_id'           => "community-events-location-{$user->ID}",
4220              'data'              => $location_data_to_export,
4221          );
4222      }
4223  
4224      if ( isset( $user_meta['session_tokens'] ) ) {
4225          $session_tokens = maybe_unserialize( $user_meta['session_tokens'][0] );
4226  
4227          $session_tokens_props_to_export = array(
4228              'expiration' => __( 'Expiration' ),
4229              'ip'         => __( 'IP' ),
4230              'ua'         => __( 'User Agent' ),
4231              'login'      => __( 'Last Login' ),
4232          );
4233  
4234          foreach ( $session_tokens as $token_key => $session_token ) {
4235              $session_tokens_data_to_export = array();
4236  
4237              foreach ( $session_tokens_props_to_export as $key => $name ) {
4238                  if ( ! empty( $session_token[ $key ] ) ) {
4239                      $value = $session_token[ $key ];
4240                      if ( in_array( $key, array( 'expiration', 'login' ), true ) ) {
4241                          $value = date_i18n( 'F d, Y H:i A', $value );
4242                      }
4243                      $session_tokens_data_to_export[] = array(
4244                          'name'  => $name,
4245                          'value' => $value,
4246                      );
4247                  }
4248              }
4249  
4250              $data_to_export[] = array(
4251                  'group_id'          => 'session-tokens',
4252                  'group_label'       => __( 'Session Tokens' ),
4253                  'group_description' => __( 'User&#8217;s Session Tokens data.' ),
4254                  'item_id'           => "session-tokens-{$user->ID}-{$token_key}",
4255                  'data'              => $session_tokens_data_to_export,
4256              );
4257          }
4258      }
4259  
4260      return array(
4261          'data' => $data_to_export,
4262          'done' => true,
4263      );
4264  }
4265  
4266  /**
4267   * Updates log when privacy request is confirmed.
4268   *
4269   * @since 4.9.6
4270   * @access private
4271   *
4272   * @param int $request_id ID of the request.
4273   */
4274  function _wp_privacy_account_request_confirmed( $request_id ) {
4275      $request = wp_get_user_request( $request_id );
4276  
4277      if ( ! $request ) {
4278          return;
4279      }
4280  
4281      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
4282          return;
4283      }
4284  
4285      update_post_meta( $request_id, '_wp_user_request_confirmed_timestamp', time() );
4286      wp_update_post(
4287          array(
4288              'ID'          => $request_id,
4289              'post_status' => 'request-confirmed',
4290          )
4291      );
4292  }
4293  
4294  /**
4295   * Notifies the site administrator via email when a request is confirmed.
4296   *
4297   * Without this, the admin would have to manually check the site to see if any
4298   * action was needed on their part yet.
4299   *
4300   * @since 4.9.6
4301   *
4302   * @param int $request_id The ID of the request.
4303   */
4304  function _wp_privacy_send_request_confirmation_notification( $request_id ) {
4305      $request = wp_get_user_request( $request_id );
4306  
4307      if ( ! ( $request instanceof WP_User_Request ) || 'request-confirmed' !== $request->status ) {
4308          return;
4309      }
4310  
4311      $already_notified = (bool) get_post_meta( $request_id, '_wp_admin_notified', true );
4312  
4313      if ( $already_notified ) {
4314          return;
4315      }
4316  
4317      if ( 'export_personal_data' === $request->action_name ) {
4318          $manage_url = admin_url( 'export-personal-data.php' );
4319      } elseif ( 'remove_personal_data' === $request->action_name ) {
4320          $manage_url = admin_url( 'erase-personal-data.php' );
4321      }
4322      $action_description = wp_user_request_action_description( $request->action_name );
4323  
4324      /**
4325       * Filters the recipient of the data request confirmation notification.
4326       *
4327       * In a Multisite environment, this will default to the email address of the
4328       * network admin because, by default, single site admins do not have the
4329       * capabilities required to process requests. Some networks may wish to
4330       * delegate those capabilities to a single-site admin, or a dedicated person
4331       * responsible for managing privacy requests.
4332       *
4333       * @since 4.9.6
4334       *
4335       * @param string          $admin_email The email address of the notification recipient.
4336       * @param WP_User_Request $request     The request that is initiating the notification.
4337       */
4338      $admin_email = apply_filters( 'user_request_confirmed_email_to', get_site_option( 'admin_email' ), $request );
4339  
4340      $email_data = array(
4341          'request'     => $request,
4342          'user_email'  => $request->email,
4343          'description' => $action_description,
4344          'manage_url'  => $manage_url,
4345          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
4346          'siteurl'     => home_url(),
4347          'admin_email' => $admin_email,
4348      );
4349  
4350      $subject = sprintf(
4351          /* translators: Privacy data request confirmed notification email subject. 1: Site title, 2: Name of the confirmed action. */
4352          __( '[%1$s] Action Confirmed: %2$s' ),
4353          $email_data['sitename'],
4354          $action_description
4355      );
4356  
4357      /**
4358       * Filters the subject of the user request confirmation email.
4359       *
4360       * @since 4.9.8
4361       *
4362       * @param string $subject    The email subject.
4363       * @param string $sitename   The name of the site.
4364       * @param array  $email_data {
4365       *     Data relating to the account action email.
4366       *
4367       *     @type WP_User_Request $request     User request object.
4368       *     @type string          $user_email  The email address confirming a request.
4369       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4370       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4371       *     @type string          $sitename    The site name sending the mail.
4372       *     @type string          $siteurl     The site URL sending the mail.
4373       *     @type string          $admin_email The administrator email receiving the mail.
4374       * }
4375       */
4376      $subject = apply_filters( 'user_request_confirmed_email_subject', $subject, $email_data['sitename'], $email_data );
4377  
4378      /* translators: Do not translate SITENAME, USER_EMAIL, DESCRIPTION, MANAGE_URL, SITEURL; those are placeholders. */
4379      $content = __(
4380          'Howdy,
4381  
4382  A user data privacy request has been confirmed on ###SITENAME###:
4383  
4384  User: ###USER_EMAIL###
4385  Request: ###DESCRIPTION###
4386  
4387  You can view and manage these data privacy requests here:
4388  
4389  ###MANAGE_URL###
4390  
4391  Regards,
4392  All at ###SITENAME###
4393  ###SITEURL###'
4394      );
4395  
4396      /**
4397       * Filters the body of the user request confirmation email.
4398       *
4399       * The email is sent to an administrator when a user request is confirmed.
4400       *
4401       * The following strings have a special meaning and will get replaced dynamically:
4402       *
4403       *  - `###SITENAME###`    The name of the site.
4404       *  - `###USER_EMAIL###`  The user email for the request.
4405       *  - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for.
4406       *  - `###MANAGE_URL###`  The URL to manage requests.
4407       *  - `###SITEURL###`     The URL to the site.
4408       *
4409       * @since 4.9.6
4410       * @deprecated 5.8.0 Use {@see 'user_request_confirmed_email_content'} instead.
4411       *                   For user erasure fulfillment email content
4412       *                   use {@see 'user_erasure_fulfillment_email_content'} instead.
4413       *
4414       * @param string $content    The email content.
4415       * @param array  $email_data {
4416       *     Data relating to the account action email.
4417       *
4418       *     @type WP_User_Request $request     User request object.
4419       *     @type string          $user_email  The email address confirming a request.
4420       *     @type string          $description Description of the action being performed
4421       *                                        so the user knows what the email is for.
4422       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4423       *     @type string          $sitename    The site name sending the mail.
4424       *     @type string          $siteurl     The site URL sending the mail.
4425       *     @type string          $admin_email The administrator email receiving the mail.
4426       * }
4427       */
4428      $content = apply_filters_deprecated(
4429          'user_confirmed_action_email_content',
4430          array( $content, $email_data ),
4431          '5.8.0',
4432          sprintf(
4433              /* translators: 1 & 2: Deprecation replacement options. */
4434              __( '%1$s or %2$s' ),
4435              'user_request_confirmed_email_content',
4436              'user_erasure_fulfillment_email_content'
4437          )
4438      );
4439  
4440      /**
4441       * Filters the body of the user request confirmation email.
4442       *
4443       * The email is sent to an administrator when a user request is confirmed.
4444       * The following strings have a special meaning and will get replaced dynamically:
4445       *
4446       *  - `###SITENAME###`    The name of the site.
4447       *  - `###USER_EMAIL###`  The user email for the request.
4448       *  - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for.
4449       *  - `###MANAGE_URL###`  The URL to manage requests.
4450       *  - `###SITEURL###`     The URL to the site.
4451       *
4452       * @since 5.8.0
4453       *
4454       * @param string $content    The email content.
4455       * @param array  $email_data {
4456       *     Data relating to the account action email.
4457       *
4458       *     @type WP_User_Request $request     User request object.
4459       *     @type string          $user_email  The email address confirming a request.
4460       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4461       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4462       *     @type string          $sitename    The site name sending the mail.
4463       *     @type string          $siteurl     The site URL sending the mail.
4464       *     @type string          $admin_email The administrator email receiving the mail.
4465       * }
4466       */
4467      $content = apply_filters( 'user_request_confirmed_email_content', $content, $email_data );
4468  
4469      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
4470      $content = str_replace( '###USER_EMAIL###', $email_data['user_email'], $content );
4471      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
4472      $content = str_replace( '###MANAGE_URL###', sanitize_url( $email_data['manage_url'] ), $content );
4473      $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
4474  
4475      $headers = '';
4476  
4477      /**
4478       * Filters the headers of the user request confirmation email.
4479       *
4480       * @since 5.4.0
4481       *
4482       * @param string|array $headers    The email headers.
4483       * @param string       $subject    The email subject.
4484       * @param string       $content    The email content.
4485       * @param int          $request_id The request ID.
4486       * @param array        $email_data {
4487       *     Data relating to the account action email.
4488       *
4489       *     @type WP_User_Request $request     User request object.
4490       *     @type string          $user_email  The email address confirming a request.
4491       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4492       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4493       *     @type string          $sitename    The site name sending the mail.
4494       *     @type string          $siteurl     The site URL sending the mail.
4495       *     @type string          $admin_email The administrator email receiving the mail.
4496       * }
4497       */
4498      $headers = apply_filters( 'user_request_confirmed_email_headers', $headers, $subject, $content, $request_id, $email_data );
4499  
4500      $email_sent = wp_mail( $email_data['admin_email'], $subject, $content, $headers );
4501  
4502      if ( $email_sent ) {
4503          update_post_meta( $request_id, '_wp_admin_notified', true );
4504      }
4505  }
4506  
4507  /**
4508   * Notifies the user when their erasure request is fulfilled.
4509   *
4510   * Without this, the user would never know if their data was actually erased.
4511   *
4512   * @since 4.9.6
4513   *
4514   * @param int $request_id The privacy request post ID associated with this request.
4515   */
4516  function _wp_privacy_send_erasure_fulfillment_notification( $request_id ) {
4517      $request = wp_get_user_request( $request_id );
4518  
4519      if ( ! ( $request instanceof WP_User_Request ) || 'request-completed' !== $request->status ) {
4520          return;
4521      }
4522  
4523      $already_notified = (bool) get_post_meta( $request_id, '_wp_user_notified', true );
4524  
4525      if ( $already_notified ) {
4526          return;
4527      }
4528  
4529      // Localize message content for user; fallback to site default for visitors.
4530      if ( ! empty( $request->user_id ) ) {
4531          $switched_locale = switch_to_user_locale( $request->user_id );
4532      } else {
4533          $switched_locale = switch_to_locale( get_locale() );
4534      }
4535  
4536      /**
4537       * Filters the recipient of the data erasure fulfillment notification.
4538       *
4539       * @since 4.9.6
4540       *
4541       * @param string          $user_email The email address of the notification recipient.
4542       * @param WP_User_Request $request    The request that is initiating the notification.
4543       */
4544      $user_email = apply_filters( 'user_erasure_fulfillment_email_to', $request->email, $request );
4545  
4546      $email_data = array(
4547          'request'            => $request,
4548          'message_recipient'  => $user_email,
4549          'privacy_policy_url' => get_privacy_policy_url(),
4550          'sitename'           => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
4551          'siteurl'            => home_url(),
4552      );
4553  
4554      $subject = sprintf(
4555          /* translators: Erasure request fulfilled notification email subject. %s: Site title. */
4556          __( '[%s] Erasure Request Fulfilled' ),
4557          $email_data['sitename']
4558      );
4559  
4560      /**
4561       * Filters the subject of the email sent when an erasure request is completed.
4562       *
4563       * @since 4.9.8
4564       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_subject'} instead.
4565       *
4566       * @param string $subject    The email subject.
4567       * @param string $sitename   The name of the site.
4568       * @param array  $email_data {
4569       *     Data relating to the account action email.
4570       *
4571       *     @type WP_User_Request $request            User request object.
4572       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4573       *                                               to the value of `$request->email`, but can be changed
4574       *                                               by the `user_erasure_fulfillment_email_to` filter.
4575       *     @type string          $privacy_policy_url Privacy policy URL.
4576       *     @type string          $sitename           The site name sending the mail.
4577       *     @type string          $siteurl            The site URL sending the mail.
4578       * }
4579       */
4580      $subject = apply_filters_deprecated(
4581          'user_erasure_complete_email_subject',
4582          array( $subject, $email_data['sitename'], $email_data ),
4583          '5.8.0',
4584          'user_erasure_fulfillment_email_subject'
4585      );
4586  
4587      /**
4588       * Filters the subject of the email sent when an erasure request is completed.
4589       *
4590       * @since 5.8.0
4591       *
4592       * @param string $subject    The email subject.
4593       * @param string $sitename   The name of the site.
4594       * @param array  $email_data {
4595       *     Data relating to the account action email.
4596       *
4597       *     @type WP_User_Request $request            User request object.
4598       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4599       *                                               to the value of `$request->email`, but can be changed
4600       *                                               by the `user_erasure_fulfillment_email_to` filter.
4601       *     @type string          $privacy_policy_url Privacy policy URL.
4602       *     @type string          $sitename           The site name sending the mail.
4603       *     @type string          $siteurl            The site URL sending the mail.
4604       * }
4605       */
4606      $subject = apply_filters( 'user_erasure_fulfillment_email_subject', $subject, $email_data['sitename'], $email_data );
4607  
4608      /* translators: Do not translate SITENAME, SITEURL; those are placeholders. */
4609      $content = __(
4610          'Howdy,
4611  
4612  Your request to erase your personal data on ###SITENAME### has been completed.
4613  
4614  If you have any follow-up questions or concerns, please contact the site administrator.
4615  
4616  Regards,
4617  All at ###SITENAME###
4618  ###SITEURL###'
4619      );
4620  
4621      if ( ! empty( $email_data['privacy_policy_url'] ) ) {
4622          /* translators: Do not translate SITENAME, SITEURL, PRIVACY_POLICY_URL; those are placeholders. */
4623          $content = __(
4624              'Howdy,
4625  
4626  Your request to erase your personal data on ###SITENAME### has been completed.
4627  
4628  If you have any follow-up questions or concerns, please contact the site administrator.
4629  
4630  For more information, you can also read our privacy policy: ###PRIVACY_POLICY_URL###
4631  
4632  Regards,
4633  All at ###SITENAME###
4634  ###SITEURL###'
4635          );
4636      }
4637  
4638      /**
4639       * Filters the body of the data erasure fulfillment notification.
4640       *
4641       * The email is sent to a user when their data erasure request is fulfilled
4642       * by an administrator.
4643       *
4644       * The following strings have a special meaning and will get replaced dynamically:
4645       *
4646       *  - `###SITENAME###`           The name of the site.
4647       *  - `###PRIVACY_POLICY_URL###` Privacy policy page URL.
4648       *  - `###SITEURL###`            The URL to the site.
4649       *
4650       * @since 4.9.6
4651       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_content'} instead.
4652       *                   For user request confirmation email content
4653       *                   use {@see 'user_request_confirmed_email_content'} instead.
4654       *
4655       * @param string $content The email content.
4656       * @param array  $email_data {
4657       *     Data relating to the account action email.
4658       *
4659       *     @type WP_User_Request $request            User request object.
4660       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4661       *                                               to the value of `$request->email`, but can be changed
4662       *                                               by the `user_erasure_fulfillment_email_to` filter.
4663       *     @type string          $privacy_policy_url Privacy policy URL.
4664       *     @type string          $sitename           The site name sending the mail.
4665       *     @type string          $siteurl            The site URL sending the mail.
4666       * }
4667       */
4668      $content = apply_filters_deprecated(
4669          'user_confirmed_action_email_content',
4670          array( $content, $email_data ),
4671          '5.8.0',
4672          sprintf(
4673              /* translators: 1 & 2: Deprecation replacement options. */
4674              __( '%1$s or %2$s' ),
4675              'user_erasure_fulfillment_email_content',
4676              'user_request_confirmed_email_content'
4677          )
4678      );
4679  
4680      /**
4681       * Filters the body of the data erasure fulfillment notification.
4682       *
4683       * The email is sent to a user when their data erasure request is fulfilled
4684       * by an administrator.
4685       *
4686       * The following strings have a special meaning and will get replaced dynamically:
4687       *
4688       *  - `###SITENAME###`           The name of the site.
4689       *  - `###PRIVACY_POLICY_URL###` Privacy policy page URL.
4690       *  - `###SITEURL###`            The URL to the site.
4691       *
4692       * @since 5.8.0
4693       *
4694       * @param string $content The email content.
4695       * @param array  $email_data {
4696       *     Data relating to the account action email.
4697       *
4698       *     @type WP_User_Request $request            User request object.
4699       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4700       *                                               to the value of `$request->email`, but can be changed
4701       *                                               by the `user_erasure_fulfillment_email_to` filter.
4702       *     @type string          $privacy_policy_url Privacy policy URL.
4703       *     @type string          $sitename           The site name sending the mail.
4704       *     @type string          $siteurl            The site URL sending the mail.
4705       * }
4706       */
4707      $content = apply_filters( 'user_erasure_fulfillment_email_content', $content, $email_data );
4708  
4709      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
4710      $content = str_replace( '###PRIVACY_POLICY_URL###', $email_data['privacy_policy_url'], $content );
4711      $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
4712  
4713      $headers = '';
4714  
4715      /**
4716       * Filters the headers of the data erasure fulfillment notification.
4717       *
4718       * @since 5.4.0
4719       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_headers'} instead.
4720       *
4721       * @param string|array $headers    The email headers.
4722       * @param string       $subject    The email subject.
4723       * @param string       $content    The email content.
4724       * @param int          $request_id The request ID.
4725       * @param array        $email_data {
4726       *     Data relating to the account action email.
4727       *
4728       *     @type WP_User_Request $request            User request object.
4729       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4730       *                                               to the value of `$request->email`, but can be changed
4731       *                                               by the `user_erasure_fulfillment_email_to` filter.
4732       *     @type string          $privacy_policy_url Privacy policy URL.
4733       *     @type string          $sitename           The site name sending the mail.
4734       *     @type string          $siteurl            The site URL sending the mail.
4735       * }
4736       */
4737      $headers = apply_filters_deprecated(
4738          'user_erasure_complete_email_headers',
4739          array( $headers, $subject, $content, $request_id, $email_data ),
4740          '5.8.0',
4741          'user_erasure_fulfillment_email_headers'
4742      );
4743  
4744      /**
4745       * Filters the headers of the data erasure fulfillment notification.
4746       *
4747       * @since 5.8.0
4748       *
4749       * @param string|array $headers    The email headers.
4750       * @param string       $subject    The email subject.
4751       * @param string       $content    The email content.
4752       * @param int          $request_id The request ID.
4753       * @param array        $email_data {
4754       *     Data relating to the account action email.
4755       *
4756       *     @type WP_User_Request $request            User request object.
4757       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4758       *                                               to the value of `$request->email`, but can be changed
4759       *                                               by the `user_erasure_fulfillment_email_to` filter.
4760       *     @type string          $privacy_policy_url Privacy policy URL.
4761       *     @type string          $sitename           The site name sending the mail.
4762       *     @type string          $siteurl            The site URL sending the mail.
4763       * }
4764       */
4765      $headers = apply_filters( 'user_erasure_fulfillment_email_headers', $headers, $subject, $content, $request_id, $email_data );
4766  
4767      $email_sent = wp_mail( $user_email, $subject, $content, $headers );
4768  
4769      if ( $switched_locale ) {
4770          restore_previous_locale();
4771      }
4772  
4773      if ( $email_sent ) {
4774          update_post_meta( $request_id, '_wp_user_notified', true );
4775      }
4776  }
4777  
4778  /**
4779   * Returns request confirmation message HTML.
4780   *
4781   * @since 4.9.6
4782   * @access private
4783   *
4784   * @param int $request_id The request ID being confirmed.
4785   * @return string The confirmation message.
4786   */
4787  function _wp_privacy_account_request_confirmed_message( $request_id ) {
4788      $request = wp_get_user_request( $request_id );
4789  
4790      $message  = '<p class="success">' . __( 'Action has been confirmed.' ) . '</p>';
4791      $message .= '<p>' . __( 'The site administrator has been notified and will fulfill your request as soon as possible.' ) . '</p>';
4792  
4793      if ( $request && in_array( $request->action_name, _wp_privacy_action_request_types(), true ) ) {
4794          if ( 'export_personal_data' === $request->action_name ) {
4795              $message  = '<p class="success">' . __( 'Thanks for confirming your export request.' ) . '</p>';
4796              $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>';
4797          } elseif ( 'remove_personal_data' === $request->action_name ) {
4798              $message  = '<p class="success">' . __( 'Thanks for confirming your erasure request.' ) . '</p>';
4799              $message .= '<p>' . __( 'The site administrator has been notified. You will receive an email confirmation when they erase your data.' ) . '</p>';
4800          }
4801      }
4802  
4803      /**
4804       * Filters the message displayed to a user when they confirm a data request.
4805       *
4806       * @since 4.9.6
4807       *
4808       * @param string $message    The message to the user.
4809       * @param int    $request_id The ID of the request being confirmed.
4810       */
4811      $message = apply_filters( 'user_request_action_confirmed_message', $message, $request_id );
4812  
4813      return $message;
4814  }
4815  
4816  /**
4817   * Creates and logs a user request to perform a specific action.
4818   *
4819   * Requests are stored inside a post type named `user_request` since they can apply to both
4820   * users on the site, or guests without a user account.
4821   *
4822   * @since 4.9.6
4823   * @since 5.7.0 Added the `$status` parameter.
4824   *
4825   * @param string $email_address           User email address. This can be the address of a registered
4826   *                                        or non-registered user.
4827   * @param string $action_name             Name of the action that is being confirmed. Required.
4828   * @param array  $request_data            Misc data you want to send with the verification request and pass
4829   *                                        to the actions once the request is confirmed.
4830   * @param string $status                  Optional request status (pending or confirmed). Default 'pending'.
4831   * @return int|WP_Error                   Returns the request ID if successful, or a WP_Error object on failure.
4832   */
4833  function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array(), $status = 'pending' ) {
4834      $email_address = sanitize_email( $email_address );
4835      $action_name   = sanitize_key( $action_name );
4836  
4837      if ( ! is_email( $email_address ) ) {
4838          return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) );
4839      }
4840  
4841      if ( ! in_array( $action_name, _wp_privacy_action_request_types(), true ) ) {
4842          return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) );
4843      }
4844  
4845      if ( ! in_array( $status, array( 'pending', 'confirmed' ), true ) ) {
4846          return new WP_Error( 'invalid_status', __( 'Invalid request status.' ) );
4847      }
4848  
4849      $user    = get_user_by( 'email', $email_address );
4850      $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0;
4851  
4852      // Check for duplicates.
4853      $requests_query = new WP_Query(
4854          array(
4855              'post_type'     => 'user_request',
4856              'post_name__in' => array( $action_name ), // Action name stored in post_name column.
4857              'title'         => $email_address,        // Email address stored in post_title column.
4858              'post_status'   => array(
4859                  'request-pending',
4860                  'request-confirmed',
4861              ),
4862              'fields'        => 'ids',
4863          )
4864      );
4865  
4866      if ( $requests_query->found_posts ) {
4867          return new WP_Error( 'duplicate_request', __( 'An incomplete personal data request for this email address already exists.' ) );
4868      }
4869  
4870      $request_id = wp_insert_post(
4871          array(
4872              'post_author'   => $user_id,
4873              'post_name'     => $action_name,
4874              'post_title'    => $email_address,
4875              'post_content'  => wp_json_encode( $request_data ),
4876              'post_status'   => 'request-' . $status,
4877              'post_type'     => 'user_request',
4878              'post_date'     => current_time( 'mysql', false ),
4879              'post_date_gmt' => current_time( 'mysql', true ),
4880          ),
4881          true
4882      );
4883  
4884      return $request_id;
4885  }
4886  
4887  /**
4888   * Gets action description from the name and return a string.
4889   *
4890   * @since 4.9.6
4891   *
4892   * @param string $action_name Action name of the request.
4893   * @return string Human readable action name.
4894   */
4895  function wp_user_request_action_description( $action_name ) {
4896      switch ( $action_name ) {
4897          case 'export_personal_data':
4898              $description = __( 'Export Personal Data' );
4899              break;
4900          case 'remove_personal_data':
4901              $description = __( 'Erase Personal Data' );
4902              break;
4903          default:
4904              /* translators: %s: Action name. */
4905              $description = sprintf( __( 'Confirm the "%s" action' ), $action_name );
4906              break;
4907      }
4908  
4909      /**
4910       * Filters the user action description.
4911       *
4912       * @since 4.9.6
4913       *
4914       * @param string $description The default description.
4915       * @param string $action_name The name of the request.
4916       */
4917      return apply_filters( 'user_request_action_description', $description, $action_name );
4918  }
4919  
4920  /**
4921   * Send a confirmation request email to confirm an action.
4922   *
4923   * If the request is not already pending, it will be updated.
4924   *
4925   * @since 4.9.6
4926   *
4927   * @param int $request_id ID of the request created via wp_create_user_request().
4928   * @return true|WP_Error True on success, `WP_Error` on failure.
4929   */
4930  function wp_send_user_request( $request_id ) {
4931      $request_id = absint( $request_id );
4932      $request    = wp_get_user_request( $request_id );
4933  
4934      if ( ! $request ) {
4935          return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
4936      }
4937  
4938      // Localize message content for user; fallback to site default for visitors.
4939      if ( ! empty( $request->user_id ) ) {
4940          $switched_locale = switch_to_user_locale( $request->user_id );
4941      } else {
4942          $switched_locale = switch_to_locale( get_locale() );
4943      }
4944  
4945      /*
4946       * Generate the new user request key first, as it is used by both the $request
4947       * object and the confirm_url array.
4948       * See https://core.trac.wordpress.org/ticket/44940
4949       */
4950      $request->confirm_key = wp_generate_user_request_key( $request_id );
4951  
4952      $email_data = array(
4953          'request'     => $request,
4954          'email'       => $request->email,
4955          'description' => wp_user_request_action_description( $request->action_name ),
4956          'confirm_url' => add_query_arg(
4957              array(
4958                  'action'      => 'confirmaction',
4959                  'request_id'  => $request_id,
4960                  'confirm_key' => $request->confirm_key,
4961              ),
4962              wp_login_url()
4963          ),
4964          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
4965          'siteurl'     => home_url(),
4966      );
4967  
4968      /* translators: Confirm privacy data request notification email subject. 1: Site title, 2: Name of the action. */
4969      $subject = sprintf( __( '[%1$s] Confirm Action: %2$s' ), $email_data['sitename'], $email_data['description'] );
4970  
4971      /**
4972       * Filters the subject of the email sent when an account action is attempted.
4973       *
4974       * @since 4.9.6
4975       *
4976       * @param string $subject    The email subject.
4977       * @param string $sitename   The name of the site.
4978       * @param array  $email_data {
4979       *     Data relating to the account action email.
4980       *
4981       *     @type WP_User_Request $request     User request object.
4982       *     @type string          $email       The email address this is being sent to.
4983       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4984       *     @type string          $confirm_url The link to click on to confirm the account action.
4985       *     @type string          $sitename    The site name sending the mail.
4986       *     @type string          $siteurl     The site URL sending the mail.
4987       * }
4988       */
4989      $subject = apply_filters( 'user_request_action_email_subject', $subject, $email_data['sitename'], $email_data );
4990  
4991      /* translators: Do not translate DESCRIPTION, CONFIRM_URL, SITENAME, SITEURL: those are placeholders. */
4992      $content = __(
4993          'Howdy,
4994  
4995  A request has been made to perform the following action on your account:
4996  
4997       ###DESCRIPTION###
4998  
4999  To confirm this, please click on the following link:
5000  ###CONFIRM_URL###
5001  
5002  You can safely ignore and delete this email if you do not want to
5003  take this action.
5004  
5005  Regards,
5006  All at ###SITENAME###
5007  ###SITEURL###'
5008      );
5009  
5010      /**
5011       * Filters the text of the email sent when an account action is attempted.
5012       *
5013       * The following strings have a special meaning and will get replaced dynamically:
5014       *
5015       *  - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for.
5016       *  - `###CONFIRM_URL###` The link to click on to confirm the account action.
5017       *  - `###SITENAME###`    The name of the site.
5018       *  - `###SITEURL###`     The URL to the site.
5019       *
5020       * @since 4.9.6
5021       *
5022       * @param string $content Text in the email.
5023       * @param array  $email_data {
5024       *     Data relating to the account action email.
5025       *
5026       *     @type WP_User_Request $request     User request object.
5027       *     @type string          $email       The email address this is being sent to.
5028       *     @type string          $description Description of the action being performed so the user knows what the email is for.
5029       *     @type string          $confirm_url The link to click on to confirm the account action.
5030       *     @type string          $sitename    The site name sending the mail.
5031       *     @type string          $siteurl     The site URL sending the mail.
5032       * }
5033       */
5034      $content = apply_filters( 'user_request_action_email_content', $content, $email_data );
5035  
5036      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
5037      $content = str_replace( '###CONFIRM_URL###', sanitize_url( $email_data['confirm_url'] ), $content );
5038      $content = str_replace( '###EMAIL###', $email_data['email'], $content );
5039      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
5040      $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
5041  
5042      $headers = '';
5043  
5044      /**
5045       * Filters the headers of the email sent when an account action is attempted.
5046       *
5047       * @since 5.4.0
5048       *
5049       * @param string|array $headers    The email headers.
5050       * @param string       $subject    The email subject.
5051       * @param string       $content    The email content.
5052       * @param int          $request_id The request ID.
5053       * @param array        $email_data {
5054       *     Data relating to the account action email.
5055       *
5056       *     @type WP_User_Request $request     User request object.
5057       *     @type string          $email       The email address this is being sent to.
5058       *     @type string          $description Description of the action being performed so the user knows what the email is for.
5059       *     @type string          $confirm_url The link to click on to confirm the account action.
5060       *     @type string          $sitename    The site name sending the mail.
5061       *     @type string          $siteurl     The site URL sending the mail.
5062       * }
5063       */
5064      $headers = apply_filters( 'user_request_action_email_headers', $headers, $subject, $content, $request_id, $email_data );
5065  
5066      $email_sent = wp_mail( $email_data['email'], $subject, $content, $headers );
5067  
5068      if ( $switched_locale ) {
5069          restore_previous_locale();
5070      }
5071  
5072      if ( ! $email_sent ) {
5073          return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export confirmation email.' ) );
5074      }
5075  
5076      return true;
5077  }
5078  
5079  /**
5080   * Returns a confirmation key for a user action and stores the hashed version for future comparison.
5081   *
5082   * @since 4.9.6
5083   *
5084   * @param int $request_id Request ID.
5085   * @return string Confirmation key.
5086   */
5087  function wp_generate_user_request_key( $request_id ) {
5088      // Generate something random for a confirmation key.
5089      $key = wp_generate_password( 20, false );
5090  
5091      // Save the key, hashed.
5092      wp_update_post(
5093          array(
5094              'ID'            => $request_id,
5095              'post_status'   => 'request-pending',
5096              'post_password' => wp_fast_hash( $key ),
5097          )
5098      );
5099  
5100      return $key;
5101  }
5102  
5103  /**
5104   * Validates a user request by comparing the key with the request's key.
5105   *
5106   * @since 4.9.6
5107   *
5108   * @param int    $request_id ID of the request being confirmed.
5109   * @param string $key        Provided key to validate.
5110   * @return true|WP_Error True on success, WP_Error on failure.
5111   */
5112  function wp_validate_user_request_key(
5113      $request_id,
5114      #[\SensitiveParameter]
5115      $key
5116  ) {
5117      $request_id       = absint( $request_id );
5118      $request          = wp_get_user_request( $request_id );
5119      $saved_key        = $request->confirm_key;
5120      $key_request_time = $request->modified_timestamp;
5121  
5122      if ( ! $request || ! $saved_key || ! $key_request_time ) {
5123          return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
5124      }
5125  
5126      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
5127          return new WP_Error( 'expired_request', __( 'This personal data request has expired.' ) );
5128      }
5129  
5130      if ( empty( $key ) ) {
5131          return new WP_Error( 'missing_key', __( 'The confirmation key is missing from this personal data request.' ) );
5132      }
5133  
5134      /**
5135       * Filters the expiration time of confirm keys.
5136       *
5137       * @since 4.9.6
5138       *
5139       * @param int $expiration The expiration time in seconds.
5140       */
5141      $expiration_duration = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS );
5142      $expiration_time     = $key_request_time + $expiration_duration;
5143  
5144      if ( ! wp_verify_fast_hash( $key, $saved_key ) ) {
5145          return new WP_Error( 'invalid_key', __( 'The confirmation key is invalid for this personal data request.' ) );
5146      }
5147  
5148      if ( ! $expiration_time || time() > $expiration_time ) {
5149          return new WP_Error( 'expired_key', __( 'The confirmation key has expired for this personal data request.' ) );
5150      }
5151  
5152      return true;
5153  }
5154  
5155  /**
5156   * Returns the user request object for the specified request ID.
5157   *
5158   * @since 5.4.0
5159   *
5160   * @param int $request_id The ID of the user request.
5161   * @return WP_User_Request|false
5162   */
5163  function wp_get_user_request( $request_id ) {
5164      $request_id = absint( $request_id );
5165      $post       = get_post( $request_id );
5166  
5167      if ( ! $post || 'user_request' !== $post->post_type ) {
5168          return false;
5169      }
5170  
5171      return new WP_User_Request( $post );
5172  }
5173  
5174  /**
5175   * Checks if Application Passwords is supported.
5176   *
5177   * Application Passwords is supported only by sites using SSL or local environments
5178   * but may be made available using the {@see 'wp_is_application_passwords_available'} filter.
5179   *
5180   * @since 5.9.0
5181   *
5182   * @return bool
5183   */
5184  function wp_is_application_passwords_supported() {
5185      return is_ssl() || 'local' === wp_get_environment_type();
5186  }
5187  
5188  /**
5189   * Checks if Application Passwords is globally available.
5190   *
5191   * By default, Application Passwords is available to all sites using SSL or to local environments.
5192   * Use the {@see 'wp_is_application_passwords_available'} filter to adjust its availability.
5193   *
5194   * @since 5.6.0
5195   *
5196   * @return bool
5197   */
5198  function wp_is_application_passwords_available() {
5199      /**
5200       * Filters whether Application Passwords is available.
5201       *
5202       * @since 5.6.0
5203       *
5204       * @param bool $available True if available, false otherwise.
5205       */
5206      return apply_filters( 'wp_is_application_passwords_available', wp_is_application_passwords_supported() );
5207  }
5208  
5209  /**
5210   * Checks if Application Passwords is available for a specific user.
5211   *
5212   * By default all users can use Application Passwords. Use {@see 'wp_is_application_passwords_available_for_user'}
5213   * to restrict availability to certain users.
5214   *
5215   * @since 5.6.0
5216   *
5217   * @param int|WP_User $user The user to check.
5218   * @return bool
5219   */
5220  function wp_is_application_passwords_available_for_user( $user ) {
5221      if ( ! wp_is_application_passwords_available() ) {
5222          return false;
5223      }
5224  
5225      if ( ! is_object( $user ) ) {
5226          $user = get_userdata( $user );
5227      }
5228  
5229      if ( ! $user || ! $user->exists() ) {
5230          return false;
5231      }
5232  
5233      /**
5234       * Filters whether Application Passwords is available for a specific user.
5235       *
5236       * @since 5.6.0
5237       *
5238       * @param bool    $available True if available, false otherwise.
5239       * @param WP_User $user      The user to check.
5240       */
5241      return apply_filters( 'wp_is_application_passwords_available_for_user', true, $user );
5242  }
5243  
5244  /**
5245   * Registers the user meta property for persisted preferences.
5246   *
5247   * This property is used to store user preferences across page reloads and is
5248   * currently used by the block editor for preferences like 'fullscreenMode' and
5249   * 'fixedToolbar'.
5250   *
5251   * @since 6.1.0
5252   * @access private
5253   *
5254   * @global wpdb $wpdb WordPress database abstraction object.
5255   */
5256  function wp_register_persisted_preferences_meta() {
5257      /*
5258       * Create a meta key that incorporates the blog prefix so that each site
5259       * on a multisite can have distinct user preferences.
5260       */
5261      global $wpdb;
5262      $meta_key = $wpdb->get_blog_prefix() . 'persisted_preferences';
5263  
5264      register_meta(
5265          'user',
5266          $meta_key,
5267          array(
5268              'type'         => 'object',
5269              'single'       => true,
5270              'show_in_rest' => array(
5271                  'name'   => 'persisted_preferences',
5272                  'type'   => 'object',
5273                  'schema' => array(
5274                      'type'                 => 'object',
5275                      'context'              => array( 'edit' ),
5276                      'properties'           => array(
5277                          '_modified' => array(
5278                              'description' => __( 'The date and time the preferences were updated.' ),
5279                              'type'        => 'string',
5280                              'format'      => 'date-time',
5281                              'readonly'    => false,
5282                          ),
5283                      ),
5284                      'additionalProperties' => true,
5285                  ),
5286              ),
5287          )
5288      );
5289  }
5290  
5291  /**
5292   * Sets the last changed time for the 'users' cache group.
5293   *
5294   * @since 6.3.0
5295   */
5296  function wp_cache_set_users_last_changed() {
5297      wp_cache_set_last_changed( 'users' );
5298  }
5299  
5300  /**
5301   * Checks if password reset is allowed for a specific user.
5302   *
5303   * @since 6.3.0
5304   *
5305   * @param int|WP_User $user The user to check.
5306   * @return bool|WP_Error True if allowed, false or WP_Error otherwise.
5307   */
5308  function wp_is_password_reset_allowed_for_user( $user ) {
5309      if ( ! is_object( $user ) ) {
5310          $user = get_userdata( $user );
5311      }
5312  
5313      if ( ! $user || ! $user->exists() ) {
5314          return false;
5315      }
5316      $allow = true;
5317      if ( is_multisite() && is_user_spammy( $user ) ) {
5318          $allow = false;
5319      }
5320  
5321      /**
5322       * Filters whether to allow a password to be reset.
5323       *
5324       * @since 2.7.0
5325       *
5326       * @param bool $allow   Whether to allow the password to be reset. Default true.
5327       * @param int  $user_id The ID of the user attempting to reset a password.
5328       */
5329      return apply_filters( 'allow_password_reset', $allow, $user->ID );
5330  }


Generated : Sat Sep 26 08:20:30 2026 Cross-referenced by PHPXref