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