[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Tue Nov 19 01:00:03 2019 Cross-referenced by PHPXref 0.7.1