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