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