| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * These functions can be replaced via plugins. If plugins do not redefine these 4 * functions, then these will be used instead. 5 * 6 * @package WordPress 7 */ 8 9 if ( ! function_exists( 'wp_set_current_user' ) ) : 10 /** 11 * Changes the current user by ID or name. 12 * 13 * Set $id to null and specify a name if you do not know a user's ID. 14 * 15 * Some WordPress functionality is based on the current user and not based on 16 * the signed in user. Therefore, it opens the ability to edit and perform 17 * actions on users who aren't signed in. 18 * 19 * @since 2.0.3 20 * 21 * @global WP_User $current_user The current user object which holds the user data. 22 * 23 * @param int|null $id User ID. 24 * @param string $name User's username. 25 * @return WP_User Current user User object. 26 */ 27 function wp_set_current_user( $id, $name = '' ) { 28 global $current_user; 29 30 // If `$id` matches the current user, there is nothing to do. 31 if ( isset( $current_user ) 32 && ( $current_user instanceof WP_User ) 33 && ( (int) $id === $current_user->ID ) 34 && ( null !== $id ) 35 ) { 36 return $current_user; 37 } 38 39 $current_user = new WP_User( $id, $name ); 40 41 setup_userdata( $current_user->ID ); 42 43 /** 44 * Fires after the current user is set. 45 * 46 * @since 2.0.1 47 */ 48 do_action( 'set_current_user' ); 49 50 return $current_user; 51 } 52 endif; 53 54 if ( ! function_exists( 'wp_get_current_user' ) ) : 55 /** 56 * Retrieves the current user object. 57 * 58 * Will set the current user, if the current user is not set. The current user 59 * will be set to the logged-in person. If no user is logged-in, then it will 60 * set the current user to 0, which is invalid and won't have any permissions. 61 * 62 * @since 2.0.3 63 * 64 * @see _wp_get_current_user() 65 * @global WP_User $current_user Checks if the current user is set. 66 * 67 * @return WP_User Current WP_User instance. 68 */ 69 function wp_get_current_user() { 70 return _wp_get_current_user(); 71 } 72 endif; 73 74 if ( ! function_exists( 'get_userdata' ) ) : 75 /** 76 * Retrieves user info by user ID. 77 * 78 * @since 0.71 79 * 80 * @param int $user_id User ID. 81 * @return WP_User|false WP_User object on success, false on failure. 82 */ 83 function get_userdata( $user_id ) { 84 return get_user_by( 'id', $user_id ); 85 } 86 endif; 87 88 if ( ! function_exists( 'get_user_by' ) ) : 89 /** 90 * Retrieves user info by a given field. 91 * 92 * @since 2.8.0 93 * @since 4.4.0 Added 'ID' as an alias of 'id' for the `$field` parameter. 94 * 95 * @global WP_User $current_user The current user object which holds the user data. 96 * 97 * @param string $field The field to retrieve the user with. id | ID | slug | email | login. 98 * @param int|string $value A value for $field. A user ID, slug, email address, or login name. 99 * @return WP_User|false WP_User object on success, false on failure. 100 * 101 * @phpstan-return ( 102 * $field is 'id'|'ID' 103 * ? ( $value is int<min, 0> ? false : WP_User|false ) 104 * : WP_User|false 105 * ) 106 */ 107 function get_user_by( $field, $value ) { 108 $userdata = WP_User::get_data_by( $field, $value ); 109 110 if ( ! $userdata ) { 111 return false; 112 } 113 114 $user = new WP_User(); 115 $user->init( $userdata ); 116 117 return $user; 118 } 119 endif; 120 121 if ( ! function_exists( 'cache_users' ) ) : 122 /** 123 * Retrieves info for user lists to prevent multiple queries by get_userdata(). 124 * 125 * @since 3.0.0 126 * 127 * @global wpdb $wpdb WordPress database abstraction object. 128 * 129 * @param int[] $user_ids User ID numbers list. 130 */ 131 function cache_users( $user_ids ) { 132 global $wpdb; 133 134 update_meta_cache( 'user', $user_ids ); 135 136 $clean = _get_non_cached_ids( $user_ids, 'users' ); 137 138 if ( empty( $clean ) ) { 139 return; 140 } 141 142 $list = implode( ',', $clean ); 143 144 $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" ); 145 146 foreach ( $users as $user ) { 147 update_user_caches( $user ); 148 } 149 } 150 endif; 151 152 if ( ! function_exists( 'wp_mail' ) ) : 153 /** 154 * Sends an email, similar to PHP's mail function. 155 * 156 * A true return value does not automatically mean that the user received the 157 * email successfully. It just only means that the method used was able to 158 * process the request without any errors. 159 * 160 * The default content type is `text/plain` which does not allow using HTML. 161 * However, you can set the content type of the email by using the 162 * {@see 'wp_mail_content_type'} filter. 163 * 164 * The default charset is based on the charset used on the blog. The charset can 165 * be set using the {@see 'wp_mail_charset'} filter. 166 * 167 * When using the `$embeds` parameter to embed images for use in HTML emails, 168 * reference the embedded file in your HTML with a `cid:` URL whose value 169 * matches the file's Content-ID. By default, the Content-ID (`cid`) used for 170 * each embedded file is the key in the embeds array, unless modified via the 171 * {@see 'wp_mail_embed_args'} filter. For example: 172 * 173 * `<img src="cid:0" alt="Logo">` 174 * `<img src="cid:my-image" alt="Image">` 175 * 176 * You may also customize the Content-ID for each file by using the 177 * {@see 'wp_mail_embed_args'} filter and setting the `cid` value. 178 * 179 * @since 1.2.1 180 * @since 5.5.0 is_email() is used for email validation, 181 * instead of PHPMailer's default validator. 182 * @since 6.9.0 The `$embeds` parameter was added. 183 * @since 6.9.0 Improved Content-Type header handling for multipart messages. 184 * 185 * @global PHPMailer\PHPMailer\PHPMailer $phpmailer 186 * 187 * @param string|string[] $to Array or comma-separated list of email addresses to send message. 188 * @param string $subject Email subject. 189 * @param string $message Message contents. 190 * @param string|string[] $headers Optional. Additional headers. 191 * @param string|string[] $attachments Optional. Paths to files to attach. 192 * @param string|string[] $embeds Optional. Paths to files to embed. 193 * @return bool Whether the email was sent successfully. 194 */ 195 function wp_mail( $to, $subject, $message, $headers = '', $attachments = array(), $embeds = array() ) { 196 // Compact the input, apply the filters, and extract them back out. 197 198 /** 199 * Filters the wp_mail() arguments. 200 * 201 * @since 2.2.0 202 * @since 6.9.0 The `$embeds` element was added to the `$args` array. 203 * 204 * @param array $args { 205 * Array of the `wp_mail()` arguments. 206 * 207 * @type string|string[] $to Array or comma-separated list of email addresses to send message. 208 * @type string $subject Email subject. 209 * @type string $message Message contents. 210 * @type string|string[] $headers Additional headers. 211 * @type string|string[] $attachments Paths to files to attach. 212 * @type string|string[] $embeds Paths to files to embed. 213 * } 214 */ 215 $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments', 'embeds' ) ); 216 217 /** 218 * Filters whether to preempt sending an email. 219 * 220 * Returning a non-null value will short-circuit {@see wp_mail()}, returning 221 * that value instead. A boolean return value should be used to indicate whether 222 * the email was successfully sent. 223 * 224 * @since 5.7.0 225 * @since 6.9.0 The `$embeds` element was added to the `$atts` array. 226 * 227 * @param null|bool $return Short-circuit return value. 228 * @param array $atts { 229 * Array of the `wp_mail()` arguments. 230 * 231 * @type string|string[] $to Array or comma-separated list of email addresses to send message. 232 * @type string $subject Email subject. 233 * @type string $message Message contents. 234 * @type string|string[] $headers Additional headers. 235 * @type string|string[] $attachments Paths to files to attach. 236 * @type string|string[] $embeds Paths to files to embed. 237 * } 238 */ 239 $pre_wp_mail = apply_filters( 'pre_wp_mail', null, $atts ); 240 241 if ( null !== $pre_wp_mail ) { 242 return $pre_wp_mail; 243 } 244 245 if ( isset( $atts['to'] ) ) { 246 $to = $atts['to']; 247 } 248 249 if ( ! is_array( $to ) ) { 250 $to = explode( ',', $to ); 251 } 252 253 if ( isset( $atts['subject'] ) ) { 254 $subject = $atts['subject']; 255 } 256 257 if ( isset( $atts['message'] ) ) { 258 $message = $atts['message']; 259 } 260 261 if ( isset( $atts['headers'] ) ) { 262 $headers = $atts['headers']; 263 } 264 265 if ( isset( $atts['attachments'] ) ) { 266 $attachments = $atts['attachments']; 267 } 268 269 if ( ! is_array( $attachments ) ) { 270 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) ); 271 } 272 273 if ( isset( $atts['embeds'] ) ) { 274 $embeds = $atts['embeds']; 275 } 276 277 if ( ! is_array( $embeds ) ) { 278 $embeds = explode( "\n", str_replace( "\r\n", "\n", $embeds ) ); 279 } 280 281 global $phpmailer; 282 283 // (Re)create it, if it's gone missing. 284 if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer ) ) { 285 require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php'; 286 require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php'; 287 require_once ABSPATH . WPINC . '/PHPMailer/Exception.php'; 288 require_once ABSPATH . WPINC . '/class-wp-phpmailer.php'; 289 $phpmailer = new WP_PHPMailer( true ); 290 291 $phpmailer::$validator = static function ( $email ) { 292 return (bool) is_email( $email ); 293 }; 294 } 295 296 // Headers. 297 $cc = array(); 298 $bcc = array(); 299 $reply_to = array(); 300 301 if ( empty( $headers ) ) { 302 $headers = array(); 303 } else { 304 if ( ! is_array( $headers ) ) { 305 /* 306 * Explode the headers out, so this function can take 307 * both string headers and an array of headers. 308 */ 309 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) ); 310 } else { 311 $tempheaders = $headers; 312 } 313 $headers = array(); 314 315 // If it's actually got contents. 316 if ( ! empty( $tempheaders ) ) { 317 // Iterate through the raw headers. 318 foreach ( (array) $tempheaders as $header ) { 319 if ( ! str_contains( $header, ':' ) ) { 320 if ( false !== stripos( $header, 'boundary=' ) ) { 321 $parts = preg_split( '/boundary=/i', trim( $header ) ); 322 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) ); 323 } 324 continue; 325 } 326 // Explode them out. 327 list( $name, $content ) = explode( ':', trim( $header ), 2 ); 328 329 // Cleanup crew. 330 $name = trim( $name ); 331 $content = trim( $content ); 332 333 switch ( strtolower( $name ) ) { 334 // Mainly for legacy -- process a "From:" header if it's there. 335 case 'from': 336 $bracket_pos = strpos( $content, '<' ); 337 if ( false !== $bracket_pos ) { 338 // Text before the bracketed email is the "From" name. 339 if ( $bracket_pos > 0 ) { 340 $from_name = substr( $content, 0, $bracket_pos ); 341 $from_name = str_replace( '"', '', $from_name ); 342 $from_name = trim( $from_name ); 343 } 344 345 $from_email = substr( $content, $bracket_pos + 1 ); 346 $from_email = str_replace( '>', '', $from_email ); 347 $from_email = trim( $from_email ); 348 349 // Avoid setting an empty $from_email. 350 } elseif ( '' !== trim( $content ) ) { 351 $from_email = trim( $content ); 352 } 353 break; 354 case 'content-type': 355 if ( str_contains( $content, ';' ) ) { 356 list( $type, $charset_content ) = explode( ';', $content ); 357 $content_type = trim( $type ); 358 if ( false !== stripos( $charset_content, 'charset=' ) ) { 359 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) ); 360 } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) { 361 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) ); 362 $charset = ''; 363 if ( preg_match( '~^multipart/(\S+)~', $content_type, $matches ) ) { 364 $content_type = 'multipart/' . strtolower( $matches[1] ) . '; boundary="' . $boundary . '"'; 365 } 366 } 367 368 // Avoid setting an empty $content_type. 369 } elseif ( '' !== trim( $content ) ) { 370 $content_type = trim( $content ); 371 } 372 break; 373 case 'cc': 374 $cc = array_merge( (array) $cc, explode( ',', $content ) ); 375 break; 376 case 'bcc': 377 $bcc = array_merge( (array) $bcc, explode( ',', $content ) ); 378 break; 379 case 'reply-to': 380 $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) ); 381 break; 382 default: 383 // Add it to our grand headers array. 384 $headers[ trim( $name ) ] = trim( $content ); 385 break; 386 } 387 } 388 } 389 } 390 391 // Empty out the values that may be set. 392 $phpmailer->clearAllRecipients(); 393 $phpmailer->clearAttachments(); 394 $phpmailer->clearCustomHeaders(); 395 $phpmailer->clearReplyTos(); 396 $phpmailer->Body = ''; 397 $phpmailer->AltBody = ''; 398 399 /* 400 * Reset encoding to 8-bit, as it may have been automatically downgraded 401 * to 7-bit by PHPMailer (based on the body contents) in a previous call 402 * to wp_mail(). 403 * 404 * See https://core.trac.wordpress.org/ticket/33972 405 */ 406 $phpmailer->Encoding = PHPMailer\PHPMailer\PHPMailer::ENCODING_8BIT; 407 408 // Set "From" name and email. 409 410 // If we don't have a name from the input headers. 411 if ( ! isset( $from_name ) ) { 412 $from_name = 'WordPress'; 413 } 414 415 /* 416 * If we don't have an email from the input headers, default to wordpress@$sitename 417 * Some hosts will block outgoing mail from this address if it doesn't exist, 418 * but there's no easy alternative. Defaulting to admin_email might appear to be 419 * another option, but some hosts may refuse to relay mail from an unknown domain. 420 * See https://core.trac.wordpress.org/ticket/5007. 421 */ 422 if ( ! isset( $from_email ) ) { 423 // Get the site domain and get rid of www. 424 $sitename = wp_parse_url( network_home_url(), PHP_URL_HOST ); 425 $from_email = 'wordpress@'; 426 427 if ( null !== $sitename ) { 428 if ( str_starts_with( $sitename, 'www.' ) ) { 429 $sitename = substr( $sitename, 4 ); 430 } 431 432 $from_email .= $sitename; 433 } 434 } 435 436 /** 437 * Filters the email address to send from. 438 * 439 * @since 2.2.0 440 * 441 * @param string $from_email Email address to send from. 442 */ 443 $from_email = apply_filters( 'wp_mail_from', $from_email ); 444 445 /** 446 * Filters the name to associate with the "from" email address. 447 * 448 * @since 2.3.0 449 * 450 * @param string $from_name Name associated with the "from" email address. 451 */ 452 $from_name = apply_filters( 'wp_mail_from_name', $from_name ); 453 454 try { 455 $phpmailer->setFrom( $from_email, $from_name, false ); 456 } catch ( PHPMailer\PHPMailer\Exception $e ) { 457 $mail_error_data = compact( 'to', 'subject', 'message', 'headers', 'attachments' ); 458 $mail_error_data['phpmailer_exception_code'] = $e->getCode(); 459 460 /** This filter is documented in wp-includes/pluggable.php */ 461 do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_error_data ) ); 462 463 return false; 464 } 465 466 // Set mail's subject and body. 467 $phpmailer->Subject = $subject; 468 $phpmailer->Body = $message; 469 470 // Set destination addresses, using appropriate methods for handling addresses. 471 $address_headers = compact( 'to', 'cc', 'bcc', 'reply_to' ); 472 473 foreach ( $address_headers as $address_header => $addresses ) { 474 if ( empty( $addresses ) ) { 475 continue; 476 } 477 478 foreach ( (array) $addresses as $address ) { 479 try { 480 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>". 481 $recipient_name = ''; 482 483 if ( preg_match( '/(.*)<(.+)>/', $address, $matches ) ) { 484 if ( count( $matches ) === 3 ) { 485 $recipient_name = $matches[1]; 486 $address = $matches[2]; 487 } 488 } 489 490 switch ( $address_header ) { 491 case 'to': 492 $phpmailer->addAddress( $address, $recipient_name ); 493 break; 494 case 'cc': 495 $phpmailer->addCC( $address, $recipient_name ); 496 break; 497 case 'bcc': 498 $phpmailer->addBCC( $address, $recipient_name ); 499 break; 500 case 'reply_to': 501 $phpmailer->addReplyTo( $address, $recipient_name ); 502 break; 503 } 504 } catch ( PHPMailer\PHPMailer\Exception $e ) { 505 continue; 506 } 507 } 508 } 509 510 // Set to use PHP's mail(). 511 $phpmailer->isMail(); 512 513 // Set Content-Type and charset. 514 515 // If we don't have a Content-Type from the input headers. 516 if ( ! isset( $content_type ) ) { 517 $content_type = 'text/plain'; 518 } 519 520 /** 521 * Filters the wp_mail() content type. 522 * 523 * @since 2.3.0 524 * 525 * @param string $content_type Default wp_mail() content type. 526 */ 527 $content_type = apply_filters( 'wp_mail_content_type', $content_type ); 528 529 $phpmailer->ContentType = $content_type; 530 531 // Set whether it's plaintext, depending on $content_type. 532 if ( 'text/html' === $content_type ) { 533 $phpmailer->isHTML( true ); 534 } 535 536 // If we don't have a charset from the input headers. 537 if ( ! isset( $charset ) ) { 538 $charset = get_bloginfo( 'charset' ); 539 } 540 541 /** 542 * Filters the default wp_mail() charset. 543 * 544 * @since 2.3.0 545 * 546 * @param string $charset Default email charset. 547 */ 548 $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset ); 549 550 // Set custom headers. 551 if ( ! empty( $headers ) ) { 552 foreach ( (array) $headers as $name => $content ) { 553 // Only add custom headers not added automatically by PHPMailer. 554 if ( ! in_array( $name, array( 'MIME-Version', 'X-Mailer' ), true ) ) { 555 try { 556 $phpmailer->addCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) ); 557 } catch ( PHPMailer\PHPMailer\Exception $e ) { 558 continue; 559 } 560 } 561 } 562 } 563 564 if ( ! empty( $attachments ) ) { 565 foreach ( $attachments as $filename => $attachment ) { 566 $filename = is_string( $filename ) ? $filename : ''; 567 568 try { 569 $phpmailer->addAttachment( $attachment, $filename ); 570 } catch ( PHPMailer\PHPMailer\Exception $e ) { 571 continue; 572 } 573 } 574 } 575 576 if ( ! empty( $embeds ) ) { 577 foreach ( $embeds as $key => $embed_path ) { 578 /** 579 * Filters the arguments for PHPMailer's addEmbeddedImage() method. 580 * 581 * @since 6.9.0 582 * 583 * @param array $args { 584 * An array of arguments for PHPMailer's addEmbeddedImage() method. 585 * 586 * @type string $path The path to the file. 587 * @type string $cid The Content-ID of the image. Default: The key in the embeds array. 588 * @type string $name The filename of the image. 589 * @type string $encoding The encoding of the image. Default: 'base64'. 590 * @type string $type The MIME type of the image. Default: empty string, which lets PHPMailer auto-detect. 591 * @type string $disposition The disposition of the image. Default: 'inline'. 592 * } 593 */ 594 $embed_args = apply_filters( 595 'wp_mail_embed_args', 596 array( 597 'path' => $embed_path, 598 'cid' => (string) $key, 599 'name' => basename( $embed_path ), 600 'encoding' => 'base64', 601 'type' => '', 602 'disposition' => 'inline', 603 ) 604 ); 605 606 try { 607 $phpmailer->addEmbeddedImage( 608 $embed_args['path'], 609 $embed_args['cid'], 610 $embed_args['name'], 611 $embed_args['encoding'], 612 $embed_args['type'], 613 $embed_args['disposition'] 614 ); 615 } catch ( PHPMailer\PHPMailer\Exception $e ) { 616 continue; 617 } 618 } 619 } 620 621 /** 622 * Fires after PHPMailer is initialized. 623 * 624 * @since 2.2.0 625 * 626 * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference). 627 */ 628 do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) ); 629 630 $mail_data = compact( 'to', 'subject', 'message', 'headers', 'attachments', 'embeds' ); 631 632 // Send! 633 try { 634 $send = $phpmailer->send(); 635 636 /** 637 * Fires after PHPMailer has successfully sent an email. 638 * 639 * The firing of this action does not necessarily mean that the recipient(s) received the 640 * email successfully. It only means that the `send` method above was able to 641 * process the request without any errors. 642 * 643 * @since 5.9.0 644 * @since 6.9.0 The `$embeds` element was added to the `$mail_data` array. 645 * 646 * @param array $mail_data { 647 * An array containing the email recipient(s), subject, message, headers, attachments, and embeds. 648 * 649 * @type string[] $to Email addresses to send message. 650 * @type string $subject Email subject. 651 * @type string $message Message contents. 652 * @type string[] $headers Additional headers. 653 * @type string[] $attachments Paths to files to attach. 654 * @type string[] $embeds Paths to files to embed. 655 * } 656 */ 657 do_action( 'wp_mail_succeeded', $mail_data ); 658 659 return $send; 660 } catch ( PHPMailer\PHPMailer\Exception $e ) { 661 $mail_data['phpmailer_exception_code'] = $e->getCode(); 662 663 /** 664 * Fires after a PHPMailer exception is caught. 665 * 666 * @since 4.4.0 667 * 668 * @param WP_Error $error A WP_Error object with the PHPMailer\PHPMailer\Exception message, and an array 669 * containing the mail recipient, subject, message, headers, attachments, and embeds. 670 */ 671 do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_data ) ); 672 673 return false; 674 } 675 } 676 endif; 677 678 if ( ! function_exists( 'wp_authenticate' ) ) : 679 /** 680 * Authenticates a user, confirming the login credentials are valid. 681 * 682 * @since 2.5.0 683 * @since 4.5.0 `$username` now accepts an email address. 684 * 685 * @param string $username User's username or email address. 686 * @param string $password User's password. 687 * @return WP_User|WP_Error WP_User object if the credentials are valid, 688 * otherwise WP_Error. 689 */ 690 function wp_authenticate( 691 $username, 692 #[\SensitiveParameter] 693 $password 694 ) { 695 $username = sanitize_user( $username ); 696 $password = trim( $password ); 697 698 /** 699 * Filters whether a set of user login credentials are valid. 700 * 701 * A WP_User object is returned if the credentials authenticate a user. 702 * WP_Error or null otherwise. 703 * 704 * @since 2.8.0 705 * @since 4.5.0 `$username` now accepts an email address. 706 * 707 * @param null|WP_User|WP_Error $user WP_User if the user is authenticated. 708 * WP_Error or null otherwise. 709 * @param string $username Username or email address. 710 * @param string $password User password. 711 */ 712 $user = apply_filters( 'authenticate', null, $username, $password ); 713 714 if ( null === $user || false === $user ) { 715 /* 716 * TODO: What should the error message be? (Or would these even happen?) 717 * Only needed if all authentication handlers fail to return anything. 718 */ 719 $user = new WP_Error( 'authentication_failed', __( '<strong>Error:</strong> Invalid username, email address or incorrect password.' ) ); 720 } 721 722 $ignore_codes = array( 'empty_username', 'empty_password' ); 723 724 if ( is_wp_error( $user ) && ! in_array( $user->get_error_code(), $ignore_codes, true ) ) { 725 $error = $user; 726 727 /** 728 * Fires after a user login has failed. 729 * 730 * @since 2.5.0 731 * @since 4.5.0 The value of `$username` can now be an email address. 732 * @since 5.4.0 The `$error` parameter was added. 733 * 734 * @param string $username Username or email address. 735 * @param WP_Error $error A WP_Error object with the authentication failure details. 736 */ 737 do_action( 'wp_login_failed', $username, $error ); 738 } 739 740 return $user; 741 } 742 endif; 743 744 if ( ! function_exists( 'wp_logout' ) ) : 745 /** 746 * Logs the current user out. 747 * 748 * @since 2.5.0 749 */ 750 function wp_logout() { 751 $user_id = get_current_user_id(); 752 753 wp_destroy_current_session(); 754 wp_clear_auth_cookie(); 755 wp_set_current_user( 0 ); 756 757 /** 758 * Fires after a user is logged out. 759 * 760 * @since 1.5.0 761 * @since 5.5.0 Added the `$user_id` parameter. 762 * 763 * @param int $user_id ID of the user that was logged out. 764 */ 765 do_action( 'wp_logout', $user_id ); 766 } 767 endif; 768 769 if ( ! function_exists( 'wp_validate_auth_cookie' ) ) : 770 /** 771 * Validates authentication cookie. 772 * 773 * The checks include making sure that the authentication cookie is set and 774 * pulling in the contents (if $cookie is not used). 775 * 776 * Makes sure the cookie is not expired. Verifies the hash in cookie is what is 777 * should be and compares the two. 778 * 779 * @since 2.5.0 780 * 781 * @global int $login_grace_period 782 * 783 * @param string $cookie Optional. If used, will validate contents instead of cookie's. 784 * @param string $scheme Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'. 785 * Note: This does *not* default to 'auth' like other cookie functions. 786 * @return int|false User ID if valid cookie, false if invalid. 787 */ 788 function wp_validate_auth_cookie( $cookie = '', $scheme = '' ) { 789 $cookie_elements = wp_parse_auth_cookie( $cookie, $scheme ); 790 if ( ! $cookie_elements ) { 791 /** 792 * Fires if an authentication cookie is malformed. 793 * 794 * @since 2.7.0 795 * 796 * @param string $cookie Malformed auth cookie. 797 * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth', 798 * or 'logged_in'. 799 */ 800 do_action( 'auth_cookie_malformed', $cookie, $scheme ); 801 return false; 802 } 803 804 $scheme = $cookie_elements['scheme']; 805 $username = $cookie_elements['username']; 806 $hmac = $cookie_elements['hmac']; 807 $token = $cookie_elements['token']; 808 $expiration = $cookie_elements['expiration']; 809 810 $expired = (int) $expiration; 811 812 // Allow a grace period for POST and Ajax requests. 813 if ( wp_doing_ajax() || 'POST' === $_SERVER['REQUEST_METHOD'] ) { 814 $expired += HOUR_IN_SECONDS; 815 } 816 817 // Quick check to see if an honest cookie has expired. 818 if ( $expired < time() ) { 819 /** 820 * Fires once an authentication cookie has expired. 821 * 822 * @since 2.7.0 823 * 824 * @param string[] $cookie_elements { 825 * Authentication cookie components. None of the components should be assumed 826 * to be valid as they come directly from a client-provided cookie value. 827 * 828 * @type string $username User's username. 829 * @type string $expiration The time the cookie expires as a UNIX timestamp. 830 * @type string $token User's session token used. 831 * @type string $hmac The security hash for the cookie. 832 * @type string $scheme The cookie scheme to use. 833 * } 834 */ 835 do_action( 'auth_cookie_expired', $cookie_elements ); 836 return false; 837 } 838 839 $user = get_user_by( 'login', $username ); 840 if ( ! $user ) { 841 /** 842 * Fires if a bad username is entered in the user authentication process. 843 * 844 * @since 2.7.0 845 * 846 * @param string[] $cookie_elements { 847 * Authentication cookie components. None of the components should be assumed 848 * to be valid as they come directly from a client-provided cookie value. 849 * 850 * @type string $username User's username. 851 * @type string $expiration The time the cookie expires as a UNIX timestamp. 852 * @type string $token User's session token used. 853 * @type string $hmac The security hash for the cookie. 854 * @type string $scheme The cookie scheme to use. 855 * } 856 */ 857 do_action( 'auth_cookie_bad_username', $cookie_elements ); 858 return false; 859 } 860 861 if ( str_starts_with( $user->user_pass, '$P$' ) || str_starts_with( $user->user_pass, '$2y$' ) ) { 862 // Retain previous behaviour of phpass or vanilla bcrypt hashed passwords. 863 $pass_frag = substr( $user->user_pass, 8, 4 ); 864 } else { 865 // Otherwise, use a substring from the end of the hash to avoid dealing with potentially long hash prefixes. 866 $pass_frag = substr( $user->user_pass, -4 ); 867 } 868 869 $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme ); 870 871 $hash = hash_hmac( 'sha256', $username . '|' . $expiration . '|' . $token, $key ); 872 873 if ( ! hash_equals( $hash, $hmac ) ) { 874 /** 875 * Fires if a bad authentication cookie hash is encountered. 876 * 877 * @since 2.7.0 878 * 879 * @param string[] $cookie_elements { 880 * Authentication cookie components. None of the components should be assumed 881 * to be valid as they come directly from a client-provided cookie value. 882 * 883 * @type string $username User's username. 884 * @type string $expiration The time the cookie expires as a UNIX timestamp. 885 * @type string $token User's session token used. 886 * @type string $hmac The security hash for the cookie. 887 * @type string $scheme The cookie scheme to use. 888 * } 889 */ 890 do_action( 'auth_cookie_bad_hash', $cookie_elements ); 891 return false; 892 } 893 894 $manager = WP_Session_Tokens::get_instance( $user->ID ); 895 if ( ! $manager->verify( $token ) ) { 896 /** 897 * Fires if a bad session token is encountered. 898 * 899 * @since 4.0.0 900 * 901 * @param string[] $cookie_elements { 902 * Authentication cookie components. None of the components should be assumed 903 * to be valid as they come directly from a client-provided cookie value. 904 * 905 * @type string $username User's username. 906 * @type string $expiration The time the cookie expires as a UNIX timestamp. 907 * @type string $token User's session token used. 908 * @type string $hmac The security hash for the cookie. 909 * @type string $scheme The cookie scheme to use. 910 * } 911 */ 912 do_action( 'auth_cookie_bad_session_token', $cookie_elements ); 913 return false; 914 } 915 916 // Ajax/POST grace period set above. 917 if ( $expiration < time() ) { 918 $GLOBALS['login_grace_period'] = 1; 919 } 920 921 /** 922 * Fires once an authentication cookie has been validated. 923 * 924 * @since 2.7.0 925 * 926 * @param string[] $cookie_elements { 927 * Authentication cookie components. 928 * 929 * @type string $username User's username. 930 * @type string $expiration The time the cookie expires as a UNIX timestamp. 931 * @type string $token User's session token used. 932 * @type string $hmac The security hash for the cookie. 933 * @type string $scheme The cookie scheme to use. 934 * } 935 * @param WP_User $user User object. 936 */ 937 do_action( 'auth_cookie_valid', $cookie_elements, $user ); 938 939 return $user->ID; 940 } 941 endif; 942 943 if ( ! function_exists( 'wp_generate_auth_cookie' ) ) : 944 /** 945 * Generates authentication cookie contents. 946 * 947 * @since 2.5.0 948 * @since 4.0.0 The `$token` parameter was added. 949 * 950 * @param int $user_id User ID. 951 * @param int $expiration The time the cookie expires as a UNIX timestamp. 952 * @param string $scheme Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'. 953 * Default 'auth'. 954 * @param string $token User's session token to use for this cookie. 955 * @return string Authentication cookie contents. Empty string if user does not exist. 956 */ 957 function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) { 958 $user = get_userdata( $user_id ); 959 if ( ! $user ) { 960 return ''; 961 } 962 963 if ( ! $token ) { 964 $manager = WP_Session_Tokens::get_instance( $user_id ); 965 $token = $manager->create( $expiration ); 966 } 967 968 if ( str_starts_with( $user->user_pass, '$P$' ) || str_starts_with( $user->user_pass, '$2y$' ) ) { 969 // Retain previous behaviour of phpass or vanilla bcrypt hashed passwords. 970 $pass_frag = substr( $user->user_pass, 8, 4 ); 971 } else { 972 // Otherwise, use a substring from the end of the hash to avoid dealing with potentially long hash prefixes. 973 $pass_frag = substr( $user->user_pass, -4 ); 974 } 975 976 $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme ); 977 978 $hash = hash_hmac( 'sha256', $user->user_login . '|' . $expiration . '|' . $token, $key ); 979 980 $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash; 981 982 /** 983 * Filters the authentication cookie. 984 * 985 * @since 2.5.0 986 * @since 4.0.0 The `$token` parameter was added. 987 * 988 * @param string $cookie Authentication cookie. 989 * @param int $user_id User ID. 990 * @param int $expiration The time the cookie expires as a UNIX timestamp. 991 * @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'. 992 * @param string $token User's session token used. 993 */ 994 return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token ); 995 } 996 endif; 997 998 if ( ! function_exists( 'wp_parse_auth_cookie' ) ) : 999 /** 1000 * Parses a cookie into its components. 1001 * 1002 * @since 2.7.0 1003 * @since 4.0.0 The `$token` element was added to the return value. 1004 * 1005 * @param string $cookie Authentication cookie. 1006 * @param string $scheme Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'. 1007 * @return string[]|false { 1008 * Authentication cookie components. None of the components should be assumed 1009 * to be valid as they come directly from a client-provided cookie value. If 1010 * the cookie value is malformed, false is returned. 1011 * 1012 * @type string $username User's username. 1013 * @type string $expiration The time the cookie expires as a UNIX timestamp. 1014 * @type string $token User's session token used. 1015 * @type string $hmac The security hash for the cookie. 1016 * @type string $scheme The cookie scheme to use. 1017 * } 1018 */ 1019 function wp_parse_auth_cookie( $cookie = '', $scheme = '' ) { 1020 if ( empty( $cookie ) ) { 1021 switch ( $scheme ) { 1022 case 'auth': 1023 $cookie_name = AUTH_COOKIE; 1024 break; 1025 case 'secure_auth': 1026 $cookie_name = SECURE_AUTH_COOKIE; 1027 break; 1028 case 'logged_in': 1029 $cookie_name = LOGGED_IN_COOKIE; 1030 break; 1031 default: 1032 if ( is_ssl() ) { 1033 $cookie_name = SECURE_AUTH_COOKIE; 1034 $scheme = 'secure_auth'; 1035 } else { 1036 $cookie_name = AUTH_COOKIE; 1037 $scheme = 'auth'; 1038 } 1039 } 1040 1041 if ( empty( $_COOKIE[ $cookie_name ] ) ) { 1042 return false; 1043 } 1044 $cookie = $_COOKIE[ $cookie_name ]; 1045 } 1046 1047 $cookie_elements = explode( '|', $cookie ); 1048 if ( count( $cookie_elements ) !== 4 ) { 1049 return false; 1050 } 1051 1052 list( $username, $expiration, $token, $hmac ) = $cookie_elements; 1053 1054 return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' ); 1055 } 1056 endif; 1057 1058 if ( ! function_exists( 'wp_set_auth_cookie' ) ) : 1059 /** 1060 * Sets the authentication cookies for a given user ID. 1061 * 1062 * The `$remember` parameter controls cookie persistence: 1063 * - If true, the cookie is persistent (default 14 days, filterable via {@see 'auth_cookie_expiration'}). 1064 * - If false, the cookie is a browser session cookie (expires when the browser closes). 1065 * Internally, {@see 'auth_cookie_expiration'} is still applied, to expire the login after 1066 * two days or when the browser is closed, whichever occurs first. 1067 * 1068 * @since 2.5.0 1069 * @since 4.3.0 Added the `$token` parameter. 1070 * 1071 * @param int $user_id User ID. 1072 * @param bool $remember Whether to remember the user. 1073 * @param bool|string $secure Whether the auth cookie should only be sent over HTTPS. Default is an empty 1074 * string which means the value of `is_ssl()` will be used. 1075 * @param string $token Optional. User's session token to use for this cookie. 1076 */ 1077 function wp_set_auth_cookie( $user_id, $remember = false, $secure = '', $token = '' ) { 1078 if ( $remember ) { 1079 /** 1080 * Filters the duration of the authentication cookie expiration period. 1081 * 1082 * @since 2.8.0 1083 * 1084 * @param int $length Duration of the expiration period in seconds. 1085 * @param int $user_id User ID. 1086 * @param bool $remember Whether to remember the user login. Default false. 1087 */ 1088 $expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember ); 1089 1090 /* 1091 * Ensure the browser will continue to send the cookie after the expiration time is reached. 1092 * Needed for the login grace period in wp_validate_auth_cookie(). 1093 */ 1094 $expire = $expiration + ( 12 * HOUR_IN_SECONDS ); 1095 } else { 1096 /** This filter is documented in wp-includes/pluggable.php */ 1097 $expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember ); 1098 $expire = 0; 1099 } 1100 1101 if ( '' === $secure ) { 1102 $secure = is_ssl(); 1103 } 1104 1105 // Front-end cookie is secure when the auth cookie is secure and the site's home URL uses HTTPS. 1106 $secure_logged_in_cookie = $secure && 'https' === parse_url( get_option( 'home' ), PHP_URL_SCHEME ); 1107 1108 /** 1109 * Filters whether the auth cookie should only be sent over HTTPS. 1110 * 1111 * @since 3.1.0 1112 * 1113 * @param bool $secure Whether the cookie should only be sent over HTTPS. 1114 * @param int $user_id User ID. 1115 */ 1116 $secure = apply_filters( 'secure_auth_cookie', $secure, $user_id ); 1117 1118 /** 1119 * Filters whether the logged in cookie should only be sent over HTTPS. 1120 * 1121 * @since 3.1.0 1122 * 1123 * @param bool $secure_logged_in_cookie Whether the logged in cookie should only be sent over HTTPS. 1124 * @param int $user_id User ID. 1125 * @param bool $secure Whether the auth cookie should only be sent over HTTPS. 1126 */ 1127 $secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure ); 1128 1129 if ( $secure ) { 1130 $auth_cookie_name = SECURE_AUTH_COOKIE; 1131 $scheme = 'secure_auth'; 1132 } else { 1133 $auth_cookie_name = AUTH_COOKIE; 1134 $scheme = 'auth'; 1135 } 1136 1137 if ( '' === $token ) { 1138 $manager = WP_Session_Tokens::get_instance( $user_id ); 1139 $token = $manager->create( $expiration ); 1140 } 1141 1142 $auth_cookie = wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token ); 1143 $logged_in_cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token ); 1144 1145 /** 1146 * Fires immediately before the authentication cookie is set. 1147 * 1148 * @since 2.5.0 1149 * @since 4.9.0 The `$token` parameter was added. 1150 * 1151 * @param string $auth_cookie Authentication cookie value. 1152 * @param int $expire The time the login grace period expires as a UNIX timestamp. 1153 * Default is 12 hours past the cookie's expiration time. 1154 * @param int $expiration The time when the authentication cookie expires as a UNIX timestamp. 1155 * Default is 14 days from now. 1156 * @param int $user_id User ID. 1157 * @param string $scheme Authentication scheme. Values include 'auth' or 'secure_auth'. 1158 * @param string $token User's session token to use for this cookie. 1159 */ 1160 do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme, $token ); 1161 1162 /** 1163 * Fires immediately before the logged-in authentication cookie is set. 1164 * 1165 * @since 2.6.0 1166 * @since 4.9.0 The `$token` parameter was added. 1167 * 1168 * @param string $logged_in_cookie The logged-in cookie value. 1169 * @param int $expire The time the login grace period expires as a UNIX timestamp. 1170 * Default is 12 hours past the cookie's expiration time. 1171 * @param int $expiration The time when the logged-in authentication cookie expires as a UNIX timestamp. 1172 * Default is 14 days from now. 1173 * @param int $user_id User ID. 1174 * @param string $scheme Authentication scheme. Default 'logged_in'. 1175 * @param string $token User's session token to use for this cookie. 1176 */ 1177 do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in', $token ); 1178 1179 /** 1180 * Allows preventing auth cookies from actually being sent to the client. 1181 * 1182 * @since 4.7.4 1183 * @since 6.2.0 The `$expire`, `$expiration`, `$user_id`, `$scheme`, and `$token` parameters were added. 1184 * 1185 * @param bool $send Whether to send auth cookies to the client. Default true. 1186 * @param int $expire The time the login grace period expires as a UNIX timestamp. 1187 * Default is 12 hours past the cookie's expiration time. Zero when clearing cookies. 1188 * @param int $expiration The time when the logged-in authentication cookie expires as a UNIX timestamp. 1189 * Default is 14 days from now. Zero when clearing cookies. 1190 * @param int $user_id User ID. Zero when clearing cookies. 1191 * @param string $scheme Authentication scheme. Values include 'auth' or 'secure_auth'. 1192 * Empty string when clearing cookies. 1193 * @param string $token User's session token to use for this cookie. Empty string when clearing cookies. 1194 */ 1195 if ( ! apply_filters( 'send_auth_cookies', true, $expire, $expiration, $user_id, $scheme, $token ) ) { 1196 return; 1197 } 1198 1199 setcookie( $auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true ); 1200 setcookie( $auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true ); 1201 setcookie( LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true ); 1202 if ( COOKIEPATH !== SITECOOKIEPATH ) { 1203 setcookie( LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true ); 1204 } 1205 } 1206 endif; 1207 1208 if ( ! function_exists( 'wp_clear_auth_cookie' ) ) : 1209 /** 1210 * Removes all of the cookies associated with authentication. 1211 * 1212 * @since 2.5.0 1213 */ 1214 function wp_clear_auth_cookie() { 1215 /** 1216 * Fires just before the authentication cookies are cleared. 1217 * 1218 * @since 2.7.0 1219 */ 1220 do_action( 'clear_auth_cookie' ); 1221 1222 /** This filter is documented in wp-includes/pluggable.php */ 1223 if ( ! apply_filters( 'send_auth_cookies', true, 0, 0, 0, '', '' ) ) { 1224 return; 1225 } 1226 1227 // Auth cookies. 1228 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN ); 1229 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN ); 1230 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN ); 1231 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN ); 1232 setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); 1233 setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); 1234 1235 // Settings cookies. 1236 setcookie( 'wp-settings-' . get_current_user_id(), ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH ); 1237 setcookie( 'wp-settings-time-' . get_current_user_id(), ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH ); 1238 1239 // Old cookies. 1240 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); 1241 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); 1242 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); 1243 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); 1244 1245 // Even older cookies. 1246 setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); 1247 setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); 1248 setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); 1249 setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); 1250 1251 // Post password cookie. 1252 setcookie( 'wp-postpass_' . COOKIEHASH, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); 1253 } 1254 endif; 1255 1256 if ( ! function_exists( 'is_user_logged_in' ) ) : 1257 /** 1258 * Determines whether the current visitor is a logged in user. 1259 * 1260 * For more information on this and similar theme functions, check out 1261 * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/ 1262 * Conditional Tags} article in the Theme Developer Handbook. 1263 * 1264 * @since 2.0.0 1265 * 1266 * @return bool True if user is logged in, false if not logged in. 1267 */ 1268 function is_user_logged_in() { 1269 $user = wp_get_current_user(); 1270 1271 return $user->exists(); 1272 } 1273 endif; 1274 1275 if ( ! function_exists( 'auth_redirect' ) ) : 1276 /** 1277 * Checks if a user is logged in, if not it redirects them to the login page. 1278 * 1279 * When this code is called from a page, it checks to see if the user viewing the page is logged in. 1280 * If the user is not logged in, they are redirected to the login page. The user is redirected 1281 * in such a way that, upon logging in, they will be sent directly to the page they were originally 1282 * trying to access. 1283 * 1284 * @since 1.5.0 1285 */ 1286 function auth_redirect() { 1287 $secure = ( is_ssl() || force_ssl_admin() ); 1288 1289 /** 1290 * Filters whether to use a secure authentication redirect. 1291 * 1292 * @since 3.1.0 1293 * 1294 * @param bool $secure Whether to use a secure authentication redirect. Default false. 1295 */ 1296 $secure = apply_filters( 'secure_auth_redirect', $secure ); 1297 1298 // If https is required and request is http, redirect. 1299 if ( $secure && ! is_ssl() && str_contains( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) { 1300 if ( str_starts_with( $_SERVER['REQUEST_URI'], 'http' ) ) { 1301 wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) ); 1302 exit; 1303 } else { 1304 wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); 1305 exit; 1306 } 1307 } 1308 1309 /** 1310 * Filters the authentication redirect scheme. 1311 * 1312 * @since 2.9.0 1313 * 1314 * @param string $scheme Authentication redirect scheme. Default empty. 1315 */ 1316 $scheme = apply_filters( 'auth_redirect_scheme', '' ); 1317 1318 $user_id = wp_validate_auth_cookie( '', $scheme ); 1319 if ( $user_id ) { 1320 /** 1321 * Fires before the authentication redirect. 1322 * 1323 * @since 2.8.0 1324 * 1325 * @param int $user_id User ID. 1326 */ 1327 do_action( 'auth_redirect', $user_id ); 1328 1329 // If the user wants ssl but the session is not ssl, redirect. 1330 if ( ! $secure && get_user_option( 'use_ssl', $user_id ) && str_contains( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) { 1331 if ( str_starts_with( $_SERVER['REQUEST_URI'], 'http' ) ) { 1332 wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) ); 1333 exit; 1334 } else { 1335 wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); 1336 exit; 1337 } 1338 } 1339 1340 return; // The cookie is good, so we're done. 1341 } 1342 1343 // The cookie is no good, so force login. 1344 nocache_headers(); 1345 1346 if ( str_contains( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) { 1347 $redirect = wp_get_referer(); 1348 } else { 1349 $redirect = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); 1350 } 1351 1352 $login_url = wp_login_url( $redirect, true ); 1353 1354 wp_redirect( $login_url ); 1355 exit; 1356 } 1357 endif; 1358 1359 if ( ! function_exists( 'check_admin_referer' ) ) : 1360 /** 1361 * Ensures intent by verifying that a user was referred from another admin page with the correct security nonce. 1362 * 1363 * This function ensures the user intends to perform a given action, which helps protect against clickjacking style 1364 * attacks. It verifies intent, not authorization, therefore it does not verify the user's capabilities. This should 1365 * be performed with `current_user_can()` or similar. 1366 * 1367 * If the nonce value is invalid, the function will exit with an "Are You Sure?" style message. 1368 * 1369 * @since 1.2.0 1370 * @since 2.5.0 The `$query_arg` parameter was added. 1371 * 1372 * @param int|string $action The nonce action. 1373 * @param string $query_arg Optional. Key to check for nonce in `$_REQUEST`. Default '_wpnonce'. 1374 * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago, 1375 * 2 if the nonce is valid and generated between 12-24 hours ago. 1376 * False if the nonce is invalid. Only possible when `$action` is -1, 1377 * as the function otherwise exits rather than returning false. 1378 * @phpstan-return ( $action is -1 ? int|false : int ) 1379 */ 1380 function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) { 1381 if ( -1 === $action ) { 1382 _doing_it_wrong( __FUNCTION__, __( 'You should specify an action to be verified by using the first parameter.' ), '3.2.0' ); 1383 } 1384 1385 $adminurl = strtolower( admin_url() ); 1386 $referer = strtolower( wp_get_referer() ); 1387 $result = isset( $_REQUEST[ $query_arg ] ) ? wp_verify_nonce( $_REQUEST[ $query_arg ], $action ) : false; 1388 1389 /** 1390 * Fires once the admin request has been validated or not. 1391 * 1392 * @since 1.5.1 1393 * 1394 * @param string $action The nonce action. 1395 * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between 1396 * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago. 1397 */ 1398 do_action( 'check_admin_referer', $action, $result ); 1399 1400 if ( ! $result && ! ( -1 === $action && str_starts_with( $referer, $adminurl ) ) ) { 1401 wp_nonce_ays( $action ); 1402 die(); 1403 } 1404 1405 return $result; 1406 } 1407 endif; 1408 1409 if ( ! function_exists( 'check_ajax_referer' ) ) : 1410 /** 1411 * Verifies the Ajax request to prevent processing requests external of the blog. 1412 * 1413 * @since 2.0.3 1414 * 1415 * @param int|string $action Action nonce. 1416 * @param false|string $query_arg Optional. Key to check for the nonce in `$_REQUEST` (since 2.5). If false, 1417 * `$_REQUEST` values will be evaluated for '_ajax_nonce', and '_wpnonce' 1418 * (in that order). Default false. 1419 * @param bool $stop Optional. Whether to stop early when the nonce cannot be verified. 1420 * Default true. 1421 * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago, 1422 * 2 if the nonce is valid and generated between 12-24 hours ago. 1423 * False if the nonce is invalid. Only possible when `$stop` is false, 1424 * as the function otherwise exits rather than returning false. 1425 * @phpstan-return ( $stop is true ? int : int|false ) 1426 */ 1427 function check_ajax_referer( $action = -1, $query_arg = false, $stop = true ) { 1428 if ( -1 === $action ) { 1429 _doing_it_wrong( __FUNCTION__, __( 'You should specify an action to be verified by using the first parameter.' ), '4.7.0' ); 1430 } 1431 1432 $nonce = ''; 1433 1434 if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) ) { 1435 $nonce = $_REQUEST[ $query_arg ]; 1436 } elseif ( isset( $_REQUEST['_ajax_nonce'] ) ) { 1437 $nonce = $_REQUEST['_ajax_nonce']; 1438 } elseif ( isset( $_REQUEST['_wpnonce'] ) ) { 1439 $nonce = $_REQUEST['_wpnonce']; 1440 } 1441 1442 $result = wp_verify_nonce( $nonce, $action ); 1443 1444 /** 1445 * Fires once the Ajax request has been validated or not. 1446 * 1447 * @since 2.1.0 1448 * 1449 * @param string $action The Ajax nonce action. 1450 * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between 1451 * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago. 1452 */ 1453 do_action( 'check_ajax_referer', $action, $result ); 1454 1455 if ( $stop && false === $result ) { 1456 if ( wp_doing_ajax() ) { 1457 wp_die( -1, 403 ); 1458 } else { 1459 die( '-1' ); 1460 } 1461 } 1462 1463 return $result; 1464 } 1465 endif; 1466 1467 if ( ! function_exists( 'wp_redirect' ) ) : 1468 /** 1469 * Redirects to another page. 1470 * 1471 * Note: wp_redirect() does not exit automatically, and should almost always be 1472 * followed by a call to `exit;`: 1473 * 1474 * wp_redirect( $url ); 1475 * exit; 1476 * 1477 * Exiting can also be selectively manipulated by using wp_redirect() as a conditional 1478 * in conjunction with the {@see 'wp_redirect'} and {@see 'wp_redirect_status'} filters: 1479 * 1480 * if ( wp_redirect( $url ) ) { 1481 * exit; 1482 * } 1483 * 1484 * @since 1.5.1 1485 * @since 5.1.0 The `$x_redirect_by` parameter was added. 1486 * @since 5.4.0 On invalid status codes, wp_die() is called. 1487 * 1488 * @global bool $is_IIS 1489 * 1490 * @param string $location The path or URL to redirect to. 1491 * @param int $status Optional. HTTP response status code to use. Default '302' (Moved Temporarily). 1492 * @param string|false $x_redirect_by Optional. The application doing the redirect or false to omit. Default 'WordPress'. 1493 * @return bool False if the redirect was canceled, true otherwise. 1494 */ 1495 function wp_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) { 1496 global $is_IIS; 1497 1498 /** 1499 * Filters the redirect location. 1500 * 1501 * @since 2.1.0 1502 * 1503 * @param string $location The path or URL to redirect to. 1504 * @param int $status The HTTP response status code to use. 1505 */ 1506 $location = apply_filters( 'wp_redirect', $location, $status ); 1507 1508 /** 1509 * Filters the redirect HTTP response status code to use. 1510 * 1511 * @since 2.3.0 1512 * 1513 * @param int $status The HTTP response status code to use. 1514 * @param string $location The path or URL to redirect to. 1515 */ 1516 $status = apply_filters( 'wp_redirect_status', $status, $location ); 1517 1518 if ( ! $location ) { 1519 return false; 1520 } 1521 1522 if ( $status < 300 || 399 < $status ) { 1523 wp_die( __( 'HTTP redirect status code must be a redirection code, 3xx.' ) ); 1524 } 1525 1526 $location = wp_sanitize_redirect( $location ); 1527 1528 if ( ! $is_IIS && 'cgi-fcgi' !== PHP_SAPI ) { 1529 status_header( $status ); // This causes problems on IIS and some FastCGI setups. 1530 } 1531 1532 /** 1533 * Filters the value of the `X-Redirect-By` HTTP header. 1534 * 1535 * Allows applications to identify themselves when they're doing a redirect. 1536 * 1537 * @since 5.1.0 1538 * 1539 * @param string|false $x_redirect_by The application doing the redirect or false to omit the header. 1540 * @param int $status Status code to use. 1541 * @param string $location The path to redirect to. 1542 */ 1543 $x_redirect_by = apply_filters( 'x_redirect_by', $x_redirect_by, $status, $location ); 1544 if ( is_string( $x_redirect_by ) ) { 1545 header( "X-Redirect-By: $x_redirect_by" ); 1546 } 1547 1548 header( "Location: $location", true, $status ); 1549 1550 return true; 1551 } 1552 endif; 1553 1554 if ( ! function_exists( 'wp_sanitize_redirect' ) ) : 1555 /** 1556 * Sanitizes a URL for use in a redirect. 1557 * 1558 * @since 2.3.0 1559 * 1560 * @param string $location The path to redirect to. 1561 * @return string Redirect-sanitized URL. 1562 */ 1563 function wp_sanitize_redirect( $location ) { 1564 // Encode spaces. 1565 $location = str_replace( ' ', '%20', $location ); 1566 1567 $regex = '/ 1568 ( 1569 (?: [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx 1570 | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2 1571 | [\xE1-\xEC][\x80-\xBF]{2} 1572 | \xED[\x80-\x9F][\x80-\xBF] 1573 | [\xEE-\xEF][\x80-\xBF]{2} 1574 | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3 1575 | [\xF1-\xF3][\x80-\xBF]{3} 1576 | \xF4[\x80-\x8F][\x80-\xBF]{2} 1577 ){1,40} # ...one or more times 1578 )/x'; 1579 $location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location ); 1580 $location = preg_replace( '|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()@]|i', '', $location ); 1581 $location = wp_kses_no_null( $location ); 1582 1583 // Remove %0D and %0A from location. 1584 $strip = array( '%0d', '%0a', '%0D', '%0A' ); 1585 return _deep_replace( $strip, $location ); 1586 } 1587 1588 /** 1589 * URL encodes UTF-8 characters in a URL. 1590 * 1591 * @ignore 1592 * @since 4.2.0 1593 * @access private 1594 * 1595 * @see wp_sanitize_redirect() 1596 * 1597 * @param array $matches RegEx matches against the redirect location. 1598 * @return string URL-encoded version of the first RegEx match. 1599 */ 1600 function _wp_sanitize_utf8_in_redirect( $matches ) { 1601 return urlencode( $matches[0] ); 1602 } 1603 endif; 1604 1605 if ( ! function_exists( 'wp_safe_redirect' ) ) : 1606 /** 1607 * Performs a safe (local) redirect, using wp_redirect(). 1608 * 1609 * Checks whether the $location is using an allowed host, if it has an absolute 1610 * path. A plugin can therefore set or remove allowed host(s) to or from the 1611 * list. 1612 * 1613 * If the host is not allowed, then the redirect defaults to wp-admin on the siteurl 1614 * instead. This prevents malicious redirects which redirect to another host, 1615 * but only used in a few places. 1616 * 1617 * Note: wp_safe_redirect() does not exit automatically, and should almost always be 1618 * followed by a call to `exit;`: 1619 * 1620 * wp_safe_redirect( $url ); 1621 * exit; 1622 * 1623 * Exiting can also be selectively manipulated by using wp_safe_redirect() as a conditional 1624 * in conjunction with the {@see 'wp_redirect'} and {@see 'wp_redirect_status'} filters: 1625 * 1626 * if ( wp_safe_redirect( $url ) ) { 1627 * exit; 1628 * } 1629 * 1630 * @since 2.3.0 1631 * @since 5.1.0 The return value from wp_redirect() is now passed on, and the `$x_redirect_by` parameter was added. 1632 * 1633 * @param string $location The path or URL to redirect to. 1634 * @param int $status Optional. HTTP response status code to use. Default '302' (Moved Temporarily). 1635 * @param string|false $x_redirect_by Optional. The application doing the redirect or false to omit. Default 'WordPress'. 1636 * @return bool False if the redirect was canceled, true otherwise. 1637 */ 1638 function wp_safe_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) { 1639 1640 // Need to look at the URL the way it will end up in wp_redirect(). 1641 $location = wp_sanitize_redirect( $location ); 1642 1643 /** 1644 * Filters the redirect fallback URL for when the provided redirect is not safe (local). 1645 * 1646 * @since 4.3.0 1647 * 1648 * @param string $fallback_url The fallback URL to use by default. 1649 * @param int $status The HTTP response status code to use. 1650 */ 1651 $fallback_url = apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ); 1652 1653 $location = wp_validate_redirect( $location, $fallback_url ); 1654 1655 return wp_redirect( $location, $status, $x_redirect_by ); 1656 } 1657 endif; 1658 1659 if ( ! function_exists( 'wp_validate_redirect' ) ) : 1660 /** 1661 * Validates a URL for use in a redirect. 1662 * 1663 * Checks whether the $location is using an allowed host, if it has an absolute 1664 * path. A plugin can therefore set or remove allowed host(s) to or from the 1665 * list. 1666 * 1667 * If the host is not allowed, then the redirect is to $fallback_url supplied. 1668 * 1669 * @since 2.8.1 1670 * 1671 * @param string $location The redirect to validate. 1672 * @param string $fallback_url The value to return if $location is not allowed. 1673 * @return string Redirect-sanitized URL. 1674 */ 1675 function wp_validate_redirect( $location, $fallback_url = '' ) { 1676 $location = wp_sanitize_redirect( trim( $location, " \t\n\r\0\x08\x0B" ) ); 1677 // Browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'. 1678 if ( str_starts_with( $location, '//' ) ) { 1679 $location = 'http:' . $location; 1680 } 1681 1682 /* 1683 * In PHP 5 parse_url() may fail if the URL query part contains 'http://'. 1684 * See https://bugs.php.net/bug.php?id=38143 1685 */ 1686 $cut = strpos( $location, '?' ); 1687 $test = $cut ? substr( $location, 0, $cut ) : $location; 1688 1689 $lp = parse_url( $test ); 1690 1691 // Give up if malformed URL. 1692 if ( false === $lp ) { 1693 return $fallback_url; 1694 } 1695 1696 // Allow only 'http' and 'https' schemes. No 'data:', etc. 1697 if ( isset( $lp['scheme'] ) && ! ( 'http' === $lp['scheme'] || 'https' === $lp['scheme'] ) ) { 1698 return $fallback_url; 1699 } 1700 1701 if ( ! isset( $lp['host'] ) && ! empty( $lp['path'] ) && '/' !== $lp['path'][0] ) { 1702 $path = ''; 1703 if ( ! empty( $_SERVER['REQUEST_URI'] ) ) { 1704 $path = dirname( parse_url( 'http://placeholder' . $_SERVER['REQUEST_URI'], PHP_URL_PATH ) . '?' ); 1705 $path = wp_normalize_path( $path ); 1706 } 1707 $location = '/' . ltrim( $path . '/', '/' ) . $location; 1708 } 1709 1710 /* 1711 * Reject if certain components are set but host is not. 1712 * This catches URLs like https:host.com for which parse_url() does not set the host field. 1713 */ 1714 if ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) { 1715 return $fallback_url; 1716 } 1717 1718 // Reject malformed components parse_url() can return on odd inputs. 1719 foreach ( array( 'user', 'pass', 'host' ) as $component ) { 1720 if ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) { 1721 return $fallback_url; 1722 } 1723 } 1724 1725 $wpp = parse_url( home_url() ); 1726 1727 /** 1728 * Filters the list of allowed hosts to redirect to. 1729 * 1730 * @since 2.3.0 1731 * 1732 * @param string[] $hosts An array of allowed host names. 1733 * @param string $host The host name of the redirect destination; empty string if not set. 1734 */ 1735 $allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array( $wpp['host'] ), $lp['host'] ?? '' ); 1736 1737 if ( isset( $lp['host'] ) && ( ! in_array( $lp['host'], $allowed_hosts, true ) && strtolower( $wpp['host'] ) !== $lp['host'] ) ) { 1738 $location = $fallback_url; 1739 } 1740 1741 return $location; 1742 } 1743 endif; 1744 1745 if ( ! function_exists( 'wp_notify_postauthor' ) ) : 1746 /** 1747 * Notifies an author (and/or others) of a comment/trackback/pingback on a post. 1748 * 1749 * @since 1.0.0 1750 * 1751 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object. 1752 * @param string $deprecated Not used. 1753 * @return bool True on completion. False if no email addresses were specified. 1754 */ 1755 function wp_notify_postauthor( $comment_id, $deprecated = null ) { 1756 if ( null !== $deprecated ) { 1757 _deprecated_argument( __FUNCTION__, '3.8.0' ); 1758 } 1759 1760 $comment = get_comment( $comment_id ); 1761 if ( empty( $comment ) || empty( $comment->comment_post_ID ) ) { 1762 return false; 1763 } 1764 1765 $post = get_post( $comment->comment_post_ID ); 1766 $author = get_userdata( $post->post_author ); 1767 1768 // Who to notify? By default, just the post author, but others can be added. 1769 $emails = array(); 1770 if ( $author ) { 1771 $emails[] = $author->user_email; 1772 } 1773 1774 /** 1775 * Filters the list of email addresses to receive a comment notification. 1776 * 1777 * By default, only post authors are notified of comments. This filter allows 1778 * others to be added. 1779 * 1780 * @since 3.7.0 1781 * 1782 * @param string[] $emails An array of email addresses to receive a comment notification. 1783 * @param string $comment_id The comment ID as a numeric string. 1784 */ 1785 $emails = apply_filters( 'comment_notification_recipients', $emails, $comment->comment_ID ); 1786 $emails = array_filter( $emails ); 1787 1788 // If there are no addresses to send the comment to, bail. 1789 if ( ! count( $emails ) ) { 1790 return false; 1791 } 1792 1793 // Facilitate unsetting below without knowing the keys. 1794 $emails = array_flip( $emails ); 1795 1796 /** 1797 * Filters whether to notify comment authors of their comments on their own posts. 1798 * 1799 * By default, comment authors aren't notified of their comments on their own 1800 * posts. This filter allows you to override that. 1801 * 1802 * @since 3.8.0 1803 * 1804 * @param bool $notify Whether to notify the post author of their own comment. 1805 * Default false. 1806 * @param string $comment_id The comment ID as a numeric string. 1807 */ 1808 $notify_author = apply_filters( 'comment_notification_notify_author', false, $comment->comment_ID ); 1809 1810 // The comment was left by the author. 1811 if ( $author && ! $notify_author && (int) $comment->user_id === (int) $post->post_author ) { 1812 unset( $emails[ $author->user_email ] ); 1813 } 1814 1815 // The author moderated a comment on their own post. 1816 if ( $author && ! $notify_author && get_current_user_id() === (int) $post->post_author ) { 1817 unset( $emails[ $author->user_email ] ); 1818 } 1819 1820 // The post author is no longer a member of the blog. 1821 if ( $author && ! $notify_author && ! user_can( $post->post_author, 'read_post', $post->ID ) ) { 1822 unset( $emails[ $author->user_email ] ); 1823 } 1824 1825 // If there's no email to send the comment to, bail, otherwise flip array back around for use below. 1826 if ( ! count( $emails ) ) { 1827 return false; 1828 } else { 1829 $emails = array_flip( $emails ); 1830 } 1831 1832 $comment_author_domain = ''; 1833 if ( WP_Http::is_ip_address( $comment->comment_author_IP ) ) { 1834 $comment_author_domain = gethostbyaddr( $comment->comment_author_IP ); 1835 } 1836 1837 /* 1838 * The blogname option is escaped with esc_html() on the way into the database in sanitize_option(). 1839 * We want to reverse this for the plain text arena of emails. 1840 */ 1841 $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); 1842 $comment_content = wp_specialchars_decode( $comment->comment_content ); 1843 1844 /* 1845 * Line breaks in the comment author fields would end the header or line they 1846 * are placed in, letting the comment author add email headers or lines of their own. 1847 */ 1848 $isolate_header_value = static function ( $value ): string { 1849 $is_stringy = is_string( $value ) || ( is_object( $value ) && method_exists( $value, '__toString' ) ); 1850 $value = $is_stringy ? (string) $value : ''; 1851 return trim( (string) preg_replace( '/[\r\n]+/', ' ', $value ) ); 1852 }; 1853 $comment_author = $isolate_header_value( $comment->comment_author ); 1854 $comment_author_email = $isolate_header_value( $comment->comment_author_email ); 1855 $comment_author_url = $isolate_header_value( $comment->comment_author_url ); 1856 1857 $wp_email = 'wordpress@' . preg_replace( '#^www\.#', '', wp_parse_url( network_home_url(), PHP_URL_HOST ) ); 1858 1859 if ( '' === $comment_author ) { 1860 $from = "From: \"$blogname\" <$wp_email>"; 1861 if ( is_email( $comment_author_email ) ) { 1862 $reply_to = "Reply-To: $comment_author_email"; 1863 } 1864 } else { 1865 $from = "From: \"$comment_author\" <$wp_email>"; 1866 if ( is_email( $comment_author_email ) ) { 1867 $reply_to = "Reply-To: \"$comment_author_email\" <$comment_author_email>"; 1868 } 1869 } 1870 1871 $message_headers = "$from\n" 1872 . 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . "\"\n"; 1873 1874 if ( isset( $reply_to ) ) { 1875 $message_headers .= $reply_to . "\n"; 1876 } 1877 1878 /** 1879 * Filters the comment notification email headers. 1880 * 1881 * @since 1.5.2 1882 * 1883 * @param string $message_headers Headers for the comment notification email. 1884 * @param string $comment_id Comment ID as a numeric string. 1885 */ 1886 $message_headers = apply_filters( 'comment_notification_headers', $message_headers, $comment->comment_ID ); 1887 1888 foreach ( $emails as $email ) { 1889 $user = get_user_by( 'email', $email ); 1890 1891 if ( $user ) { 1892 $switched_locale = switch_to_user_locale( $user->ID ); 1893 } else { 1894 $switched_locale = switch_to_locale( get_locale() ); 1895 } 1896 1897 switch ( $comment->comment_type ) { 1898 case 'trackback': 1899 /* translators: %s: Post title. */ 1900 $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n"; 1901 /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ 1902 $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; 1903 /* translators: %s: Trackback/pingback/comment author URL. */ 1904 $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; 1905 /* translators: %s: Comment text. */ 1906 $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; 1907 $notify_message .= __( 'You can see all trackbacks on this post here:' ) . "\r\n"; 1908 /* translators: Trackback notification email subject. 1: Site title, 2: Post title. */ 1909 $subject = sprintf( __( '[%1$s] Trackback: "%2$s"' ), $blogname, $post->post_title ); 1910 break; 1911 1912 case 'pingback': 1913 /* translators: %s: Post title. */ 1914 $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n"; 1915 /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ 1916 $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; 1917 /* translators: %s: Trackback/pingback/comment author URL. */ 1918 $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; 1919 /* translators: %s: Comment text. */ 1920 $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; 1921 $notify_message .= __( 'You can see all pingbacks on this post here:' ) . "\r\n"; 1922 /* translators: Pingback notification email subject. 1: Site title, 2: Post title. */ 1923 $subject = sprintf( __( '[%1$s] Pingback: "%2$s"' ), $blogname, $post->post_title ); 1924 break; 1925 1926 case 'note': 1927 /* translators: %s: Post title. */ 1928 $notify_message = sprintf( __( 'New note on your post "%s"' ), $post->post_title ) . "\r\n"; 1929 /* translators: 1: Note author's name, 2: Note author's IP address, 3: Note author's hostname. */ 1930 $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; 1931 /* translators: %s: Note author email. */ 1932 $notify_message .= sprintf( __( 'Email: %s' ), $comment_author_email ) . "\r\n"; 1933 /* translators: %s: Note text. */ 1934 $notify_message .= sprintf( __( 'Note: %s' ), "\r\n" . ( empty( $comment_content ) ? __( 'resolved/reopened' ) : $comment_content ) ) . "\r\n\r\n"; 1935 $notify_message .= __( 'You can see all notes on this post here:' ) . "\r\n"; 1936 /* translators: Note notification email subject. 1: Site title, 2: Post title. */ 1937 $subject = sprintf( __( '[%1$s] Note: "%2$s"' ), $blogname, $post->post_title ); 1938 break; 1939 1940 default: // Comments. 1941 /* translators: %s: Post title. */ 1942 $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n"; 1943 /* translators: 1: Comment author's name, 2: Comment author's IP address, 3: Comment author's hostname. */ 1944 $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; 1945 /* translators: %s: Comment author email. */ 1946 $notify_message .= sprintf( __( 'Email: %s' ), $comment_author_email ) . "\r\n"; 1947 /* translators: %s: Trackback/pingback/comment author URL. */ 1948 $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; 1949 1950 if ( $comment->comment_parent && user_can( $post->post_author, 'edit_comment', $comment->comment_parent ) ) { 1951 /* translators: Comment moderation. %s: Parent comment edit URL. */ 1952 $notify_message .= sprintf( __( 'In reply to: %s' ), admin_url( "comment.php?action=editcomment&c={$comment->comment_parent}#wpbody-content" ) ) . "\r\n"; 1953 } 1954 1955 /* translators: %s: Comment text. */ 1956 $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; 1957 $notify_message .= __( 'You can see all comments on this post here:' ) . "\r\n"; 1958 /* translators: Comment notification email subject. 1: Site title, 2: Post title. */ 1959 $subject = sprintf( __( '[%1$s] Comment: "%2$s"' ), $blogname, $post->post_title ); 1960 break; 1961 } 1962 1963 if ( 'note' === $comment->comment_type ) { 1964 $notify_message .= get_edit_post_link( $comment->comment_post_ID, 'url' ) . "\r\n"; 1965 } else { 1966 $notify_message .= get_permalink( $comment->comment_post_ID ) . "#comments\r\n\r\n"; 1967 /* translators: %s: Comment URL. */ 1968 $notify_message .= sprintf( __( 'Permalink: %s' ), get_comment_link( $comment ) ) . "\r\n"; 1969 } 1970 1971 if ( 'note' !== $comment->comment_type && user_can( $post->post_author, 'edit_comment', $comment->comment_ID ) ) { 1972 if ( EMPTY_TRASH_DAYS ) { 1973 /* translators: Comment moderation. %s: Comment action URL. */ 1974 $notify_message .= sprintf( __( 'Trash it: %s' ), admin_url( "comment.php?action=trash&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n"; 1975 } else { 1976 /* translators: Comment moderation. %s: Comment action URL. */ 1977 $notify_message .= sprintf( __( 'Delete it: %s' ), admin_url( "comment.php?action=delete&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n"; 1978 } 1979 /* translators: Comment moderation. %s: Comment action URL. */ 1980 $notify_message .= sprintf( __( 'Spam it: %s' ), admin_url( "comment.php?action=spam&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n"; 1981 } 1982 1983 /** 1984 * Filters the comment notification email text. 1985 * 1986 * @since 1.5.2 1987 * 1988 * @param string $notify_message The comment notification email text. 1989 * @param string $comment_id Comment ID as a numeric string. 1990 */ 1991 $notify_message = apply_filters( 'comment_notification_text', $notify_message, $comment->comment_ID ); 1992 1993 /** 1994 * Filters the comment notification email subject. 1995 * 1996 * @since 1.5.2 1997 * 1998 * @param string $subject The comment notification email subject. 1999 * @param string $comment_id Comment ID as a numeric string. 2000 */ 2001 $subject = apply_filters( 'comment_notification_subject', $subject, $comment->comment_ID ); 2002 2003 wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers ); 2004 2005 if ( $switched_locale ) { 2006 restore_previous_locale(); 2007 } 2008 } 2009 2010 return true; 2011 } 2012 endif; 2013 2014 if ( ! function_exists( 'wp_notify_moderator' ) ) : 2015 /** 2016 * Notifies the moderator of the site about a new comment that is awaiting approval. 2017 * 2018 * @since 1.0.0 2019 * 2020 * @global wpdb $wpdb WordPress database abstraction object. 2021 * 2022 * Uses the {@see 'notify_moderator'} filter to determine whether the site moderator 2023 * should be notified, overriding the site setting. 2024 * 2025 * @param int $comment_id Comment ID. 2026 * @return true Always returns true. 2027 */ 2028 function wp_notify_moderator( $comment_id ) { 2029 global $wpdb; 2030 2031 $maybe_notify = get_option( 'moderation_notify' ); 2032 2033 /** 2034 * Filters whether to send the site moderator email notifications, overriding the site setting. 2035 * 2036 * @since 4.4.0 2037 * 2038 * @param bool $maybe_notify Whether to notify blog moderator. 2039 * @param int $comment_id The ID of the comment for the notification. 2040 */ 2041 $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_id ); 2042 2043 if ( ! $maybe_notify ) { 2044 return true; 2045 } 2046 2047 $comment = get_comment( $comment_id ); 2048 $post = get_post( $comment->comment_post_ID ); 2049 $user = get_userdata( $post->post_author ); 2050 // Send to the administration and to the post author if the author can modify the comment. 2051 $emails = array( get_option( 'admin_email' ) ); 2052 if ( $user && user_can( $user->ID, 'edit_comment', $comment_id ) && ! empty( $user->user_email ) ) { 2053 if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) { 2054 $emails[] = $user->user_email; 2055 } 2056 } 2057 2058 $comment_author_domain = ''; 2059 if ( WP_Http::is_ip_address( $comment->comment_author_IP ) ) { 2060 $comment_author_domain = gethostbyaddr( $comment->comment_author_IP ); 2061 } 2062 2063 $comments_waiting = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '0'" ); 2064 2065 /* 2066 * The blogname option is escaped with esc_html() on the way into the database in sanitize_option(). 2067 * We want to reverse this for the plain text arena of emails. 2068 */ 2069 $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); 2070 $comment_content = wp_specialchars_decode( $comment->comment_content ); 2071 2072 /* 2073 * Line breaks in the comment author fields would end the header or line they 2074 * are placed in, letting the comment author add email headers or lines of their own. 2075 */ 2076 $isolate_header_value = static function ( $value ): string { 2077 $is_stringy = is_string( $value ) || ( is_object( $value ) && method_exists( $value, '__toString' ) ); 2078 $value = $is_stringy ? (string) $value : ''; 2079 return trim( (string) preg_replace( '/[\r\n]+/', ' ', $value ) ); 2080 }; 2081 $comment_author = $isolate_header_value( $comment->comment_author ); 2082 $comment_author_email = $isolate_header_value( $comment->comment_author_email ); 2083 $comment_author_url = $isolate_header_value( $comment->comment_author_url ); 2084 2085 $message_headers = ''; 2086 2087 /** 2088 * Filters the list of recipients for comment moderation emails. 2089 * 2090 * @since 3.7.0 2091 * 2092 * @param string[] $emails List of email addresses to notify for comment moderation. 2093 * @param int $comment_id Comment ID. 2094 */ 2095 $emails = apply_filters( 'comment_moderation_recipients', $emails, $comment_id ); 2096 2097 /** 2098 * Filters the comment moderation email headers. 2099 * 2100 * @since 2.8.0 2101 * 2102 * @param string $message_headers Headers for the comment moderation email. 2103 * @param int $comment_id Comment ID. 2104 */ 2105 $message_headers = apply_filters( 'comment_moderation_headers', $message_headers, $comment_id ); 2106 2107 foreach ( $emails as $email ) { 2108 $user = get_user_by( 'email', $email ); 2109 2110 if ( $user ) { 2111 $switched_locale = switch_to_user_locale( $user->ID ); 2112 } else { 2113 $switched_locale = switch_to_locale( get_locale() ); 2114 } 2115 2116 switch ( $comment->comment_type ) { 2117 case 'trackback': 2118 /* translators: %s: Post title. */ 2119 $notify_message = sprintf( __( 'A new trackback on the post "%s" is waiting for your approval' ), $post->post_title ) . "\r\n"; 2120 $notify_message .= get_permalink( $comment->comment_post_ID ) . "\r\n\r\n"; 2121 /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ 2122 $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; 2123 /* translators: %s: Trackback/pingback/comment author URL. */ 2124 $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; 2125 /* translators: %s: Trackback excerpt text. */ 2126 $notify_message .= sprintf( __( 'Trackback excerpt: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; 2127 break; 2128 2129 case 'pingback': 2130 /* translators: %s: Post title. */ 2131 $notify_message = sprintf( __( 'A new pingback on the post "%s" is waiting for your approval' ), $post->post_title ) . "\r\n"; 2132 $notify_message .= get_permalink( $comment->comment_post_ID ) . "\r\n\r\n"; 2133 /* translators: 1: Trackback/pingback website name, 2: Website IP address, 3: Website hostname. */ 2134 $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; 2135 /* translators: %s: Trackback/pingback/comment author URL. */ 2136 $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; 2137 /* translators: %s: Pingback excerpt text. */ 2138 $notify_message .= sprintf( __( 'Pingback excerpt: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; 2139 break; 2140 2141 default: // Comments. 2142 /* translators: %s: Post title. */ 2143 $notify_message = sprintf( __( 'A new comment on the post "%s" is waiting for your approval' ), $post->post_title ) . "\r\n"; 2144 $notify_message .= get_permalink( $comment->comment_post_ID ) . "\r\n\r\n"; 2145 /* translators: 1: Comment author's name, 2: Comment author's IP address, 3: Comment author's hostname. */ 2146 $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; 2147 /* translators: %s: Comment author email. */ 2148 $notify_message .= sprintf( __( 'Email: %s' ), $comment_author_email ) . "\r\n"; 2149 /* translators: %s: Trackback/pingback/comment author URL. */ 2150 $notify_message .= sprintf( __( 'URL: %s' ), $comment_author_url ) . "\r\n"; 2151 2152 if ( $comment->comment_parent ) { 2153 /* translators: Comment moderation. %s: Parent comment edit URL. */ 2154 $notify_message .= sprintf( __( 'In reply to: %s' ), admin_url( "comment.php?action=editcomment&c={$comment->comment_parent}#wpbody-content" ) ) . "\r\n"; 2155 } 2156 2157 /* translators: %s: Comment text. */ 2158 $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n"; 2159 break; 2160 } 2161 2162 /* translators: Comment moderation. %s: Comment action URL. */ 2163 $notify_message .= sprintf( __( 'Approve it: %s' ), admin_url( "comment.php?action=approve&c={$comment_id}#wpbody-content" ) ) . "\r\n"; 2164 2165 if ( EMPTY_TRASH_DAYS ) { 2166 /* translators: Comment moderation. %s: Comment action URL. */ 2167 $notify_message .= sprintf( __( 'Trash it: %s' ), admin_url( "comment.php?action=trash&c={$comment_id}#wpbody-content" ) ) . "\r\n"; 2168 } else { 2169 /* translators: Comment moderation. %s: Comment action URL. */ 2170 $notify_message .= sprintf( __( 'Delete it: %s' ), admin_url( "comment.php?action=delete&c={$comment_id}#wpbody-content" ) ) . "\r\n"; 2171 } 2172 2173 /* translators: Comment moderation. %s: Comment action URL. */ 2174 $notify_message .= sprintf( __( 'Spam it: %s' ), admin_url( "comment.php?action=spam&c={$comment_id}#wpbody-content" ) ) . "\r\n"; 2175 2176 $notify_message .= sprintf( 2177 /* translators: Comment moderation. %s: Number of comments awaiting approval. */ 2178 _n( 2179 'Currently %s comment is waiting for approval. Please visit the moderation panel:', 2180 'Currently %s comments are waiting for approval. Please visit the moderation panel:', 2181 $comments_waiting 2182 ), 2183 number_format_i18n( $comments_waiting ) 2184 ) . "\r\n"; 2185 $notify_message .= admin_url( 'edit-comments.php?comment_status=moderated#wpbody-content' ) . "\r\n"; 2186 2187 /* translators: Comment moderation notification email subject. 1: Site title, 2: Post title. */ 2188 $subject = sprintf( __( '[%1$s] Please moderate: "%2$s"' ), $blogname, $post->post_title ); 2189 2190 /** 2191 * Filters the comment moderation email text. 2192 * 2193 * @since 1.5.2 2194 * 2195 * @param string $notify_message Text of the comment moderation email. 2196 * @param int $comment_id Comment ID. 2197 */ 2198 $notify_message = apply_filters( 'comment_moderation_text', $notify_message, $comment_id ); 2199 2200 /** 2201 * Filters the comment moderation email subject. 2202 * 2203 * @since 1.5.2 2204 * 2205 * @param string $subject Subject of the comment moderation email. 2206 * @param int $comment_id Comment ID. 2207 */ 2208 $subject = apply_filters( 'comment_moderation_subject', $subject, $comment_id ); 2209 2210 wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers ); 2211 2212 if ( $switched_locale ) { 2213 restore_previous_locale(); 2214 } 2215 } 2216 2217 return true; 2218 } 2219 endif; 2220 2221 if ( ! function_exists( 'wp_password_change_notification' ) ) : 2222 /** 2223 * Notifies the blog admin of a user changing password, normally via email. 2224 * 2225 * @since 2.7.0 2226 * 2227 * @param WP_User $user User object. 2228 */ 2229 function wp_password_change_notification( $user ) { 2230 /* 2231 * Send a copy of password change notification to the admin, 2232 * but check to see if it's the admin whose password we're changing, and skip this. 2233 */ 2234 if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) { 2235 2236 $admin_user = get_user_by( 'email', get_option( 'admin_email' ) ); 2237 2238 if ( $admin_user ) { 2239 $switched_locale = switch_to_user_locale( $admin_user->ID ); 2240 } else { 2241 $switched_locale = switch_to_locale( get_locale() ); 2242 } 2243 2244 /* translators: %s: User name. */ 2245 $message = sprintf( __( 'Password changed for user: %s' ), $user->user_login ) . "\r\n"; 2246 2247 /* 2248 * The blogname option is escaped with esc_html() on the way into the database in sanitize_option(). 2249 * We want to reverse this for the plain text arena of emails. 2250 */ 2251 $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); 2252 2253 $wp_password_change_notification_email = array( 2254 'to' => get_option( 'admin_email' ), 2255 /* translators: Password change notification email subject. %s: Site title. */ 2256 'subject' => __( '[%s] Password Changed' ), 2257 'message' => $message, 2258 'headers' => '', 2259 ); 2260 2261 /** 2262 * Filters the contents of the password change notification email sent to the site admin. 2263 * 2264 * @since 4.9.0 2265 * 2266 * @param array $wp_password_change_notification_email { 2267 * Used to build wp_mail(). 2268 * 2269 * @type string $to The intended recipient - site admin email address. 2270 * @type string $subject The subject of the email. 2271 * @type string $message The body of the email. 2272 * @type string $headers The headers of the email. 2273 * } 2274 * @param WP_User $user User object for user whose password was changed. 2275 * @param string $blogname The site title. 2276 */ 2277 $wp_password_change_notification_email = apply_filters( 'wp_password_change_notification_email', $wp_password_change_notification_email, $user, $blogname ); 2278 2279 wp_mail( 2280 $wp_password_change_notification_email['to'], 2281 wp_specialchars_decode( sprintf( $wp_password_change_notification_email['subject'], $blogname ) ), 2282 $wp_password_change_notification_email['message'], 2283 $wp_password_change_notification_email['headers'] 2284 ); 2285 2286 if ( $switched_locale ) { 2287 restore_previous_locale(); 2288 } 2289 } 2290 } 2291 endif; 2292 2293 if ( ! function_exists( 'wp_new_user_notification' ) ) : 2294 /** 2295 * Emails login credentials to a newly-registered user. 2296 * 2297 * A new user registration notification is also sent to admin email. 2298 * 2299 * @since 2.0.0 2300 * @since 4.3.0 The `$plaintext_pass` parameter was changed to `$notify`. 2301 * @since 4.3.1 The `$plaintext_pass` parameter was deprecated. `$notify` added as a third parameter. 2302 * @since 4.6.0 The `$notify` parameter accepts 'user' for sending notification only to the user created. 2303 * 2304 * @param int $user_id User ID. 2305 * @param mixed $deprecated Not used. 2306 * @param string $notify Optional. Type of notification that should happen. Accepts 'admin' or an empty 2307 * string (admin only), 'user', or 'both' (admin and user). Default empty. 2308 */ 2309 function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) { 2310 if ( null !== $deprecated ) { 2311 _deprecated_argument( __FUNCTION__, '4.3.1' ); 2312 } 2313 2314 // Accepts only 'user', 'admin' , 'both' or default '' as $notify. 2315 if ( ! in_array( $notify, array( 'user', 'admin', 'both', '' ), true ) ) { 2316 return; 2317 } 2318 2319 $user = get_userdata( $user_id ); 2320 2321 /* 2322 * The blogname option is escaped with esc_html() on the way into the database in sanitize_option(). 2323 * We want to reverse this for the plain text arena of emails. 2324 */ 2325 $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); 2326 2327 /** 2328 * Filters whether the admin is notified of a new user registration. 2329 * 2330 * @since 6.1.0 2331 * 2332 * @param bool $send Whether to send the email. Default true. 2333 * @param WP_User $user User object for new user. 2334 */ 2335 $send_notification_to_admin = apply_filters( 'wp_send_new_user_notification_to_admin', true, $user ); 2336 2337 if ( 'user' !== $notify && true === $send_notification_to_admin ) { 2338 2339 $admin_user = get_user_by( 'email', get_option( 'admin_email' ) ); 2340 2341 if ( $admin_user ) { 2342 $switched_locale = switch_to_user_locale( $admin_user->ID ); 2343 } else { 2344 $switched_locale = switch_to_locale( get_locale() ); 2345 } 2346 2347 /* translators: %s: Site title. */ 2348 $message = sprintf( __( 'New user registration on your site %s:' ), $blogname ) . "\r\n\r\n"; 2349 /* translators: %s: User login. */ 2350 $message .= sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n"; 2351 /* translators: %s: User email address. */ 2352 $message .= sprintf( __( 'Email: %s' ), $user->user_email ) . "\r\n"; 2353 2354 $wp_new_user_notification_email_admin = array( 2355 'to' => get_option( 'admin_email' ), 2356 /* translators: New user registration notification email subject. %s: Site title. */ 2357 'subject' => __( '[%s] New User Registration' ), 2358 'message' => $message, 2359 'headers' => '', 2360 ); 2361 2362 /** 2363 * Filters the contents of the new user notification email sent to the site admin. 2364 * 2365 * @since 4.9.0 2366 * 2367 * @param array $wp_new_user_notification_email_admin { 2368 * Used to build wp_mail(). 2369 * 2370 * @type string $to The intended recipient - site admin email address. 2371 * @type string $subject The subject of the email. 2372 * @type string $message The body of the email. 2373 * @type string $headers The headers of the email. 2374 * } 2375 * @param WP_User $user User object for new user. 2376 * @param string $blogname The site title. 2377 */ 2378 $wp_new_user_notification_email_admin = apply_filters( 'wp_new_user_notification_email_admin', $wp_new_user_notification_email_admin, $user, $blogname ); 2379 2380 wp_mail( 2381 $wp_new_user_notification_email_admin['to'], 2382 wp_specialchars_decode( sprintf( $wp_new_user_notification_email_admin['subject'], $blogname ) ), 2383 $wp_new_user_notification_email_admin['message'], 2384 $wp_new_user_notification_email_admin['headers'] 2385 ); 2386 2387 if ( $switched_locale ) { 2388 restore_previous_locale(); 2389 } 2390 } 2391 2392 /** 2393 * Filters whether the user is notified of their new user registration. 2394 * 2395 * @since 6.1.0 2396 * 2397 * @param bool $send Whether to send the email. Default true. 2398 * @param WP_User $user User object for new user. 2399 */ 2400 $send_notification_to_user = apply_filters( 'wp_send_new_user_notification_to_user', true, $user ); 2401 2402 // `$deprecated` was pre-4.3 `$plaintext_pass`. An empty `$plaintext_pass` didn't sent a user notification. 2403 if ( 'admin' === $notify || true !== $send_notification_to_user || ( empty( $deprecated ) && empty( $notify ) ) ) { 2404 return; 2405 } 2406 2407 $key = get_password_reset_key( $user ); 2408 if ( is_wp_error( $key ) ) { 2409 return; 2410 } 2411 2412 $switched_locale = switch_to_user_locale( $user_id ); 2413 2414 $message = __( 'To set your password, visit the following address:' ) . "\r\n\r\n"; 2415 2416 /* 2417 * Since some user login names end in a period, this could produce ambiguous URLs that 2418 * end in a period. To avoid the ambiguity, ensure that the login is not the last query 2419 * arg in the URL. If moving it to the end, a trailing period will need to be escaped. 2420 * 2421 * @link https://core.trac.wordpress.org/ticket/42957 2422 */ 2423 $message .= network_site_url( 'wp-login.php?login=' . rawurlencode( $user->user_login ) . "&key=$key&action=rp", 'login' ) . "\r\n"; 2424 2425 $wp_new_user_notification_email = array( 2426 'to' => $user->user_email, 2427 /* translators: Login details notification email subject. %s: Site title. */ 2428 'subject' => __( '[%s] Login Details' ), 2429 'message' => $message, 2430 'headers' => '', 2431 ); 2432 2433 /** 2434 * Filters the contents of the new user notification email sent to the new user. 2435 * 2436 * @since 4.9.0 2437 * 2438 * @param array $wp_new_user_notification_email { 2439 * Used to build wp_mail(). 2440 * 2441 * @type string $to The intended recipient - New user email address. 2442 * @type string $subject The subject of the email. 2443 * @type string $message The body of the email. 2444 * @type string $headers The headers of the email. 2445 * } 2446 * @param WP_User $user User object for new user. 2447 * @param string $blogname The site title. 2448 */ 2449 $wp_new_user_notification_email = apply_filters( 'wp_new_user_notification_email', $wp_new_user_notification_email, $user, $blogname ); 2450 2451 wp_mail( 2452 $wp_new_user_notification_email['to'], 2453 wp_specialchars_decode( sprintf( $wp_new_user_notification_email['subject'], $blogname ) ), 2454 $wp_new_user_notification_email['message'], 2455 $wp_new_user_notification_email['headers'] 2456 ); 2457 2458 if ( $switched_locale ) { 2459 restore_previous_locale(); 2460 } 2461 } 2462 endif; 2463 2464 if ( ! function_exists( 'wp_nonce_tick' ) ) : 2465 /** 2466 * Returns the time-dependent variable for nonce creation. 2467 * 2468 * A nonce has a lifespan of two ticks. Nonces in their second tick may be 2469 * updated, e.g. by autosave. 2470 * 2471 * @since 2.5.0 2472 * @since 6.1.0 Added `$action` argument. 2473 * 2474 * @param string|int $action Optional. The nonce action. Default -1. 2475 * @return float Float value rounded up to the next highest integer. 2476 */ 2477 function wp_nonce_tick( $action = -1 ) { 2478 /** 2479 * Filters the lifespan of nonces in seconds. 2480 * 2481 * @since 2.5.0 2482 * @since 6.1.0 Added `$action` argument to allow for more targeted filters. 2483 * 2484 * @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day. 2485 * @param string|int $action The nonce action, or -1 if none was provided. 2486 */ 2487 $nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS, $action ); 2488 2489 return ceil( time() / ( $nonce_life / 2 ) ); 2490 } 2491 endif; 2492 2493 if ( ! function_exists( 'wp_verify_nonce' ) ) : 2494 /** 2495 * Verifies that a correct security nonce was used with time limit. 2496 * 2497 * A nonce is valid for between 12 and 24 hours (by default). 2498 * 2499 * @since 2.0.3 2500 * 2501 * @param string $nonce Nonce value that was used for verification, usually via a form field. 2502 * @param string|int $action Should give context to what is taking place and be the same when nonce was created. 2503 * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago, 2504 * 2 if the nonce is valid and generated between 12-24 hours ago. 2505 * False if the nonce is invalid. 2506 */ 2507 function wp_verify_nonce( $nonce, $action = -1 ) { 2508 $nonce = (string) $nonce; 2509 $user = wp_get_current_user(); 2510 $uid = (int) $user->ID; 2511 if ( ! $uid ) { 2512 /** 2513 * Filters whether the user who generated the nonce is logged out. 2514 * 2515 * @since 3.5.0 2516 * 2517 * @param int $uid ID of the nonce-owning user. 2518 * @param string|int $action The nonce action, or -1 if none was provided. 2519 */ 2520 $uid = apply_filters( 'nonce_user_logged_out', $uid, $action ); 2521 } 2522 2523 if ( empty( $nonce ) ) { 2524 return false; 2525 } 2526 2527 $token = wp_get_session_token(); 2528 $i = wp_nonce_tick( $action ); 2529 2530 // Nonce generated 0-12 hours ago. 2531 $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); 2532 if ( hash_equals( $expected, $nonce ) ) { 2533 return 1; 2534 } 2535 2536 // Nonce generated 12-24 hours ago. 2537 $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); 2538 if ( hash_equals( $expected, $nonce ) ) { 2539 return 2; 2540 } 2541 2542 /** 2543 * Fires when nonce verification fails. 2544 * 2545 * @since 4.4.0 2546 * 2547 * @param string $nonce The invalid nonce. 2548 * @param string|int $action The nonce action. 2549 * @param WP_User $user The current user object. 2550 * @param string $token The user's session token. 2551 */ 2552 do_action( 'wp_verify_nonce_failed', $nonce, $action, $user, $token ); 2553 2554 // Invalid nonce. 2555 return false; 2556 } 2557 endif; 2558 2559 if ( ! function_exists( 'wp_create_nonce' ) ) : 2560 /** 2561 * Creates a cryptographic token tied to a specific action, user, user session, 2562 * and window of time. 2563 * 2564 * @since 2.0.3 2565 * @since 4.0.0 Session tokens were integrated with nonce creation. 2566 * 2567 * @param string|int $action Scalar value to add context to the nonce. 2568 * @return string The token. 2569 * 2570 * @phpstan-return lowercase-string&non-falsy-string 2571 */ 2572 function wp_create_nonce( $action = -1 ) { 2573 $user = wp_get_current_user(); 2574 $uid = (int) $user->ID; 2575 if ( ! $uid ) { 2576 /** This filter is documented in wp-includes/pluggable.php */ 2577 $uid = apply_filters( 'nonce_user_logged_out', $uid, $action ); 2578 } 2579 2580 $token = wp_get_session_token(); 2581 $i = wp_nonce_tick( $action ); 2582 2583 return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); 2584 } 2585 endif; 2586 2587 if ( ! function_exists( 'wp_salt' ) ) : 2588 /** 2589 * Returns a salt to add to hashes. 2590 * 2591 * Salts are created using secret keys. Secret keys are located in two places: 2592 * in the database and in the wp-config.php file. The secret key in the database 2593 * is randomly generated and will be appended to the secret keys in wp-config.php. 2594 * 2595 * The secret keys in wp-config.php should be updated to strong, random keys to maximize 2596 * security. Below is an example of how the secret key constants are defined. 2597 * Do not paste this example directly into wp-config.php. Instead, have a 2598 * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just 2599 * for you. 2600 * 2601 * define('AUTH_KEY', ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON'); 2602 * define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~'); 2603 * define('LOGGED_IN_KEY', '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM'); 2604 * define('NONCE_KEY', '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|'); 2605 * define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW'); 2606 * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n'); 2607 * define('LOGGED_IN_SALT', '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm'); 2608 * define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT'); 2609 * 2610 * Salting passwords helps against tools which has stored hashed values of 2611 * common dictionary strings. The added values makes it harder to crack. 2612 * 2613 * @since 2.5.0 2614 * 2615 * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php 2616 * 2617 * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce). 2618 * @return string Salt value 2619 */ 2620 function wp_salt( $scheme = 'auth' ) { 2621 static $cached_salts = array(); 2622 if ( isset( $cached_salts[ $scheme ] ) ) { 2623 /** 2624 * Filters the WordPress salt. 2625 * 2626 * @since 2.5.0 2627 * 2628 * @param string $cached_salt Cached salt for the given scheme. 2629 * @param string $scheme Authentication scheme. Values include 'auth', 2630 * 'secure_auth', 'logged_in', and 'nonce'. 2631 */ 2632 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme ); 2633 } 2634 2635 static $duplicated_keys; 2636 if ( null === $duplicated_keys ) { 2637 $duplicated_keys = array(); 2638 2639 foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) { 2640 foreach ( array( 'KEY', 'SALT' ) as $second ) { 2641 if ( ! defined( "{$first}_{$second}" ) ) { 2642 continue; 2643 } 2644 $value = constant( "{$first}_{$second}" ); 2645 $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] ); 2646 } 2647 } 2648 2649 $duplicated_keys['put your unique phrase here'] = true; 2650 2651 /* 2652 * translators: This string should only be translated if wp-config-sample.php is localized. 2653 * You can check the localized release package or 2654 * https://i18n.svn.wordpress.org/<locale code>/branches/<wp version>/dist/wp-config-sample.php 2655 */ 2656 $duplicated_keys[ __( 'put your unique phrase here' ) ] = true; 2657 } 2658 2659 /* 2660 * Determine which options to prime. 2661 * 2662 * If the salt keys are undefined, use a duplicate value or the 2663 * default `put your unique phrase here` value the salt will be 2664 * generated via `wp_generate_password()` and stored as a site 2665 * option. These options will be primed to avoid repeated 2666 * database requests for undefined salts. 2667 */ 2668 $options_to_prime = array(); 2669 foreach ( array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) as $key ) { 2670 foreach ( array( 'key', 'salt' ) as $second ) { 2671 $const = strtoupper( "{$key}_{$second}" ); 2672 if ( ! defined( $const ) || true === $duplicated_keys[ constant( $const ) ] ) { 2673 $options_to_prime[] = "{$key}_{$second}"; 2674 } 2675 } 2676 } 2677 2678 if ( ! empty( $options_to_prime ) ) { 2679 /* 2680 * Also prime `secret_key` used for undefined salting schemes. 2681 * 2682 * If the scheme is unknown, the default value for `secret_key` will be 2683 * used too for the salt. This should rarely happen, so the option is only 2684 * primed if other salts are undefined. 2685 * 2686 * At this point of execution it is known that a database call will be made 2687 * to prime salts, so the `secret_key` option can be primed regardless of the 2688 * constants status. 2689 */ 2690 $options_to_prime[] = 'secret_key'; 2691 wp_prime_site_option_caches( $options_to_prime ); 2692 } 2693 2694 $values = array( 2695 'key' => '', 2696 'salt' => '', 2697 ); 2698 if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) { 2699 $values['key'] = SECRET_KEY; 2700 } 2701 if ( 'auth' === $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) { 2702 $values['salt'] = SECRET_SALT; 2703 } 2704 2705 if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ), true ) ) { 2706 foreach ( array( 'key', 'salt' ) as $type ) { 2707 $const = strtoupper( "{$scheme}_{$type}" ); 2708 if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) { 2709 $values[ $type ] = constant( $const ); 2710 } elseif ( ! $values[ $type ] ) { 2711 $values[ $type ] = get_site_option( "{$scheme}_{$type}" ); 2712 if ( ! $values[ $type ] ) { 2713 $values[ $type ] = wp_generate_password( 64, true, true ); 2714 update_site_option( "{$scheme}_{$type}", $values[ $type ] ); 2715 } 2716 } 2717 } 2718 } else { 2719 if ( ! $values['key'] ) { 2720 $values['key'] = get_site_option( 'secret_key' ); 2721 if ( ! $values['key'] ) { 2722 $values['key'] = wp_generate_password( 64, true, true ); 2723 update_site_option( 'secret_key', $values['key'] ); 2724 } 2725 } 2726 $values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] ); 2727 } 2728 2729 $cached_salts[ $scheme ] = $values['key'] . $values['salt']; 2730 2731 /** This filter is documented in wp-includes/pluggable.php */ 2732 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme ); 2733 } 2734 endif; 2735 2736 if ( ! function_exists( 'wp_hash' ) ) : 2737 /** 2738 * Gets the hash of the given string. 2739 * 2740 * The default algorithm is md5 but can be changed to any algorithm supported by 2741 * `hash_hmac()`. Use the `hash_hmac_algos()` function to check the supported 2742 * algorithms. 2743 * 2744 * @since 2.0.3 2745 * @since 6.8.0 The `$algo` parameter was added. 2746 * 2747 * @throws InvalidArgumentException If the hashing algorithm is not supported. 2748 * 2749 * @param string $data Plain text to hash. 2750 * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce). 2751 * @param string $algo Hashing algorithm to use. Default: 'md5'. 2752 * @return string Hash of $data. 2753 * 2754 * @phpstan-return lowercase-string&non-falsy-string 2755 */ 2756 function wp_hash( $data, $scheme = 'auth', $algo = 'md5' ) { 2757 $salt = wp_salt( $scheme ); 2758 2759 // Ensure the algorithm is supported by the hash_hmac function. 2760 if ( ! in_array( $algo, hash_hmac_algos(), true ) ) { 2761 throw new InvalidArgumentException( 2762 sprintf( 2763 /* translators: 1: Name of a cryptographic hash algorithm. 2: List of supported algorithms. */ 2764 __( 'Unsupported hashing algorithm: %1$s. Supported algorithms are: %2$s' ), 2765 $algo, 2766 implode( ', ', hash_hmac_algos() ) 2767 ) 2768 ); 2769 } 2770 2771 return hash_hmac( $algo, $data, $salt ); 2772 } 2773 endif; 2774 2775 if ( ! function_exists( 'wp_hash_password' ) ) : 2776 /** 2777 * Creates a hash of a plain text password. 2778 * 2779 * For integration with other applications, this function can be overwritten to 2780 * instead use the other package password hashing algorithm. 2781 * 2782 * @since 2.5.0 2783 * @since 6.8.0 The password is now hashed using bcrypt by default instead of phpass. 2784 * 2785 * @global PasswordHash $wp_hasher phpass object. 2786 * 2787 * @param string $password Plain text user password to hash. 2788 * @return string The hash string of the password. 2789 */ 2790 function wp_hash_password( 2791 #[\SensitiveParameter] 2792 $password 2793 ) { 2794 global $wp_hasher; 2795 2796 if ( ! empty( $wp_hasher ) ) { 2797 return $wp_hasher->HashPassword( trim( $password ) ); 2798 } 2799 2800 if ( strlen( $password ) > 4096 ) { 2801 return '*'; 2802 } 2803 2804 /** 2805 * Filters the hashing algorithm to use in the password_hash() and password_needs_rehash() functions. 2806 * 2807 * The default is the value of the `PASSWORD_BCRYPT` constant which means bcrypt is used. 2808 * 2809 * **Important:** The only password hashing algorithm that is guaranteed to be available across PHP 2810 * installations is bcrypt. If you use any other algorithm you must make sure that it is available on 2811 * the server. The `password_algos()` function can be used to check which hashing algorithms are available. 2812 * 2813 * The hashing options can be controlled via the {@see 'wp_hash_password_options'} filter. 2814 * 2815 * Other available constants include: 2816 * 2817 * - `PASSWORD_ARGON2I` 2818 * - `PASSWORD_ARGON2ID` 2819 * - `PASSWORD_DEFAULT` 2820 * 2821 * @since 6.8.0 2822 * @since 7.0.0 The `$algorithm` parameter is now always a string. 2823 * 2824 * @param string $algorithm The hashing algorithm. Default is the value of the `PASSWORD_BCRYPT` constant. 2825 */ 2826 $algorithm = apply_filters( 'wp_hash_password_algorithm', PASSWORD_BCRYPT ); 2827 2828 /** 2829 * Filters the options passed to the password_hash() and password_needs_rehash() functions. 2830 * 2831 * The default hashing algorithm is bcrypt, but this can be changed via the {@see 'wp_hash_password_algorithm'} 2832 * filter. You must ensure that the options are appropriate for the algorithm in use. 2833 * 2834 * @since 6.8.0 2835 * @since 7.0.0 The `$algorithm` parameter is now always a string. 2836 * 2837 * @param array $options Array of options to pass to the password hashing functions. 2838 * By default this is an empty array which means the default 2839 * options will be used. 2840 * @param string $algorithm The hashing algorithm in use. 2841 */ 2842 $options = apply_filters( 'wp_hash_password_options', array(), $algorithm ); 2843 2844 // Algorithms other than bcrypt don't need to use pre-hashing. 2845 if ( PASSWORD_BCRYPT !== $algorithm ) { 2846 return password_hash( $password, $algorithm, $options ); 2847 } 2848 2849 // Use SHA-384 to retain entropy from a password that's longer than 72 bytes, and a `wp-sha384` key for domain separation. 2850 $password_to_hash = base64_encode( hash_hmac( 'sha384', trim( $password ), 'wp-sha384', true ) ); 2851 2852 // Add a prefix to facilitate distinguishing vanilla bcrypt hashes. 2853 return '$wp' . password_hash( $password_to_hash, $algorithm, $options ); 2854 } 2855 endif; 2856 2857 if ( ! function_exists( 'wp_check_password' ) ) : 2858 /** 2859 * Checks a plaintext password against a hashed password. 2860 * 2861 * Note that this function may be used to check a value that is not a user password. 2862 * A plugin may use this function to check a password of a different type, and there 2863 * may not always be a user ID associated with the password. 2864 * 2865 * For integration with other applications, this function can be overwritten to 2866 * instead use the other package password hashing algorithm. 2867 * 2868 * @since 2.5.0 2869 * @since 6.8.0 Passwords in WordPress are now hashed with bcrypt by default. A 2870 * password that wasn't hashed with bcrypt will be checked with phpass. 2871 * 2872 * @global PasswordHash $wp_hasher phpass object. Used as a fallback for verifying 2873 * passwords that were hashed with phpass. 2874 * 2875 * @param string $password Plaintext password. 2876 * @param string $hash Hash of the password to check against. 2877 * @param string|int $user_id Optional. ID of a user associated with the password. 2878 * @return bool False, if the $password does not match the hashed password. 2879 */ 2880 function wp_check_password( 2881 #[\SensitiveParameter] 2882 $password, 2883 $hash, 2884 $user_id = '' 2885 ) { 2886 global $wp_hasher; 2887 2888 if ( strlen( $hash ) <= 32 ) { 2889 // Check the hash using md5 regardless of the current hashing mechanism. 2890 $check = hash_equals( $hash, md5( $password ) ); 2891 } elseif ( ! empty( $wp_hasher ) ) { 2892 // Check the password using the overridden hasher. 2893 $check = $wp_hasher->CheckPassword( $password, $hash ); 2894 } elseif ( strlen( $password ) > 4096 ) { 2895 // Passwords longer than 4096 characters are not supported. 2896 $check = false; 2897 } elseif ( str_starts_with( $hash, '$wp' ) ) { 2898 // Check the password using the current prefixed hash. 2899 $password_to_verify = base64_encode( hash_hmac( 'sha384', $password, 'wp-sha384', true ) ); 2900 $check = password_verify( $password_to_verify, substr( $hash, 3 ) ); 2901 } elseif ( str_starts_with( $hash, '$P$' ) ) { 2902 // Check the password using phpass. 2903 require_once ABSPATH . WPINC . '/class-phpass.php'; 2904 $check = ( new PasswordHash( 8, true ) )->CheckPassword( $password, $hash ); 2905 } else { 2906 // Check the password using compat support for any non-prefixed hash. 2907 $check = password_verify( $password, $hash ); 2908 } 2909 2910 /** 2911 * Filters whether the plaintext password matches the hashed password. 2912 * 2913 * @since 2.5.0 2914 * @since 6.8.0 Passwords are now hashed with bcrypt by default. 2915 * Old passwords may still be hashed with phpass or md5. 2916 * 2917 * @param bool $check Whether the passwords match. 2918 * @param string $password The plaintext password. 2919 * @param string $hash The hashed password. 2920 * @param string|int $user_id Optional ID of a user associated with the password. 2921 * Can be empty. 2922 */ 2923 return apply_filters( 'check_password', $check, $password, $hash, $user_id ); 2924 } 2925 endif; 2926 2927 if ( ! function_exists( 'wp_password_needs_rehash' ) ) : 2928 /** 2929 * Checks whether a password hash needs to be rehashed. 2930 * 2931 * Passwords are hashed with bcrypt using the default cost. A password hashed in a prior version 2932 * of WordPress may still be hashed with phpass and will need to be rehashed. If the default cost 2933 * or algorithm is changed in PHP or WordPress then a password hashed in a previous version will 2934 * need to be rehashed. 2935 * 2936 * Note that, just like wp_check_password(), this function may be used to check a value that is 2937 * not a user password. A plugin may use this function to check a password of a different type, 2938 * and there may not always be a user ID associated with the password. 2939 * 2940 * @since 6.8.0 2941 * 2942 * @global PasswordHash $wp_hasher phpass object. 2943 * 2944 * @param string $hash Hash of a password to check. 2945 * @param string|int $user_id Optional. ID of a user associated with the password. 2946 * @return bool Whether the hash needs to be rehashed. 2947 */ 2948 function wp_password_needs_rehash( $hash, $user_id = '' ) { 2949 global $wp_hasher; 2950 2951 if ( ! empty( $wp_hasher ) ) { 2952 return false; 2953 } 2954 2955 /** This filter is documented in wp-includes/pluggable.php */ 2956 $algorithm = apply_filters( 'wp_hash_password_algorithm', PASSWORD_BCRYPT ); 2957 2958 /** This filter is documented in wp-includes/pluggable.php */ 2959 $options = apply_filters( 'wp_hash_password_options', array(), $algorithm ); 2960 2961 $prefixed = str_starts_with( $hash, '$wp' ); 2962 2963 if ( ( PASSWORD_BCRYPT === $algorithm ) && ! $prefixed ) { 2964 // If bcrypt is in use and the hash is not prefixed then it needs to be rehashed. 2965 $needs_rehash = true; 2966 } else { 2967 // Otherwise check the hash minus its prefix if necessary. 2968 $hash_to_check = $prefixed ? substr( $hash, 3 ) : $hash; 2969 $needs_rehash = password_needs_rehash( $hash_to_check, $algorithm, $options ); 2970 } 2971 2972 /** 2973 * Filters whether the password hash needs to be rehashed. 2974 * 2975 * @since 6.8.0 2976 * 2977 * @param bool $needs_rehash Whether the password hash needs to be rehashed. 2978 * @param string $hash The password hash. 2979 * @param string|int $user_id Optional. ID of a user associated with the password. 2980 */ 2981 return apply_filters( 'password_needs_rehash', $needs_rehash, $hash, $user_id ); 2982 } 2983 endif; 2984 2985 if ( ! function_exists( 'wp_generate_password' ) ) : 2986 /** 2987 * Generates a random password drawn from the defined set of characters. 2988 * 2989 * Uses wp_rand() to create passwords with far less predictability 2990 * than similar native PHP functions like `rand()` or `mt_rand()`. 2991 * 2992 * @since 2.5.0 2993 * 2994 * @param int $length Optional. The length of password to generate. Default 12. 2995 * @param bool $special_chars Optional. Whether to include standard special characters. 2996 * Default true. 2997 * @param bool $extra_special_chars Optional. Whether to include other special characters. 2998 * Used when generating secret keys and salts. Default false. 2999 * @return string The random password. 3000 */ 3001 function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) { 3002 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 3003 if ( $special_chars ) { 3004 $chars .= '!@#$%^&*()'; 3005 } 3006 if ( $extra_special_chars ) { 3007 $chars .= '-_ []{}<>~`+=,.;:/?|'; 3008 } 3009 3010 $password = ''; 3011 for ( $i = 0; $i < $length; $i++ ) { 3012 $password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 ); 3013 } 3014 3015 /** 3016 * Filters the randomly-generated password. 3017 * 3018 * @since 3.0.0 3019 * @since 5.3.0 Added the `$length`, `$special_chars`, and `$extra_special_chars` parameters. 3020 * 3021 * @param string $password The generated password. 3022 * @param int $length The length of password to generate. 3023 * @param bool $special_chars Whether to include standard special characters. 3024 * @param bool $extra_special_chars Whether to include other special characters. 3025 */ 3026 return apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars ); 3027 } 3028 endif; 3029 3030 if ( ! function_exists( 'wp_rand' ) ) : 3031 /** 3032 * Generates a random non-negative number. 3033 * 3034 * @since 2.6.2 3035 * @since 4.4.0 Uses PHP7 random_int() or the random_compat library if available. 3036 * @since 6.1.0 Returns zero instead of a random number if both `$min` and `$max` are zero. 3037 * 3038 * @global string $rnd_value 3039 * 3040 * @param int $min Optional. Lower limit for the generated number. 3041 * Accepts positive integers or zero. Defaults to 0. 3042 * @param int $max Optional. Upper limit for the generated number. 3043 * Accepts positive integers. Defaults to 4294967295. 3044 * @return int A random non-negative number between min and max. 3045 */ 3046 function wp_rand( $min = null, $max = null ) { 3047 global $rnd_value; 3048 3049 /* 3050 * Some misconfigured 32-bit environments (Entropy PHP, for example) 3051 * truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats. 3052 */ 3053 $max_random_number = 3000000000 === 2147483647 ? (float) '4294967295' : 4294967295; // 4294967295 = 0xffffffff 3054 3055 if ( null === $min ) { 3056 $min = 0; 3057 } 3058 3059 if ( null === $max ) { 3060 $max = $max_random_number; 3061 } 3062 3063 // We only handle ints, floats are truncated to their integer value. 3064 $min = (int) $min; 3065 $max = (int) $max; 3066 3067 // Use PHP's CSPRNG, or a compatible method. 3068 static $use_random_int_functionality = true; 3069 if ( $use_random_int_functionality ) { 3070 try { 3071 // wp_rand() can accept arguments in either order, PHP cannot. 3072 $_max = max( $min, $max ); 3073 $_min = min( $min, $max ); 3074 $val = random_int( $_min, $_max ); 3075 if ( false !== $val ) { 3076 return absint( $val ); 3077 } else { 3078 $use_random_int_functionality = false; 3079 } 3080 } catch ( Error $e ) { 3081 $use_random_int_functionality = false; 3082 } catch ( Exception $e ) { 3083 $use_random_int_functionality = false; 3084 } 3085 } 3086 3087 /* 3088 * Reset $rnd_value after 14 uses. 3089 * 32 (md5) + 40 (sha1) + 40 (sha1) / 8 = 14 random numbers from $rnd_value. 3090 */ 3091 if ( strlen( $rnd_value ) < 8 ) { 3092 if ( defined( 'WP_SETUP_CONFIG' ) ) { 3093 static $seed = ''; 3094 } else { 3095 $seed = get_transient( 'random_seed' ); 3096 } 3097 $rnd_value = md5( uniqid( microtime() . mt_rand(), true ) . $seed ); 3098 $rnd_value .= sha1( $rnd_value ); 3099 $rnd_value .= sha1( $rnd_value . $seed ); 3100 $seed = md5( $seed . $rnd_value ); 3101 if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) { 3102 set_transient( 'random_seed', $seed ); 3103 } 3104 } 3105 3106 // Take the first 8 digits for our value. 3107 $value = substr( $rnd_value, 0, 8 ); 3108 3109 // Strip the first eight, leaving the remainder for the next call to wp_rand(). 3110 $rnd_value = substr( $rnd_value, 8 ); 3111 3112 $value = abs( hexdec( $value ) ); 3113 3114 // Reduce the value to be within the min - max range. 3115 $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 ); 3116 3117 return abs( (int) $value ); 3118 } 3119 endif; 3120 3121 if ( ! function_exists( 'wp_set_password' ) ) : 3122 /** 3123 * Updates the user's password with a new hashed one. 3124 * 3125 * For integration with other applications, this function can be overwritten to 3126 * instead use the other package password checking algorithm. 3127 * 3128 * Please note: This function should be used sparingly and is really only meant for single-time 3129 * application. Leveraging this improperly in a plugin or theme could result in an endless loop 3130 * of password resets if precautions are not taken to ensure it does not execute on every page load. 3131 * 3132 * @since 2.5.0 3133 * @since 6.8.0 The password is now hashed using bcrypt by default instead of phpass. 3134 * 3135 * @global wpdb $wpdb WordPress database abstraction object. 3136 * 3137 * @param string $password The plaintext new user password. 3138 * @param int $user_id User ID. 3139 */ 3140 function wp_set_password( 3141 #[\SensitiveParameter] 3142 $password, 3143 $user_id 3144 ) { 3145 global $wpdb; 3146 3147 $old_user_data = get_userdata( $user_id ); 3148 3149 $hash = wp_hash_password( $password ); 3150 $wpdb->update( 3151 $wpdb->users, 3152 array( 3153 'user_pass' => $hash, 3154 'user_activation_key' => '', 3155 ), 3156 array( 'ID' => $user_id ) 3157 ); 3158 3159 clean_user_cache( $user_id ); 3160 3161 /** 3162 * Fires after the user password is set. 3163 * 3164 * @since 6.2.0 3165 * @since 6.7.0 The `$old_user_data` parameter was added. 3166 * 3167 * @param string $password The plaintext password just set. 3168 * @param int $user_id The ID of the user whose password was just set. 3169 * @param WP_User $old_user_data Object containing user's data prior to update. 3170 */ 3171 do_action( 'wp_set_password', $password, $user_id, $old_user_data ); 3172 } 3173 endif; 3174 3175 if ( ! function_exists( 'get_avatar' ) ) : 3176 /** 3177 * Retrieves the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post. 3178 * 3179 * @since 2.5.0 3180 * @since 4.2.0 Added the optional `$args` parameter. 3181 * @since 5.5.0 Added the `loading` argument. 3182 * @since 6.1.0 Added the `decoding` argument. 3183 * @since 6.3.0 Added the `fetchpriority` argument. 3184 * 3185 * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, 3186 * user email, WP_User object, WP_Post object, or WP_Comment object. 3187 * @param int $size Optional. Height and width of the avatar in pixels. Default 96. 3188 * @param string $default_value URL for the default image or a default type. Accepts: 3189 * - '404' (return a 404 instead of a default image) 3190 * - 'retro' (a 8-bit arcade-style pixelated face) 3191 * - 'robohash' (a robot) 3192 * - 'monsterid' (a monster) 3193 * - 'wavatar' (a cartoon face) 3194 * - 'identicon' (the "quilt", a geometric pattern) 3195 * - 'initials' (initials based avatar with background color) 3196 * - 'color' (generated background color) 3197 * - 'mystery', 'mm', or 'mysteryman' (The Oyster Man) 3198 * - 'blank' (transparent GIF) 3199 * - 'gravatar_default' (the Gravatar logo) 3200 * Default is the value of the 'avatar_default' option, 3201 * with a fallback of 'mystery'. 3202 * @param string $alt Optional. Alternative text to use in the avatar image tag. 3203 * Default empty. 3204 * @param array $args { 3205 * Optional. Extra arguments to retrieve the avatar. 3206 * 3207 * @type int $height Display height of the avatar in pixels. Defaults to $size. 3208 * @type int $width Display width of the avatar in pixels. Defaults to $size. 3209 * @type bool $force_default Whether to always show the default image, never the Gravatar. 3210 * Default false. 3211 * @type string $rating What rating to display avatars up to. Accepts: 3212 * - 'G' (suitable for all audiences) 3213 * - 'PG' (possibly offensive, usually for audiences 13 and above) 3214 * - 'R' (intended for adult audiences above 17) 3215 * - 'X' (even more mature than above) 3216 * Default is the value of the 'avatar_rating' option. 3217 * @type string $scheme URL scheme to use. See set_url_scheme() for accepted values. 3218 * Default null. 3219 * @type array|string $class Array or string of additional classes to add to the img element. 3220 * Default null. 3221 * @type bool $force_display Whether to always show the avatar - ignores the show_avatars option. 3222 * Default false. 3223 * @type string $loading Value for the `loading` attribute. 3224 * Default null. 3225 * @type string $fetchpriority Value for the `fetchpriority` attribute. 3226 * Default null. 3227 * @type string $decoding Value for the `decoding` attribute. 3228 * Default null. 3229 * @type string $extra_attr HTML attributes to insert in the IMG element. Is not sanitized. 3230 * Default empty. 3231 * } 3232 * @return string|false `<img>` tag for the user's avatar. False on failure. 3233 */ 3234 function get_avatar( $id_or_email, $size = 96, $default_value = '', $alt = '', $args = null ) { 3235 $defaults = array( 3236 // get_avatar_data() args. 3237 'size' => 96, 3238 'height' => null, 3239 'width' => null, 3240 'default' => get_option( 'avatar_default', 'mystery' ), 3241 'force_default' => false, 3242 'rating' => get_option( 'avatar_rating' ), 3243 'scheme' => null, 3244 'alt' => '', 3245 'class' => null, 3246 'force_display' => false, 3247 'loading' => null, 3248 'fetchpriority' => null, 3249 'decoding' => null, 3250 'extra_attr' => '', 3251 ); 3252 3253 if ( empty( $args ) ) { 3254 $args = array(); 3255 } 3256 3257 $args['size'] = (int) $size; 3258 $args['default'] = $default_value; 3259 $args['alt'] = $alt; 3260 3261 $args = wp_parse_args( $args, $defaults ); 3262 3263 if ( empty( $args['height'] ) ) { 3264 $args['height'] = $args['size']; 3265 } 3266 if ( empty( $args['width'] ) ) { 3267 $args['width'] = $args['size']; 3268 } 3269 3270 // Update args with loading optimized attributes. 3271 $loading_optimization_attr = wp_get_loading_optimization_attributes( 'img', $args, 'get_avatar' ); 3272 3273 $args = array_merge( $args, $loading_optimization_attr ); 3274 3275 if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) { 3276 $id_or_email = get_comment( $id_or_email ); 3277 } 3278 3279 /** 3280 * Allows the HTML for a user's avatar to be returned early. 3281 * 3282 * Returning a non-null value will effectively short-circuit get_avatar(), passing 3283 * the value through the {@see 'get_avatar'} filter and returning early. 3284 * 3285 * @since 4.2.0 3286 * 3287 * @param string|null $avatar HTML for the user's avatar. Default null. 3288 * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, 3289 * user email, WP_User object, WP_Post object, or WP_Comment object. 3290 * @param array $args Arguments passed to get_avatar_url(), after processing. 3291 */ 3292 $avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args ); 3293 3294 if ( ! is_null( $avatar ) ) { 3295 /** This filter is documented in wp-includes/pluggable.php */ 3296 return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args ); 3297 } 3298 3299 if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) { 3300 return false; 3301 } 3302 3303 $url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) ); 3304 3305 $args = get_avatar_data( $id_or_email, $args ); 3306 3307 $url = $args['url']; 3308 3309 if ( ! $url || is_wp_error( $url ) ) { 3310 return false; 3311 } 3312 3313 $class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' ); 3314 3315 if ( ! $args['found_avatar'] || $args['force_default'] ) { 3316 $class[] = 'avatar-default'; 3317 } 3318 3319 if ( $args['class'] ) { 3320 if ( is_array( $args['class'] ) ) { 3321 $class = array_merge( $class, $args['class'] ); 3322 } else { 3323 $class[] = $args['class']; 3324 } 3325 } 3326 3327 // Add `loading`, `fetchpriority`, and `decoding` attributes. 3328 $extra_attr = $args['extra_attr']; 3329 3330 if ( in_array( $args['loading'], array( 'lazy', 'eager' ), true ) 3331 && ! preg_match( '/\bloading\s*=/', $extra_attr ) 3332 ) { 3333 if ( ! empty( $extra_attr ) ) { 3334 $extra_attr .= ' '; 3335 } 3336 3337 $extra_attr .= "loading='{$args['loading']}'"; 3338 } 3339 3340 if ( in_array( $args['fetchpriority'], array( 'high', 'low', 'auto' ), true ) 3341 && ! preg_match( '/\bfetchpriority\s*=/', $extra_attr ) 3342 ) { 3343 if ( ! empty( $extra_attr ) ) { 3344 $extra_attr .= ' '; 3345 } 3346 3347 $extra_attr .= "fetchpriority='{$args['fetchpriority']}'"; 3348 } 3349 3350 if ( in_array( $args['decoding'], array( 'async', 'sync', 'auto' ), true ) 3351 && ! preg_match( '/\bdecoding\s*=/', $extra_attr ) 3352 ) { 3353 if ( ! empty( $extra_attr ) ) { 3354 $extra_attr .= ' '; 3355 } 3356 3357 $extra_attr .= "decoding='{$args['decoding']}'"; 3358 } 3359 3360 $avatar = sprintf( 3361 "<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>", 3362 esc_attr( $args['alt'] ), 3363 esc_url( $url ), 3364 esc_url( $url2x ) . ' 2x', 3365 esc_attr( implode( ' ', $class ) ), 3366 (int) $args['height'], 3367 (int) $args['width'], 3368 $extra_attr 3369 ); 3370 3371 /** 3372 * Filters the HTML for a user's avatar. 3373 * 3374 * @since 2.5.0 3375 * @since 4.2.0 Added the `$args` parameter. 3376 * 3377 * @param string $avatar HTML for the user's avatar. 3378 * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, 3379 * user email, WP_User object, WP_Post object, or WP_Comment object. 3380 * @param int $size Height and width of the avatar in pixels. 3381 * @param string $default_value URL for the default image or a default type. Accepts: 3382 * - '404' (return a 404 instead of a default image) 3383 * - 'retro' (a 8-bit arcade-style pixelated face) 3384 * - 'robohash' (a robot) 3385 * - 'monsterid' (a monster) 3386 * - 'wavatar' (a cartoon face) 3387 * - 'identicon' (the "quilt", a geometric pattern) 3388 * - 'mystery', 'mm', or 'mysteryman' (The Oyster Man) 3389 * - 'blank' (transparent GIF) 3390 * - 'gravatar_default' (the Gravatar logo) 3391 * @param string $alt Alternative text to use in the avatar image tag. 3392 * @param array $args Arguments passed to get_avatar_data(), after processing. 3393 */ 3394 return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args ); 3395 } 3396 endif; 3397 3398 if ( ! function_exists( 'wp_text_diff' ) ) : 3399 /** 3400 * Displays a human readable HTML representation of the difference between two strings. 3401 * 3402 * The Diff is available for getting the changes between versions. The output is 3403 * HTML, so the primary use is for displaying the changes. If the two strings 3404 * are equivalent, then an empty string will be returned. 3405 * 3406 * @since 2.6.0 3407 * 3408 * @see wp_parse_args() Used to change defaults to user defined settings. 3409 * @uses Text_Diff 3410 * @uses WP_Text_Diff_Renderer_Table 3411 * 3412 * @param string $left_string "old" (left) version of string. 3413 * @param string $right_string "new" (right) version of string. 3414 * @param string|array $args { 3415 * Associative array of options to pass to WP_Text_Diff_Renderer_Table(). 3416 * 3417 * @type string $title Titles the diff in a manner compatible 3418 * with the output. Default empty. 3419 * @type string $title_left Change the HTML to the left of the title. 3420 * Default empty. 3421 * @type string $title_right Change the HTML to the right of the title. 3422 * Default empty. 3423 * @type bool $show_split_view True for split view (two columns), false for 3424 * un-split view (single column). Default true. 3425 * } 3426 * @return string Empty string if strings are equivalent or HTML with differences. 3427 */ 3428 function wp_text_diff( $left_string, $right_string, $args = null ) { 3429 $defaults = array( 3430 'title' => '', 3431 'title_left' => '', 3432 'title_right' => '', 3433 'show_split_view' => true, 3434 ); 3435 $args = wp_parse_args( $args, $defaults ); 3436 3437 if ( ! class_exists( 'WP_Text_Diff_Renderer_Table', false ) ) { 3438 require ABSPATH . WPINC . '/wp-diff.php'; 3439 } 3440 3441 $left_string = normalize_whitespace( $left_string ); 3442 $right_string = normalize_whitespace( $right_string ); 3443 3444 $left_lines = explode( "\n", $left_string ); 3445 $right_lines = explode( "\n", $right_string ); 3446 $text_diff = new Text_Diff( $left_lines, $right_lines ); 3447 $renderer = new WP_Text_Diff_Renderer_Table( $args ); 3448 $diff = $renderer->render( $text_diff ); 3449 3450 if ( ! $diff ) { 3451 return ''; 3452 } 3453 3454 $is_split_view = ! empty( $args['show_split_view'] ); 3455 $is_split_view_class = $is_split_view ? ' is-split-view' : ''; 3456 3457 $r = "<table class='diff$is_split_view_class'>\n"; 3458 3459 if ( $args['title'] ) { 3460 $r .= "<caption class='diff-title'>$args[title]</caption>\n"; 3461 } 3462 3463 if ( $args['title_left'] || $args['title_right'] ) { 3464 $r .= '<thead>'; 3465 } 3466 3467 if ( $args['title_left'] || $args['title_right'] ) { 3468 $th_or_td_left = empty( $args['title_left'] ) ? 'td' : 'th'; 3469 $th_or_td_right = empty( $args['title_right'] ) ? 'td' : 'th'; 3470 3471 $r .= "<tr class='diff-sub-title'>\n"; 3472 $r .= "\t<$th_or_td_left>$args[title_left]</$th_or_td_left>\n"; 3473 if ( $is_split_view ) { 3474 $r .= "\t<$th_or_td_right>$args[title_right]</$th_or_td_right>\n"; 3475 } 3476 $r .= "</tr>\n"; 3477 } 3478 3479 if ( $args['title_left'] || $args['title_right'] ) { 3480 $r .= "</thead>\n"; 3481 } 3482 3483 $r .= "<tbody>\n$diff\n</tbody>\n"; 3484 $r .= '</table>'; 3485 3486 return $r; 3487 } 3488 endif;
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Tue Nov 24 08:20:01 2026 | Cross-referenced by PHPXref |