3 * These functions can be replaced via plugins. If plugins do not redefine these
4 * functions, then these will be used instead.
9 if ( !function_exists('wp_set_current_user') ) :
11 * Changes the current user by ID or name.
13 * Set $id to null and specify a name if you do not know a user's ID.
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.
20 * @global WP_User $current_user The current user object which holds the user data.
22 * @param int $id User ID
23 * @param string $name User's username
24 * @return WP_User Current user User object
26 function wp_set_current_user($id, $name = '') {
29 // If `$id` matches the user who's already current, there's nothing to do.
30 if ( isset( $current_user )
31 && ( $current_user instanceof WP_User )
32 && ( $id == $current_user->ID )
38 $current_user = new WP_User( $id, $name );
40 setup_userdata( $current_user->ID );
43 * Fires after the current user is set.
47 do_action( 'set_current_user' );
53 if ( !function_exists('wp_get_current_user') ) :
55 * Retrieve the current user object.
57 * Will set the current user, if the current user is not set. The current user
58 * will be set to the logged-in person. If no user is logged-in, then it will
59 * set the current user to 0, which is invalid and won't have any permissions.
63 * @see _wp_get_current_user()
64 * @global WP_User $current_user Checks if the current user is set.
66 * @return WP_User Current WP_User instance.
68 function wp_get_current_user() {
69 return _wp_get_current_user();
73 if ( !function_exists('get_userdata') ) :
75 * Retrieve user info by user ID.
79 * @param int $user_id User ID
80 * @return WP_User|false WP_User object on success, false on failure.
82 function get_userdata( $user_id ) {
83 return get_user_by( 'id', $user_id );
87 if ( !function_exists('get_user_by') ) :
89 * Retrieve user info by a given field
92 * @since 4.4.0 Added 'ID' as an alias of 'id' for the `$field` parameter.
94 * @param string $field The field to retrieve the user with. id | ID | slug | email | login.
95 * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
96 * @return WP_User|false WP_User object on success, false on failure.
98 function get_user_by( $field, $value ) {
99 $userdata = WP_User::get_data_by( $field, $value );
105 $user->init( $userdata );
111 if ( !function_exists('cache_users') ) :
113 * Retrieve info for user lists to prevent multiple queries by get_userdata()
117 * @global wpdb $wpdb WordPress database abstraction object.
119 * @param array $user_ids User ID numbers list
121 function cache_users( $user_ids ) {
124 $clean = _get_non_cached_ids( $user_ids, 'users' );
126 if ( empty( $clean ) )
129 $list = implode( ',', $clean );
131 $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
134 foreach ( $users as $user ) {
135 update_user_caches( $user );
138 update_meta_cache( 'user', $ids );
142 if ( !function_exists( 'wp_mail' ) ) :
144 * Send mail, similar to PHP's mail
146 * A true return value does not automatically mean that the user received the
147 * email successfully. It just only means that the method used was able to
148 * process the request without any errors.
150 * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
151 * creating a from address like 'Name <email@address.com>' when both are set. If
152 * just 'wp_mail_from' is set, then just the email address will be used with no
155 * The default content type is 'text/plain' which does not allow using HTML.
156 * However, you can set the content type of the email by using the
157 * {@see 'wp_mail_content_type'} filter.
159 * The default charset is based on the charset used on the blog. The charset can
160 * be set using the {@see 'wp_mail_charset'} filter.
164 * @global PHPMailer $phpmailer
166 * @param string|array $to Array or comma-separated list of email addresses to send message.
167 * @param string $subject Email subject
168 * @param string $message Message contents
169 * @param string|array $headers Optional. Additional headers.
170 * @param string|array $attachments Optional. Files to attach.
171 * @return bool Whether the email contents were sent successfully.
173 function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
174 // Compact the input, apply the filters, and extract them back out
177 * Filters the wp_mail() arguments.
181 * @param array $args A compacted array of wp_mail() arguments, including the "to" email,
182 * subject, message, headers, and attachments values.
184 $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );
186 if ( isset( $atts['to'] ) ) {
190 if ( isset( $atts['subject'] ) ) {
191 $subject = $atts['subject'];
194 if ( isset( $atts['message'] ) ) {
195 $message = $atts['message'];
198 if ( isset( $atts['headers'] ) ) {
199 $headers = $atts['headers'];
202 if ( isset( $atts['attachments'] ) ) {
203 $attachments = $atts['attachments'];
206 if ( ! is_array( $attachments ) ) {
207 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
211 // (Re)create it, if it's gone missing
212 if ( ! ( $phpmailer instanceof PHPMailer ) ) {
213 require_once ABSPATH . WPINC . '/class-phpmailer.php';
214 require_once ABSPATH . WPINC . '/class-smtp.php';
215 $phpmailer = new PHPMailer( true );
219 $cc = $bcc = $reply_to = array();
221 if ( empty( $headers ) ) {
224 if ( !is_array( $headers ) ) {
225 // Explode the headers out, so this function can take both
226 // string headers and an array of headers.
227 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
229 $tempheaders = $headers;
233 // If it's actually got contents
234 if ( !empty( $tempheaders ) ) {
235 // Iterate through the raw headers
236 foreach ( (array) $tempheaders as $header ) {
237 if ( strpos($header, ':') === false ) {
238 if ( false !== stripos( $header, 'boundary=' ) ) {
239 $parts = preg_split('/boundary=/i', trim( $header ) );
240 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
245 list( $name, $content ) = explode( ':', trim( $header ), 2 );
248 $name = trim( $name );
249 $content = trim( $content );
251 switch ( strtolower( $name ) ) {
252 // Mainly for legacy -- process a From: header if it's there
254 $bracket_pos = strpos( $content, '<' );
255 if ( $bracket_pos !== false ) {
256 // Text before the bracketed email is the "From" name.
257 if ( $bracket_pos > 0 ) {
258 $from_name = substr( $content, 0, $bracket_pos - 1 );
259 $from_name = str_replace( '"', '', $from_name );
260 $from_name = trim( $from_name );
263 $from_email = substr( $content, $bracket_pos + 1 );
264 $from_email = str_replace( '>', '', $from_email );
265 $from_email = trim( $from_email );
267 // Avoid setting an empty $from_email.
268 } elseif ( '' !== trim( $content ) ) {
269 $from_email = trim( $content );
273 if ( strpos( $content, ';' ) !== false ) {
274 list( $type, $charset_content ) = explode( ';', $content );
275 $content_type = trim( $type );
276 if ( false !== stripos( $charset_content, 'charset=' ) ) {
277 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
278 } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
279 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
283 // Avoid setting an empty $content_type.
284 } elseif ( '' !== trim( $content ) ) {
285 $content_type = trim( $content );
289 $cc = array_merge( (array) $cc, explode( ',', $content ) );
292 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
295 $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) );
298 // Add it to our grand headers array
299 $headers[trim( $name )] = trim( $content );
306 // Empty out the values that may be set
307 $phpmailer->ClearAllRecipients();
308 $phpmailer->ClearAttachments();
309 $phpmailer->ClearCustomHeaders();
310 $phpmailer->ClearReplyTos();
312 // From email and name
313 // If we don't have a name from the input headers
314 if ( !isset( $from_name ) )
315 $from_name = 'WordPress';
317 /* If we don't have an email from the input headers default to wordpress@$sitename
318 * Some hosts will block outgoing mail from this address if it doesn't exist but
319 * there's no easy alternative. Defaulting to admin_email might appear to be another
320 * option but some hosts may refuse to relay mail from an unknown domain. See
321 * https://core.trac.wordpress.org/ticket/5007.
324 if ( !isset( $from_email ) ) {
325 // Get the site domain and get rid of www.
326 $sitename = strtolower( $_SERVER['SERVER_NAME'] );
327 if ( substr( $sitename, 0, 4 ) == 'www.' ) {
328 $sitename = substr( $sitename, 4 );
331 $from_email = 'wordpress@' . $sitename;
335 * Filters the email address to send from.
339 * @param string $from_email Email address to send from.
341 $from_email = apply_filters( 'wp_mail_from', $from_email );
344 * Filters the name to associate with the "from" email address.
348 * @param string $from_name Name associated with the "from" email address.
350 $from_name = apply_filters( 'wp_mail_from_name', $from_name );
352 $phpmailer->setFrom( $from_email, $from_name, false );
354 // Set destination addresses
355 if ( !is_array( $to ) )
356 $to = explode( ',', $to );
358 // Set mail's subject and body
359 $phpmailer->Subject = $subject;
360 $phpmailer->Body = $message;
362 // Use appropriate methods for handling addresses, rather than treating them as generic headers
363 $address_headers = compact( 'to', 'cc', 'bcc', 'reply_to' );
365 foreach ( $address_headers as $address_header => $addresses ) {
366 if ( empty( $addresses ) ) {
370 foreach ( (array) $addresses as $address ) {
372 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
373 $recipient_name = '';
375 if ( preg_match( '/(.*)<(.+)>/', $address, $matches ) ) {
376 if ( count( $matches ) == 3 ) {
377 $recipient_name = $matches[1];
378 $address = $matches[2];
382 switch ( $address_header ) {
384 $phpmailer->addAddress( $address, $recipient_name );
387 $phpmailer->addCc( $address, $recipient_name );
390 $phpmailer->addBcc( $address, $recipient_name );
393 $phpmailer->addReplyTo( $address, $recipient_name );
396 } catch ( phpmailerException $e ) {
402 // Set to use PHP's mail()
403 $phpmailer->IsMail();
405 // Set Content-Type and charset
406 // If we don't have a content-type from the input headers
407 if ( !isset( $content_type ) )
408 $content_type = 'text/plain';
411 * Filters the wp_mail() content type.
415 * @param string $content_type Default wp_mail() content type.
417 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
419 $phpmailer->ContentType = $content_type;
421 // Set whether it's plaintext, depending on $content_type
422 if ( 'text/html' == $content_type )
423 $phpmailer->IsHTML( true );
425 // If we don't have a charset from the input headers
426 if ( !isset( $charset ) )
427 $charset = get_bloginfo( 'charset' );
429 // Set the content-type and charset
432 * Filters the default wp_mail() charset.
436 * @param string $charset Default email charset.
438 $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
440 // Set custom headers
441 if ( !empty( $headers ) ) {
442 foreach ( (array) $headers as $name => $content ) {
443 $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
446 if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
447 $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
450 if ( !empty( $attachments ) ) {
451 foreach ( $attachments as $attachment ) {
453 $phpmailer->AddAttachment($attachment);
454 } catch ( phpmailerException $e ) {
461 * Fires after PHPMailer is initialized.
465 * @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
467 do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
471 return $phpmailer->Send();
472 } catch ( phpmailerException $e ) {
474 $mail_error_data = compact( 'to', 'subject', 'message', 'headers', 'attachments' );
475 $mail_error_data['phpmailer_exception_code'] = $e->getCode();
478 * Fires after a phpmailerException is caught.
482 * @param WP_Error $error A WP_Error object with the phpmailerException message, and an array
483 * containing the mail recipient, subject, message, headers, and attachments.
485 do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_error_data ) );
492 if ( !function_exists('wp_authenticate') ) :
494 * Authenticate a user, confirming the login credentials are valid.
497 * @since 4.5.0 `$username` now accepts an email address.
499 * @param string $username User's username or email address.
500 * @param string $password User's password.
501 * @return WP_User|WP_Error WP_User object if the credentials are valid,
502 * otherwise WP_Error.
504 function wp_authenticate($username, $password) {
505 $username = sanitize_user($username);
506 $password = trim($password);
509 * Filters whether a set of user login credentials are valid.
511 * A WP_User object is returned if the credentials authenticate a user.
512 * WP_Error or null otherwise.
515 * @since 4.5.0 `$username` now accepts an email address.
517 * @param null|WP_User|WP_Error $user WP_User if the user is authenticated.
518 * WP_Error or null otherwise.
519 * @param string $username Username or email address.
520 * @param string $password User password
522 $user = apply_filters( 'authenticate', null, $username, $password );
524 if ( $user == null ) {
525 // TODO what should the error message be? (Or would these even happen?)
526 // Only needed if all authentication handlers fail to return anything.
527 $user = new WP_Error( 'authentication_failed', __( '<strong>ERROR</strong>: Invalid username, email address or incorrect password.' ) );
530 $ignore_codes = array('empty_username', 'empty_password');
532 if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
534 * Fires after a user login has failed.
537 * @since 4.5.0 The value of `$username` can now be an email address.
539 * @param string $username Username or email address.
541 do_action( 'wp_login_failed', $username );
548 if ( !function_exists('wp_logout') ) :
550 * Log the current user out.
554 function wp_logout() {
555 wp_destroy_current_session();
556 wp_clear_auth_cookie();
559 * Fires after a user is logged-out.
563 do_action( 'wp_logout' );
567 if ( !function_exists('wp_validate_auth_cookie') ) :
569 * Validates authentication cookie.
571 * The checks include making sure that the authentication cookie is set and
572 * pulling in the contents (if $cookie is not used).
574 * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
575 * should be and compares the two.
579 * @global int $login_grace_period
581 * @param string $cookie Optional. If used, will validate contents instead of cookie's
582 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
583 * @return false|int False if invalid cookie, User ID if valid.
585 function wp_validate_auth_cookie($cookie = '', $scheme = '') {
586 if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
588 * Fires if an authentication cookie is malformed.
592 * @param string $cookie Malformed auth cookie.
593 * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth',
596 do_action( 'auth_cookie_malformed', $cookie, $scheme );
600 $scheme = $cookie_elements['scheme'];
601 $username = $cookie_elements['username'];
602 $hmac = $cookie_elements['hmac'];
603 $token = $cookie_elements['token'];
604 $expired = $expiration = $cookie_elements['expiration'];
606 // Allow a grace period for POST and Ajax requests
607 if ( wp_doing_ajax() || 'POST' == $_SERVER['REQUEST_METHOD'] ) {
608 $expired += HOUR_IN_SECONDS;
611 // Quick check to see if an honest cookie has expired
612 if ( $expired < time() ) {
614 * Fires once an authentication cookie has expired.
618 * @param array $cookie_elements An array of data for the authentication cookie.
620 do_action( 'auth_cookie_expired', $cookie_elements );
624 $user = get_user_by('login', $username);
627 * Fires if a bad username is entered in the user authentication process.
631 * @param array $cookie_elements An array of data for the authentication cookie.
633 do_action( 'auth_cookie_bad_username', $cookie_elements );
637 $pass_frag = substr($user->user_pass, 8, 4);
639 $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
641 // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
642 $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
643 $hash = hash_hmac( $algo, $username . '|' . $expiration . '|' . $token, $key );
645 if ( ! hash_equals( $hash, $hmac ) ) {
647 * Fires if a bad authentication cookie hash is encountered.
651 * @param array $cookie_elements An array of data for the authentication cookie.
653 do_action( 'auth_cookie_bad_hash', $cookie_elements );
657 $manager = WP_Session_Tokens::get_instance( $user->ID );
658 if ( ! $manager->verify( $token ) ) {
659 do_action( 'auth_cookie_bad_session_token', $cookie_elements );
663 // Ajax/POST grace period set above
664 if ( $expiration < time() ) {
665 $GLOBALS['login_grace_period'] = 1;
669 * Fires once an authentication cookie has been validated.
673 * @param array $cookie_elements An array of data for the authentication cookie.
674 * @param WP_User $user User object.
676 do_action( 'auth_cookie_valid', $cookie_elements, $user );
682 if ( !function_exists('wp_generate_auth_cookie') ) :
684 * Generate authentication cookie contents.
688 * @param int $user_id User ID
689 * @param int $expiration The time the cookie expires as a UNIX timestamp.
690 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
691 * @param string $token User's session token to use for this cookie
692 * @return string Authentication cookie contents. Empty string if user does not exist.
694 function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) {
695 $user = get_userdata($user_id);
701 $manager = WP_Session_Tokens::get_instance( $user_id );
702 $token = $manager->create( $expiration );
705 $pass_frag = substr($user->user_pass, 8, 4);
707 $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
709 // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
710 $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
711 $hash = hash_hmac( $algo, $user->user_login . '|' . $expiration . '|' . $token, $key );
713 $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash;
716 * Filters the authentication cookie.
720 * @param string $cookie Authentication cookie.
721 * @param int $user_id User ID.
722 * @param int $expiration The time the cookie expires as a UNIX timestamp.
723 * @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
724 * @param string $token User's session token used.
726 return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token );
730 if ( !function_exists('wp_parse_auth_cookie') ) :
732 * Parse a cookie into its components
736 * @param string $cookie
737 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
738 * @return array|false Authentication cookie components
740 function wp_parse_auth_cookie($cookie = '', $scheme = '') {
741 if ( empty($cookie) ) {
744 $cookie_name = AUTH_COOKIE;
747 $cookie_name = SECURE_AUTH_COOKIE;
750 $cookie_name = LOGGED_IN_COOKIE;
754 $cookie_name = SECURE_AUTH_COOKIE;
755 $scheme = 'secure_auth';
757 $cookie_name = AUTH_COOKIE;
762 if ( empty($_COOKIE[$cookie_name]) )
764 $cookie = $_COOKIE[$cookie_name];
767 $cookie_elements = explode('|', $cookie);
768 if ( count( $cookie_elements ) !== 4 ) {
772 list( $username, $expiration, $token, $hmac ) = $cookie_elements;
774 return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' );
778 if ( !function_exists('wp_set_auth_cookie') ) :
780 * Log in a user by setting authentication cookies.
782 * The $remember parameter increases the time that the cookie will be kept. The
783 * default the cookie is kept without remembering is two days. When $remember is
784 * set, the cookies will be kept for 14 days or two weeks.
787 * @since 4.3.0 Added the `$token` parameter.
789 * @param int $user_id User ID
790 * @param bool $remember Whether to remember the user
791 * @param mixed $secure Whether the admin cookies should only be sent over HTTPS.
793 * @param string $token Optional. User's session token to use for this cookie.
795 function wp_set_auth_cookie( $user_id, $remember = false, $secure = '', $token = '' ) {
798 * Filters the duration of the authentication cookie expiration period.
802 * @param int $length Duration of the expiration period in seconds.
803 * @param int $user_id User ID.
804 * @param bool $remember Whether to remember the user login. Default false.
806 $expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );
809 * Ensure the browser will continue to send the cookie after the expiration time is reached.
810 * Needed for the login grace period in wp_validate_auth_cookie().
812 $expire = $expiration + ( 12 * HOUR_IN_SECONDS );
814 /** This filter is documented in wp-includes/pluggable.php */
815 $expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember );
819 if ( '' === $secure ) {
823 // Front-end cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS.
824 $secure_logged_in_cookie = $secure && 'https' === parse_url( get_option( 'home' ), PHP_URL_SCHEME );
827 * Filters whether the connection is secure.
831 * @param bool $secure Whether the connection is secure.
832 * @param int $user_id User ID.
834 $secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );
837 * Filters whether to use a secure cookie when logged-in.
841 * @param bool $secure_logged_in_cookie Whether to use a secure cookie when logged-in.
842 * @param int $user_id User ID.
843 * @param bool $secure Whether the connection is secure.
845 $secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure );
848 $auth_cookie_name = SECURE_AUTH_COOKIE;
849 $scheme = 'secure_auth';
851 $auth_cookie_name = AUTH_COOKIE;
855 if ( '' === $token ) {
856 $manager = WP_Session_Tokens::get_instance( $user_id );
857 $token = $manager->create( $expiration );
860 $auth_cookie = wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token );
861 $logged_in_cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token );
864 * Fires immediately before the authentication cookie is set.
868 * @param string $auth_cookie Authentication cookie.
869 * @param int $expire The time the login grace period expires as a UNIX timestamp.
870 * Default is 12 hours past the cookie's expiration time.
871 * @param int $expiration The time when the authentication cookie expires as a UNIX timestamp.
872 * Default is 14 days from now.
873 * @param int $user_id User ID.
874 * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth', or 'logged_in'.
876 do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme );
879 * Fires immediately before the logged-in authentication cookie is set.
883 * @param string $logged_in_cookie The logged-in cookie.
884 * @param int $expire The time the login grace period expires as a UNIX timestamp.
885 * Default is 12 hours past the cookie's expiration time.
886 * @param int $expiration The time when the logged-in authentication cookie expires as a UNIX timestamp.
887 * Default is 14 days from now.
888 * @param int $user_id User ID.
889 * @param string $scheme Authentication scheme. Default 'logged_in'.
891 do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in' );
893 setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
894 setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
895 setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
896 if ( COOKIEPATH != SITECOOKIEPATH )
897 setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
901 if ( !function_exists('wp_clear_auth_cookie') ) :
903 * Removes all of the cookies associated with authentication.
907 function wp_clear_auth_cookie() {
909 * Fires just before the authentication cookies are cleared.
913 do_action( 'clear_auth_cookie' );
915 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
916 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
917 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
918 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
919 setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
920 setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
923 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
924 setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
925 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
926 setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
928 // Even older cookies
929 setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
930 setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
931 setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
932 setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
936 if ( !function_exists('is_user_logged_in') ) :
938 * Checks if the current visitor is a logged in user.
942 * @return bool True if user is logged in, false if not logged in.
944 function is_user_logged_in() {
945 $user = wp_get_current_user();
947 return $user->exists();
951 if ( !function_exists('auth_redirect') ) :
953 * Checks if a user is logged in, if not it redirects them to the login page.
957 function auth_redirect() {
958 // Checks if a user is logged in, if not redirects them to the login page
960 $secure = ( is_ssl() || force_ssl_admin() );
963 * Filters whether to use a secure authentication redirect.
967 * @param bool $secure Whether to use a secure authentication redirect. Default false.
969 $secure = apply_filters( 'secure_auth_redirect', $secure );
971 // If https is required and request is http, redirect
972 if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
973 if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
974 wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
977 wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
983 * Filters the authentication redirect scheme.
987 * @param string $scheme Authentication redirect scheme. Default empty.
989 $scheme = apply_filters( 'auth_redirect_scheme', '' );
991 if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) {
993 * Fires before the authentication redirect.
997 * @param int $user_id User ID.
999 do_action( 'auth_redirect', $user_id );
1001 // If the user wants ssl but the session is not ssl, redirect.
1002 if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
1003 if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
1004 wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
1007 wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
1012 return; // The cookie is good so we're done
1015 // The cookie is no good so force login
1018 $redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
1020 $login_url = wp_login_url($redirect, true);
1022 wp_redirect($login_url);
1027 if ( !function_exists('check_admin_referer') ) :
1029 * Makes sure that a user was referred from another admin page.
1031 * To avoid security exploits.
1035 * @param int|string $action Action nonce.
1036 * @param string $query_arg Optional. Key to check for nonce in `$_REQUEST` (since 2.5).
1037 * Default '_wpnonce'.
1038 * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
1039 * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
1041 function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
1042 if ( -1 == $action )
1043 _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2.0' );
1045 $adminurl = strtolower(admin_url());
1046 $referer = strtolower(wp_get_referer());
1047 $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
1050 * Fires once the admin request has been validated or not.
1054 * @param string $action The nonce action.
1055 * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
1056 * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
1058 do_action( 'check_admin_referer', $action, $result );
1060 if ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {
1061 wp_nonce_ays( $action );
1069 if ( !function_exists('check_ajax_referer') ) :
1071 * Verifies the Ajax request to prevent processing requests external of the blog.
1075 * @param int|string $action Action nonce.
1076 * @param false|string $query_arg Optional. Key to check for the nonce in `$_REQUEST` (since 2.5). If false,
1077 * `$_REQUEST` values will be evaluated for '_ajax_nonce', and '_wpnonce'
1078 * (in that order). Default false.
1079 * @param bool $die Optional. Whether to die early when the nonce cannot be verified.
1081 * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
1082 * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
1084 function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
1085 if ( -1 == $action ) {
1086 _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '4.7' );
1091 if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
1092 $nonce = $_REQUEST[ $query_arg ];
1093 elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
1094 $nonce = $_REQUEST['_ajax_nonce'];
1095 elseif ( isset( $_REQUEST['_wpnonce'] ) )
1096 $nonce = $_REQUEST['_wpnonce'];
1098 $result = wp_verify_nonce( $nonce, $action );
1101 * Fires once the Ajax request has been validated or not.
1105 * @param string $action The Ajax nonce action.
1106 * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
1107 * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
1109 do_action( 'check_ajax_referer', $action, $result );
1111 if ( $die && false === $result ) {
1112 if ( wp_doing_ajax() ) {
1123 if ( !function_exists('wp_redirect') ) :
1125 * Redirects to another page.
1127 * Note: wp_redirect() does not exit automatically, and should almost always be
1128 * followed by a call to `exit;`:
1130 * wp_redirect( $url );
1133 * Exiting can also be selectively manipulated by using wp_redirect() as a conditional
1134 * in conjunction with the {@see 'wp_redirect'} and {@see 'wp_redirect_location'} hooks:
1136 * if ( wp_redirect( $url ) ) {
1142 * @global bool $is_IIS
1144 * @param string $location The path to redirect to.
1145 * @param int $status Status code to use.
1146 * @return bool False if $location is not provided, true otherwise.
1148 function wp_redirect($location, $status = 302) {
1152 * Filters the redirect location.
1156 * @param string $location The path to redirect to.
1157 * @param int $status Status code to use.
1159 $location = apply_filters( 'wp_redirect', $location, $status );
1162 * Filters the redirect status code.
1166 * @param int $status Status code to use.
1167 * @param string $location The path to redirect to.
1169 $status = apply_filters( 'wp_redirect_status', $status, $location );
1174 $location = wp_sanitize_redirect($location);
1176 if ( !$is_IIS && PHP_SAPI != 'cgi-fcgi' )
1177 status_header($status); // This causes problems on IIS and some FastCGI setups
1179 header("Location: $location", true, $status);
1185 if ( !function_exists('wp_sanitize_redirect') ) :
1187 * Sanitizes a URL for use in a redirect.
1191 * @param string $location The path to redirect to.
1192 * @return string Redirect-sanitized URL.
1194 function wp_sanitize_redirect($location) {
1197 (?: [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
1198 | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
1199 | [\xE1-\xEC][\x80-\xBF]{2}
1200 | \xED[\x80-\x9F][\x80-\xBF]
1201 | [\xEE-\xEF][\x80-\xBF]{2}
1202 | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
1203 | [\xF1-\xF3][\x80-\xBF]{3}
1204 | \xF4[\x80-\x8F][\x80-\xBF]{2}
1205 ){1,40} # ...one or more times
1207 $location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location );
1208 $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()@]|i', '', $location);
1209 $location = wp_kses_no_null($location);
1211 // remove %0d and %0a from location
1212 $strip = array('%0d', '%0a', '%0D', '%0A');
1213 return _deep_replace( $strip, $location );
1217 * URL encode UTF-8 characters in a URL.
1223 * @see wp_sanitize_redirect()
1225 * @param array $matches RegEx matches against the redirect location.
1226 * @return string URL-encoded version of the first RegEx match.
1228 function _wp_sanitize_utf8_in_redirect( $matches ) {
1229 return urlencode( $matches[0] );
1233 if ( !function_exists('wp_safe_redirect') ) :
1235 * Performs a safe (local) redirect, using wp_redirect().
1237 * Checks whether the $location is using an allowed host, if it has an absolute
1238 * path. A plugin can therefore set or remove allowed host(s) to or from the
1241 * If the host is not allowed, then the redirect defaults to wp-admin on the siteurl
1242 * instead. This prevents malicious redirects which redirect to another host,
1243 * but only used in a few places.
1247 * @param string $location The path to redirect to.
1248 * @param int $status Status code to use.
1250 function wp_safe_redirect($location, $status = 302) {
1252 // Need to look at the URL the way it will end up in wp_redirect()
1253 $location = wp_sanitize_redirect($location);
1256 * Filters the redirect fallback URL for when the provided redirect is not safe (local).
1260 * @param string $fallback_url The fallback URL to use by default.
1261 * @param int $status The redirect status.
1263 $location = wp_validate_redirect( $location, apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ) );
1265 wp_redirect($location, $status);
1269 if ( !function_exists('wp_validate_redirect') ) :
1271 * Validates a URL for use in a redirect.
1273 * Checks whether the $location is using an allowed host, if it has an absolute
1274 * path. A plugin can therefore set or remove allowed host(s) to or from the
1277 * If the host is not allowed, then the redirect is to $default supplied
1281 * @param string $location The redirect to validate
1282 * @param string $default The value to return if $location is not allowed
1283 * @return string redirect-sanitized URL
1285 function wp_validate_redirect($location, $default = '') {
1286 $location = trim( $location );
1287 // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
1288 if ( substr($location, 0, 2) == '//' )
1289 $location = 'http:' . $location;
1291 // In php 5 parse_url may fail if the URL query part contains http://, bug #38143
1292 $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
1294 // @-operator is used to prevent possible warnings in PHP < 5.3.3.
1295 $lp = @parse_url($test);
1297 // Give up if malformed URL
1298 if ( false === $lp )
1301 // Allow only http and https schemes. No data:, etc.
1302 if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
1305 // Reject if certain components are set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
1306 if ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {
1310 // Reject malformed components parse_url() can return on odd inputs.
1311 foreach ( array( 'user', 'pass', 'host' ) as $component ) {
1312 if ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {
1317 $wpp = parse_url(home_url());
1320 * Filters the whitelist of hosts to redirect to.
1324 * @param array $hosts An array of allowed hosts.
1325 * @param bool|string $host The parsed host; empty if not isset.
1327 $allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );
1329 if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
1330 $location = $default;
1336 if ( ! function_exists('wp_notify_postauthor') ) :
1338 * Notify an author (and/or others) of a comment/trackback/pingback on a post.
1342 * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
1343 * @param string $deprecated Not used
1344 * @return bool True on completion. False if no email addresses were specified.
1346 function wp_notify_postauthor( $comment_id, $deprecated = null ) {
1347 if ( null !== $deprecated ) {
1348 _deprecated_argument( __FUNCTION__, '3.8.0' );
1351 $comment = get_comment( $comment_id );
1352 if ( empty( $comment ) || empty( $comment->comment_post_ID ) )
1355 $post = get_post( $comment->comment_post_ID );
1356 $author = get_userdata( $post->post_author );
1358 // Who to notify? By default, just the post author, but others can be added.
1361 $emails[] = $author->user_email;
1365 * Filters the list of email addresses to receive a comment notification.
1367 * By default, only post authors are notified of comments. This filter allows
1368 * others to be added.
1372 * @param array $emails An array of email addresses to receive a comment notification.
1373 * @param int $comment_id The comment ID.
1375 $emails = apply_filters( 'comment_notification_recipients', $emails, $comment->comment_ID );
1376 $emails = array_filter( $emails );
1378 // If there are no addresses to send the comment to, bail.
1379 if ( ! count( $emails ) ) {
1383 // Facilitate unsetting below without knowing the keys.
1384 $emails = array_flip( $emails );
1387 * Filters whether to notify comment authors of their comments on their own posts.
1389 * By default, comment authors aren't notified of their comments on their own
1390 * posts. This filter allows you to override that.
1394 * @param bool $notify Whether to notify the post author of their own comment.
1396 * @param int $comment_id The comment ID.
1398 $notify_author = apply_filters( 'comment_notification_notify_author', false, $comment->comment_ID );
1400 // The comment was left by the author
1401 if ( $author && ! $notify_author && $comment->user_id == $post->post_author ) {
1402 unset( $emails[ $author->user_email ] );
1405 // The author moderated a comment on their own post
1406 if ( $author && ! $notify_author && $post->post_author == get_current_user_id() ) {
1407 unset( $emails[ $author->user_email ] );
1410 // The post author is no longer a member of the blog
1411 if ( $author && ! $notify_author && ! user_can( $post->post_author, 'read_post', $post->ID ) ) {
1412 unset( $emails[ $author->user_email ] );
1415 // If there's no email to send the comment to, bail, otherwise flip array back around for use below
1416 if ( ! count( $emails ) ) {
1419 $emails = array_flip( $emails );
1422 $switched_locale = switch_to_locale( get_locale() );
1424 $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
1426 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1427 // we want to reverse this for the plain text arena of emails.
1428 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1429 $comment_content = wp_specialchars_decode( $comment->comment_content );
1431 switch ( $comment->comment_type ) {
1433 /* translators: 1: Post title */
1434 $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
1435 /* translators: 1: Trackback/pingback website name, 2: website IP, 3: website hostname */
1436 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1437 $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
1438 $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
1439 $notify_message .= __( 'You can see all trackbacks on this post here:' ) . "\r\n";
1440 /* translators: 1: blog name, 2: post title */
1441 $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
1444 /* translators: 1: Post title */
1445 $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
1446 /* translators: 1: Trackback/pingback website name, 2: website IP, 3: website hostname */
1447 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1448 $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
1449 $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
1450 $notify_message .= __( 'You can see all pingbacks on this post here:' ) . "\r\n";
1451 /* translators: 1: blog name, 2: post title */
1452 $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
1454 default: // Comments
1455 $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
1456 /* translators: 1: comment author, 2: author IP, 3: author domain */
1457 $notify_message .= sprintf( __( 'Author: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1458 $notify_message .= sprintf( __( 'Email: %s' ), $comment->comment_author_email ) . "\r\n";
1459 $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
1460 $notify_message .= sprintf( __('Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
1461 $notify_message .= __( 'You can see all comments on this post here:' ) . "\r\n";
1462 /* translators: 1: blog name, 2: post title */
1463 $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
1466 $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
1467 $notify_message .= sprintf( __('Permalink: %s'), get_comment_link( $comment ) ) . "\r\n";
1469 if ( user_can( $post->post_author, 'edit_comment', $comment->comment_ID ) ) {
1470 if ( EMPTY_TRASH_DAYS ) {
1471 $notify_message .= sprintf( __( 'Trash it: %s' ), admin_url( "comment.php?action=trash&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n";
1473 $notify_message .= sprintf( __( 'Delete it: %s' ), admin_url( "comment.php?action=delete&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n";
1475 $notify_message .= sprintf( __( 'Spam it: %s' ), admin_url( "comment.php?action=spam&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n";
1478 $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
1480 if ( '' == $comment->comment_author ) {
1481 $from = "From: \"$blogname\" <$wp_email>";
1482 if ( '' != $comment->comment_author_email )
1483 $reply_to = "Reply-To: $comment->comment_author_email";
1485 $from = "From: \"$comment->comment_author\" <$wp_email>";
1486 if ( '' != $comment->comment_author_email )
1487 $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
1490 $message_headers = "$from\n"
1491 . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1493 if ( isset($reply_to) )
1494 $message_headers .= $reply_to . "\n";
1497 * Filters the comment notification email text.
1501 * @param string $notify_message The comment notification email text.
1502 * @param int $comment_id Comment ID.
1504 $notify_message = apply_filters( 'comment_notification_text', $notify_message, $comment->comment_ID );
1507 * Filters the comment notification email subject.
1511 * @param string $subject The comment notification email subject.
1512 * @param int $comment_id Comment ID.
1514 $subject = apply_filters( 'comment_notification_subject', $subject, $comment->comment_ID );
1517 * Filters the comment notification email headers.
1521 * @param string $message_headers Headers for the comment notification email.
1522 * @param int $comment_id Comment ID.
1524 $message_headers = apply_filters( 'comment_notification_headers', $message_headers, $comment->comment_ID );
1526 foreach ( $emails as $email ) {
1527 @wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
1530 if ( $switched_locale ) {
1531 restore_previous_locale();
1538 if ( !function_exists('wp_notify_moderator') ) :
1540 * Notifies the moderator of the site about a new comment that is awaiting approval.
1544 * @global wpdb $wpdb WordPress database abstraction object.
1546 * Uses the {@see 'notify_moderator'} filter to determine whether the site moderator
1547 * should be notified, overriding the site setting.
1549 * @param int $comment_id Comment ID.
1550 * @return true Always returns true.
1552 function wp_notify_moderator($comment_id) {
1555 $maybe_notify = get_option( 'moderation_notify' );
1558 * Filters whether to send the site moderator email notifications, overriding the site setting.
1562 * @param bool $maybe_notify Whether to notify blog moderator.
1563 * @param int $comment_ID The id of the comment for the notification.
1565 $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_id );
1567 if ( ! $maybe_notify ) {
1571 $comment = get_comment($comment_id);
1572 $post = get_post($comment->comment_post_ID);
1573 $user = get_userdata( $post->post_author );
1574 // Send to the administration and to the post author if the author can modify the comment.
1575 $emails = array( get_option( 'admin_email' ) );
1576 if ( $user && user_can( $user->ID, 'edit_comment', $comment_id ) && ! empty( $user->user_email ) ) {
1577 if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) )
1578 $emails[] = $user->user_email;
1581 $switched_locale = switch_to_locale( get_locale() );
1583 $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
1584 $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
1586 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1587 // we want to reverse this for the plain text arena of emails.
1588 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1589 $comment_content = wp_specialchars_decode( $comment->comment_content );
1591 switch ( $comment->comment_type ) {
1593 /* translators: 1: Post title */
1594 $notify_message = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1595 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1596 /* translators: 1: Trackback/pingback website name, 2: website IP, 3: website hostname */
1597 $notify_message .= sprintf( __( 'Website: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1598 /* translators: 1: Trackback/pingback/comment author URL */
1599 $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
1600 $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment_content . "\r\n\r\n";
1603 /* translators: 1: Post title */
1604 $notify_message = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1605 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1606 /* translators: 1: Trackback/pingback website name, 2: website IP, 3: website hostname */
1607 $notify_message .= sprintf( __( 'Website: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1608 /* translators: 1: Trackback/pingback/comment author URL */
1609 $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
1610 $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment_content . "\r\n\r\n";
1612 default: // Comments
1613 /* translators: 1: Post title */
1614 $notify_message = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1615 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1616 /* translators: 1: Comment author name, 2: comment author's IP, 3: comment author IP's hostname */
1617 $notify_message .= sprintf( __( 'Author: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1618 /* translators: 1: Comment author URL */
1619 $notify_message .= sprintf( __( 'Email: %s' ), $comment->comment_author_email ) . "\r\n";
1620 /* translators: 1: Trackback/pingback/comment author URL */
1621 $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
1622 /* translators: 1: Comment text */
1623 $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
1627 /* translators: Comment moderation. 1: Comment action URL */
1628 $notify_message .= sprintf( __( 'Approve it: %s' ), admin_url( "comment.php?action=approve&c={$comment_id}#wpbody-content" ) ) . "\r\n";
1630 if ( EMPTY_TRASH_DAYS ) {
1631 /* translators: Comment moderation. 1: Comment action URL */
1632 $notify_message .= sprintf( __( 'Trash it: %s' ), admin_url( "comment.php?action=trash&c={$comment_id}#wpbody-content" ) ) . "\r\n";
1634 /* translators: Comment moderation. 1: Comment action URL */
1635 $notify_message .= sprintf( __( 'Delete it: %s' ), admin_url( "comment.php?action=delete&c={$comment_id}#wpbody-content" ) ) . "\r\n";
1638 /* translators: Comment moderation. 1: Comment action URL */
1639 $notify_message .= sprintf( __( 'Spam it: %s' ), admin_url( "comment.php?action=spam&c={$comment_id}#wpbody-content" ) ) . "\r\n";
1641 /* translators: Comment moderation. 1: Number of comments awaiting approval */
1642 $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
1643 'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
1644 $notify_message .= admin_url( "edit-comments.php?comment_status=moderated#wpbody-content" ) . "\r\n";
1646 /* translators: Comment moderation notification email subject. 1: Site name, 2: Post title */
1647 $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
1648 $message_headers = '';
1651 * Filters the list of recipients for comment moderation emails.
1655 * @param array $emails List of email addresses to notify for comment moderation.
1656 * @param int $comment_id Comment ID.
1658 $emails = apply_filters( 'comment_moderation_recipients', $emails, $comment_id );
1661 * Filters the comment moderation email text.
1665 * @param string $notify_message Text of the comment moderation email.
1666 * @param int $comment_id Comment ID.
1668 $notify_message = apply_filters( 'comment_moderation_text', $notify_message, $comment_id );
1671 * Filters the comment moderation email subject.
1675 * @param string $subject Subject of the comment moderation email.
1676 * @param int $comment_id Comment ID.
1678 $subject = apply_filters( 'comment_moderation_subject', $subject, $comment_id );
1681 * Filters the comment moderation email headers.
1685 * @param string $message_headers Headers for the comment moderation email.
1686 * @param int $comment_id Comment ID.
1688 $message_headers = apply_filters( 'comment_moderation_headers', $message_headers, $comment_id );
1690 foreach ( $emails as $email ) {
1691 @wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
1694 if ( $switched_locale ) {
1695 restore_previous_locale();
1702 if ( !function_exists('wp_password_change_notification') ) :
1704 * Notify the blog admin of a user changing password, normally via email.
1708 * @param WP_User $user User object.
1710 function wp_password_change_notification( $user ) {
1711 // send a copy of password change notification to the admin
1712 // but check to see if it's the admin whose password we're changing, and skip this
1713 if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) {
1714 /* translators: %s: user name */
1715 $message = sprintf( __( 'Password changed for user: %s' ), $user->user_login ) . "\r\n";
1716 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1717 // we want to reverse this for the plain text arena of emails.
1718 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1719 /* translators: %s: site title */
1720 wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] Password Changed' ), $blogname ), $message );
1725 if ( !function_exists('wp_new_user_notification') ) :
1727 * Email login credentials to a newly-registered user.
1729 * A new user registration notification is also sent to admin email.
1732 * @since 4.3.0 The `$plaintext_pass` parameter was changed to `$notify`.
1733 * @since 4.3.1 The `$plaintext_pass` parameter was deprecated. `$notify` added as a third parameter.
1734 * @since 4.6.0 The `$notify` parameter accepts 'user' for sending notification only to the user created.
1736 * @global wpdb $wpdb WordPress database object for queries.
1737 * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
1739 * @param int $user_id User ID.
1740 * @param null $deprecated Not used (argument deprecated).
1741 * @param string $notify Optional. Type of notification that should happen. Accepts 'admin' or an empty
1742 * string (admin only), 'user', or 'both' (admin and user). Default empty.
1744 function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {
1745 if ( $deprecated !== null ) {
1746 _deprecated_argument( __FUNCTION__, '4.3.1' );
1749 global $wpdb, $wp_hasher;
1750 $user = get_userdata( $user_id );
1752 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1753 // we want to reverse this for the plain text arena of emails.
1754 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1756 if ( 'user' !== $notify ) {
1757 $switched_locale = switch_to_locale( get_locale() );
1758 $message = sprintf( __( 'New user registration on your site %s:' ), $blogname ) . "\r\n\r\n";
1759 $message .= sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n";
1760 $message .= sprintf( __( 'Email: %s' ), $user->user_email ) . "\r\n";
1762 @wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] New User Registration' ), $blogname ), $message );
1764 if ( $switched_locale ) {
1765 restore_previous_locale();
1769 // `$deprecated was pre-4.3 `$plaintext_pass`. An empty `$plaintext_pass` didn't sent a user notification.
1770 if ( 'admin' === $notify || ( empty( $deprecated ) && empty( $notify ) ) ) {
1774 // Generate something random for a password reset key.
1775 $key = wp_generate_password( 20, false );
1777 /** This action is documented in wp-login.php */
1778 do_action( 'retrieve_password_key', $user->user_login, $key );
1780 // Now insert the key, hashed, into the DB.
1781 if ( empty( $wp_hasher ) ) {
1782 $wp_hasher = new PasswordHash( 8, true );
1784 $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
1785 $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user->user_login ) );
1787 $switched_locale = switch_to_locale( get_user_locale( $user ) );
1789 $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
1790 $message .= __('To set your password, visit the following address:') . "\r\n\r\n";
1791 $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n";
1793 $message .= wp_login_url() . "\r\n";
1795 wp_mail($user->user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message);
1797 if ( $switched_locale ) {
1798 restore_previous_locale();
1803 if ( !function_exists('wp_nonce_tick') ) :
1805 * Get the time-dependent variable for nonce creation.
1807 * A nonce has a lifespan of two ticks. Nonces in their second tick may be
1808 * updated, e.g. by autosave.
1812 * @return float Float value rounded up to the next highest integer.
1814 function wp_nonce_tick() {
1816 * Filters the lifespan of nonces in seconds.
1820 * @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
1822 $nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS );
1824 return ceil(time() / ( $nonce_life / 2 ));
1828 if ( !function_exists('wp_verify_nonce') ) :
1830 * Verify that correct nonce was used with time limit.
1832 * The user is given an amount of time to use the token, so therefore, since the
1833 * UID and $action remain the same, the independent variable is the time.
1837 * @param string $nonce Nonce that was used in the form to verify
1838 * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
1839 * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
1840 * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
1842 function wp_verify_nonce( $nonce, $action = -1 ) {
1843 $nonce = (string) $nonce;
1844 $user = wp_get_current_user();
1845 $uid = (int) $user->ID;
1848 * Filters whether the user who generated the nonce is logged out.
1852 * @param int $uid ID of the nonce-owning user.
1853 * @param string $action The nonce action.
1855 $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
1858 if ( empty( $nonce ) ) {
1862 $token = wp_get_session_token();
1863 $i = wp_nonce_tick();
1865 // Nonce generated 0-12 hours ago
1866 $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 );
1867 if ( hash_equals( $expected, $nonce ) ) {
1871 // Nonce generated 12-24 hours ago
1872 $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
1873 if ( hash_equals( $expected, $nonce ) ) {
1878 * Fires when nonce verification fails.
1882 * @param string $nonce The invalid nonce.
1883 * @param string|int $action The nonce action.
1884 * @param WP_User $user The current user object.
1885 * @param string $token The user's session token.
1887 do_action( 'wp_verify_nonce_failed', $nonce, $action, $user, $token );
1894 if ( !function_exists('wp_create_nonce') ) :
1896 * Creates a cryptographic token tied to a specific action, user, user session,
1897 * and window of time.
1900 * @since 4.0.0 Session tokens were integrated with nonce creation
1902 * @param string|int $action Scalar value to add context to the nonce.
1903 * @return string The token.
1905 function wp_create_nonce($action = -1) {
1906 $user = wp_get_current_user();
1907 $uid = (int) $user->ID;
1909 /** This filter is documented in wp-includes/pluggable.php */
1910 $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
1913 $token = wp_get_session_token();
1914 $i = wp_nonce_tick();
1916 return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
1920 if ( !function_exists('wp_salt') ) :
1922 * Get salt to add to hashes.
1924 * Salts are created using secret keys. Secret keys are located in two places:
1925 * in the database and in the wp-config.php file. The secret key in the database
1926 * is randomly generated and will be appended to the secret keys in wp-config.php.
1928 * The secret keys in wp-config.php should be updated to strong, random keys to maximize
1929 * security. Below is an example of how the secret key constants are defined.
1930 * Do not paste this example directly into wp-config.php. Instead, have a
1931 * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
1934 * define('AUTH_KEY', ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
1935 * define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
1936 * define('LOGGED_IN_KEY', '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
1937 * define('NONCE_KEY', '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
1938 * define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
1939 * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
1940 * define('LOGGED_IN_SALT', '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
1941 * define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
1943 * Salting passwords helps against tools which has stored hashed values of
1944 * common dictionary strings. The added values makes it harder to crack.
1948 * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
1950 * @staticvar array $cached_salts
1951 * @staticvar array $duplicated_keys
1953 * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
1954 * @return string Salt value
1956 function wp_salt( $scheme = 'auth' ) {
1957 static $cached_salts = array();
1958 if ( isset( $cached_salts[ $scheme ] ) ) {
1960 * Filters the WordPress salt.
1964 * @param string $cached_salt Cached salt for the given scheme.
1965 * @param string $scheme Authentication scheme. Values include 'auth',
1966 * 'secure_auth', 'logged_in', and 'nonce'.
1968 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
1971 static $duplicated_keys;
1972 if ( null === $duplicated_keys ) {
1973 $duplicated_keys = array( 'put your unique phrase here' => true );
1974 foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
1975 foreach ( array( 'KEY', 'SALT' ) as $second ) {
1976 if ( ! defined( "{$first}_{$second}" ) ) {
1979 $value = constant( "{$first}_{$second}" );
1980 $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
1989 if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) {
1990 $values['key'] = SECRET_KEY;
1992 if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) {
1993 $values['salt'] = SECRET_SALT;
1996 if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) {
1997 foreach ( array( 'key', 'salt' ) as $type ) {
1998 $const = strtoupper( "{$scheme}_{$type}" );
1999 if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
2000 $values[ $type ] = constant( $const );
2001 } elseif ( ! $values[ $type ] ) {
2002 $values[ $type ] = get_site_option( "{$scheme}_{$type}" );
2003 if ( ! $values[ $type ] ) {
2004 $values[ $type ] = wp_generate_password( 64, true, true );
2005 update_site_option( "{$scheme}_{$type}", $values[ $type ] );
2010 if ( ! $values['key'] ) {
2011 $values['key'] = get_site_option( 'secret_key' );
2012 if ( ! $values['key'] ) {
2013 $values['key'] = wp_generate_password( 64, true, true );
2014 update_site_option( 'secret_key', $values['key'] );
2017 $values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] );
2020 $cached_salts[ $scheme ] = $values['key'] . $values['salt'];
2022 /** This filter is documented in wp-includes/pluggable.php */
2023 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
2027 if ( !function_exists('wp_hash') ) :
2029 * Get hash of given string.
2033 * @param string $data Plain text to hash
2034 * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
2035 * @return string Hash of $data
2037 function wp_hash($data, $scheme = 'auth') {
2038 $salt = wp_salt($scheme);
2040 return hash_hmac('md5', $data, $salt);
2044 if ( !function_exists('wp_hash_password') ) :
2046 * Create a hash (encrypt) of a plain text password.
2048 * For integration with other applications, this function can be overwritten to
2049 * instead use the other package password checking algorithm.
2053 * @global PasswordHash $wp_hasher PHPass object
2055 * @param string $password Plain text user password to hash
2056 * @return string The hash string of the password
2058 function wp_hash_password($password) {
2061 if ( empty($wp_hasher) ) {
2062 // By default, use the portable hash from phpass
2063 $wp_hasher = new PasswordHash(8, true);
2066 return $wp_hasher->HashPassword( trim( $password ) );
2070 if ( !function_exists('wp_check_password') ) :
2072 * Checks the plaintext password against the encrypted Password.
2074 * Maintains compatibility between old version and the new cookie authentication
2075 * protocol using PHPass library. The $hash parameter is the encrypted password
2076 * and the function compares the plain text password when encrypted similarly
2077 * against the already encrypted password to see if they match.
2079 * For integration with other applications, this function can be overwritten to
2080 * instead use the other package password checking algorithm.
2084 * @global PasswordHash $wp_hasher PHPass object used for checking the password
2085 * against the $hash + $password
2086 * @uses PasswordHash::CheckPassword
2088 * @param string $password Plaintext user's password
2089 * @param string $hash Hash of the user's password to check against.
2090 * @param string|int $user_id Optional. User ID.
2091 * @return bool False, if the $password does not match the hashed password
2093 function wp_check_password($password, $hash, $user_id = '') {
2096 // If the hash is still md5...
2097 if ( strlen($hash) <= 32 ) {
2098 $check = hash_equals( $hash, md5( $password ) );
2099 if ( $check && $user_id ) {
2100 // Rehash using new hash.
2101 wp_set_password($password, $user_id);
2102 $hash = wp_hash_password($password);
2106 * Filters whether the plaintext password matches the encrypted password.
2110 * @param bool $check Whether the passwords match.
2111 * @param string $password The plaintext password.
2112 * @param string $hash The hashed password.
2113 * @param string|int $user_id User ID. Can be empty.
2115 return apply_filters( 'check_password', $check, $password, $hash, $user_id );
2118 // If the stored hash is longer than an MD5, presume the
2119 // new style phpass portable hash.
2120 if ( empty($wp_hasher) ) {
2121 // By default, use the portable hash from phpass
2122 $wp_hasher = new PasswordHash(8, true);
2125 $check = $wp_hasher->CheckPassword($password, $hash);
2127 /** This filter is documented in wp-includes/pluggable.php */
2128 return apply_filters( 'check_password', $check, $password, $hash, $user_id );
2132 if ( !function_exists('wp_generate_password') ) :
2134 * Generates a random password drawn from the defined set of characters.
2138 * @param int $length Optional. The length of password to generate. Default 12.
2139 * @param bool $special_chars Optional. Whether to include standard special characters.
2141 * @param bool $extra_special_chars Optional. Whether to include other special characters.
2142 * Used when generating secret keys and salts. Default false.
2143 * @return string The random password.
2145 function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
2146 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
2147 if ( $special_chars )
2148 $chars .= '!@#$%^&*()';
2149 if ( $extra_special_chars )
2150 $chars .= '-_ []{}<>~`+=,.;:/?|';
2153 for ( $i = 0; $i < $length; $i++ ) {
2154 $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
2158 * Filters the randomly-generated password.
2162 * @param string $password The generated password.
2164 return apply_filters( 'random_password', $password );
2168 if ( !function_exists('wp_rand') ) :
2170 * Generates a random number
2173 * @since 4.4.0 Uses PHP7 random_int() or the random_compat library if available.
2175 * @global string $rnd_value
2176 * @staticvar string $seed
2177 * @staticvar bool $external_rand_source_available
2179 * @param int $min Lower limit for the generated number
2180 * @param int $max Upper limit for the generated number
2181 * @return int A random number between min and max
2183 function wp_rand( $min = 0, $max = 0 ) {
2186 // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
2187 $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff
2189 // We only handle Ints, floats are truncated to their integer value.
2193 // Use PHP's CSPRNG, or a compatible method
2194 static $use_random_int_functionality = true;
2195 if ( $use_random_int_functionality ) {
2197 $_max = ( 0 != $max ) ? $max : $max_random_number;
2198 // wp_rand() can accept arguments in either order, PHP cannot.
2199 $_max = max( $min, $_max );
2200 $_min = min( $min, $_max );
2201 $val = random_int( $_min, $_max );
2202 if ( false !== $val ) {
2203 return absint( $val );
2205 $use_random_int_functionality = false;
2207 } catch ( Error $e ) {
2208 $use_random_int_functionality = false;
2209 } catch ( Exception $e ) {
2210 $use_random_int_functionality = false;
2214 // Reset $rnd_value after 14 uses
2215 // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
2216 if ( strlen($rnd_value) < 8 ) {
2217 if ( defined( 'WP_SETUP_CONFIG' ) )
2220 $seed = get_transient('random_seed');
2221 $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
2222 $rnd_value .= sha1($rnd_value);
2223 $rnd_value .= sha1($rnd_value . $seed);
2224 $seed = md5($seed . $rnd_value);
2225 if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) {
2226 set_transient( 'random_seed', $seed );
2230 // Take the first 8 digits for our value
2231 $value = substr($rnd_value, 0, 8);
2233 // Strip the first eight, leaving the remainder for the next call to wp_rand().
2234 $rnd_value = substr($rnd_value, 8);
2236 $value = abs(hexdec($value));
2238 // Reduce the value to be within the min - max range
2240 $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
2242 return abs(intval($value));
2246 if ( !function_exists('wp_set_password') ) :
2248 * Updates the user's password with a new encrypted one.
2250 * For integration with other applications, this function can be overwritten to
2251 * instead use the other package password checking algorithm.
2253 * Please note: This function should be used sparingly and is really only meant for single-time
2254 * application. Leveraging this improperly in a plugin or theme could result in an endless loop
2255 * of password resets if precautions are not taken to ensure it does not execute on every page load.
2259 * @global wpdb $wpdb WordPress database abstraction object.
2261 * @param string $password The plaintext new user password
2262 * @param int $user_id User ID
2264 function wp_set_password( $password, $user_id ) {
2267 $hash = wp_hash_password( $password );
2268 $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
2270 wp_cache_delete($user_id, 'users');
2274 if ( !function_exists( 'get_avatar' ) ) :
2276 * Retrieve the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post.
2279 * @since 4.2.0 Optional `$args` parameter added.
2281 * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
2282 * user email, WP_User object, WP_Post object, or WP_Comment object.
2283 * @param int $size Optional. Height and width of the avatar image file in pixels. Default 96.
2284 * @param string $default Optional. URL for the default image or a default type. Accepts '404'
2285 * (return a 404 instead of a default image), 'retro' (8bit), 'monsterid'
2286 * (monster), 'wavatar' (cartoon face), 'indenticon' (the "quilt"),
2287 * 'mystery', 'mm', or 'mysteryman' (The Oyster Man), 'blank' (transparent GIF),
2288 * or 'gravatar_default' (the Gravatar logo). Default is the value of the
2289 * 'avatar_default' option, with a fallback of 'mystery'.
2290 * @param string $alt Optional. Alternative text to use in <img> tag. Default empty.
2291 * @param array $args {
2292 * Optional. Extra arguments to retrieve the avatar.
2294 * @type int $height Display height of the avatar in pixels. Defaults to $size.
2295 * @type int $width Display width of the avatar in pixels. Defaults to $size.
2296 * @type bool $force_default Whether to always show the default image, never the Gravatar. Default false.
2297 * @type string $rating What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
2298 * judged in that order. Default is the value of the 'avatar_rating' option.
2299 * @type string $scheme URL scheme to use. See set_url_scheme() for accepted values.
2301 * @type array|string $class Array or string of additional classes to add to the <img> element.
2303 * @type bool $force_display Whether to always show the avatar - ignores the show_avatars option.
2305 * @type string $extra_attr HTML attributes to insert in the IMG element. Is not sanitized. Default empty.
2307 * @return false|string `<img>` tag for the user's avatar. False on failure.
2309 function get_avatar( $id_or_email, $size = 96, $default = '', $alt = '', $args = null ) {
2311 // get_avatar_data() args.
2315 'default' => get_option( 'avatar_default', 'mystery' ),
2316 'force_default' => false,
2317 'rating' => get_option( 'avatar_rating' ),
2321 'force_display' => false,
2325 if ( empty( $args ) ) {
2329 $args['size'] = (int) $size;
2330 $args['default'] = $default;
2331 $args['alt'] = $alt;
2333 $args = wp_parse_args( $args, $defaults );
2335 if ( empty( $args['height'] ) ) {
2336 $args['height'] = $args['size'];
2338 if ( empty( $args['width'] ) ) {
2339 $args['width'] = $args['size'];
2342 if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
2343 $id_or_email = get_comment( $id_or_email );
2347 * Filters whether to retrieve the avatar URL early.
2349 * Passing a non-null value will effectively short-circuit get_avatar(), passing
2350 * the value through the {@see 'get_avatar'} filter and returning early.
2354 * @param string $avatar HTML for the user's avatar. Default null.
2355 * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
2356 * user email, WP_User object, WP_Post object, or WP_Comment object.
2357 * @param array $args Arguments passed to get_avatar_url(), after processing.
2359 $avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args );
2361 if ( ! is_null( $avatar ) ) {
2362 /** This filter is documented in wp-includes/pluggable.php */
2363 return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
2366 if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) {
2370 $url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );
2372 $args = get_avatar_data( $id_or_email, $args );
2374 $url = $args['url'];
2376 if ( ! $url || is_wp_error( $url ) ) {
2380 $class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
2382 if ( ! $args['found_avatar'] || $args['force_default'] ) {
2383 $class[] = 'avatar-default';
2386 if ( $args['class'] ) {
2387 if ( is_array( $args['class'] ) ) {
2388 $class = array_merge( $class, $args['class'] );
2390 $class[] = $args['class'];
2395 "<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
2396 esc_attr( $args['alt'] ),
2398 esc_attr( "$url2x 2x" ),
2399 esc_attr( join( ' ', $class ) ),
2400 (int) $args['height'],
2401 (int) $args['width'],
2406 * Filters the avatar to retrieve.
2409 * @since 4.2.0 The `$args` parameter was added.
2411 * @param string $avatar <img> tag for the user's avatar.
2412 * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
2413 * user email, WP_User object, WP_Post object, or WP_Comment object.
2414 * @param int $size Square avatar width and height in pixels to retrieve.
2415 * @param string $alt Alternative text to use in the avatar image tag.
2417 * @param array $args Arguments passed to get_avatar_data(), after processing.
2419 return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
2423 if ( !function_exists( 'wp_text_diff' ) ) :
2425 * Displays a human readable HTML representation of the difference between two strings.
2427 * The Diff is available for getting the changes between versions. The output is
2428 * HTML, so the primary use is for displaying the changes. If the two strings
2429 * are equivalent, then an empty string will be returned.
2431 * The arguments supported and can be changed are listed below.
2433 * 'title' : Default is an empty string. Titles the diff in a manner compatible
2435 * 'title_left' : Default is an empty string. Change the HTML to the left of the
2437 * 'title_right' : Default is an empty string. Change the HTML to the right of
2442 * @see wp_parse_args() Used to change defaults to user defined settings.
2444 * @uses WP_Text_Diff_Renderer_Table
2446 * @param string $left_string "old" (left) version of string
2447 * @param string $right_string "new" (right) version of string
2448 * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
2449 * @return string Empty string if strings are equivalent or HTML with differences.
2451 function wp_text_diff( $left_string, $right_string, $args = null ) {
2452 $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
2453 $args = wp_parse_args( $args, $defaults );
2455 if ( ! class_exists( 'WP_Text_Diff_Renderer_Table', false ) )
2456 require( ABSPATH . WPINC . '/wp-diff.php' );
2458 $left_string = normalize_whitespace($left_string);
2459 $right_string = normalize_whitespace($right_string);
2461 $left_lines = explode("\n", $left_string);
2462 $right_lines = explode("\n", $right_string);
2463 $text_diff = new Text_Diff($left_lines, $right_lines);
2464 $renderer = new WP_Text_Diff_Renderer_Table( $args );
2465 $diff = $renderer->render($text_diff);
2470 $r = "<table class='diff'>\n";
2472 if ( ! empty( $args[ 'show_split_view' ] ) ) {
2473 $r .= "<col class='content diffsplit left' /><col class='content diffsplit middle' /><col class='content diffsplit right' />";
2475 $r .= "<col class='content' />";
2478 if ( $args['title'] || $args['title_left'] || $args['title_right'] )
2480 if ( $args['title'] )
2481 $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
2482 if ( $args['title_left'] || $args['title_right'] ) {
2483 $r .= "<tr class='diff-sub-title'>\n";
2484 $r .= "\t<td></td><th>$args[title_left]</th>\n";
2485 $r .= "\t<td></td><th>$args[title_right]</th>\n";
2488 if ( $args['title'] || $args['title_left'] || $args['title_right'] )
2491 $r .= "<tbody>\n$diff\n</tbody>\n";