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