Make WordPress Core

Ticket #50422: pluggable.php

File pluggable.php, 99.0 KB (added by KZeni, 4 years ago)

A patched version of pluggable.php from WP 5.4.2 with these 2 changes (add nocache_headers to wp_redirect and remove nocache_headers from auth_redirect [since it then uses wp_redirect that handles that now.])

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