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