]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/pluggable.php
WordPress 3.3.2-scripts
[autoinstalls/wordpress.git] / wp-includes / pluggable.php
1 <?php
2 /**
3  * These functions can be replaced via plugins. If plugins do not redefine these
4  * functions, then these will be used instead.
5  *
6  * @package WordPress
7  */
8
9 if ( !function_exists('wp_set_current_user') ) :
10 /**
11  * Changes the current user by ID or name.
12  *
13  * Set $id to null and specify a name if you do not know a user's ID.
14  *
15  * Some WordPress functionality is based on the current user and not based on
16  * the signed in user. Therefore, it opens the ability to edit and perform
17  * actions on users who aren't signed in.
18  *
19  * @since 2.0.3
20  * @global object $current_user The current user object which holds the user data.
21  * @uses do_action() Calls 'set_current_user' hook after setting the current user.
22  *
23  * @param int $id User ID
24  * @param string $name User's username
25  * @return WP_User Current user User object
26  */
27 function wp_set_current_user($id, $name = '') {
28         global $current_user;
29
30         if ( isset($current_user) && ($id == $current_user->ID) )
31                 return $current_user;
32
33         $current_user = new WP_User($id, $name);
34
35         setup_userdata($current_user->ID);
36
37         do_action('set_current_user');
38
39         return $current_user;
40 }
41 endif;
42
43 if ( !function_exists('wp_get_current_user') ) :
44 /**
45  * Retrieve the current user object.
46  *
47  * @since 2.0.3
48  *
49  * @return WP_User Current user WP_User object
50  */
51 function wp_get_current_user() {
52         global $current_user;
53
54         get_currentuserinfo();
55
56         return $current_user;
57 }
58 endif;
59
60 if ( !function_exists('get_currentuserinfo') ) :
61 /**
62  * Populate global variables with information about the currently logged in user.
63  *
64  * Will set the current user, if the current user is not set. The current user
65  * will be set to the logged in person. If no user is logged in, then it will
66  * set the current user to 0, which is invalid and won't have any permissions.
67  *
68  * @since 0.71
69  * @uses $current_user Checks if the current user is set
70  * @uses wp_validate_auth_cookie() Retrieves current logged in user.
71  *
72  * @return bool|null False on XMLRPC Request and invalid auth cookie. Null when current user set
73  */
74 function get_currentuserinfo() {
75         global $current_user;
76
77         if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST )
78                 return false;
79
80         if ( ! empty($current_user) )
81                 return;
82
83         if ( ! $user = wp_validate_auth_cookie() ) {
84                  if ( is_blog_admin() || is_network_admin() || empty($_COOKIE[LOGGED_IN_COOKIE]) || !$user = wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in') ) {
85                         wp_set_current_user(0);
86                         return false;
87                  }
88         }
89
90         wp_set_current_user($user);
91 }
92 endif;
93
94 if ( !function_exists('get_userdata') ) :
95 /**
96  * Retrieve user info by user ID.
97  *
98  * @since 0.71
99  *
100  * @param int $user_id User ID
101  * @return bool|object False on failure, WP_User object on success
102  */
103 function get_userdata( $user_id ) {
104         return get_user_by( 'id', $user_id );
105 }
106 endif;
107
108 if ( !function_exists('get_user_by') ) :
109 /**
110  * Retrieve user info by a given field
111  *
112  * @since 2.8.0
113  *
114  * @param string $field The field to retrieve the user with.  id | slug | email | login
115  * @param int|string $value A value for $field.  A user ID, slug, email address, or login name.
116  * @return bool|object False on failure, WP_User object on success
117  */
118 function get_user_by( $field, $value ) {
119         $userdata = WP_User::get_data_by( $field, $value );
120
121         if ( !$userdata )
122                 return false;
123
124         $user = new WP_User;
125         $user->init( $userdata );
126
127         return $user;
128 }
129 endif;
130
131 if ( !function_exists('cache_users') ) :
132 /**
133  * Retrieve info for user lists to prevent multiple queries by get_userdata()
134  *
135  * @since 3.0.0
136  *
137  * @param array $user_ids User ID numbers list
138  */
139 function cache_users( $user_ids ) {
140         global $wpdb;
141
142         $clean = array();
143         foreach ( $user_ids as $id ) {
144                 $id = (int) $id;
145                 if ( !wp_cache_get( $id, 'users' ) ) {
146                         $clean[] = $id;
147                 }
148         }
149
150         if ( empty( $clean ) )
151                 return;
152
153         $list = implode( ',', $clean );
154
155         $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
156
157         $ids = array();
158         foreach ( $users as $user ) {
159                 update_user_caches( $user );
160                 $ids[] = $user->ID;
161         }
162         update_meta_cache( 'user', $ids );
163 }
164 endif;
165
166 if ( !function_exists( 'wp_mail' ) ) :
167 /**
168  * Send mail, similar to PHP's mail
169  *
170  * A true return value does not automatically mean that the user received the
171  * email successfully. It just only means that the method used was able to
172  * process the request without any errors.
173  *
174  * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
175  * creating a from address like 'Name <email@address.com>' when both are set. If
176  * just 'wp_mail_from' is set, then just the email address will be used with no
177  * name.
178  *
179  * The default content type is 'text/plain' which does not allow using HTML.
180  * However, you can set the content type of the email by using the
181  * 'wp_mail_content_type' filter.
182  *
183  * The default charset is based on the charset used on the blog. The charset can
184  * be set using the 'wp_mail_charset' filter.
185  *
186  * @since 1.2.1
187  * @uses apply_filters() Calls 'wp_mail' hook on an array of all of the parameters.
188  * @uses apply_filters() Calls 'wp_mail_from' hook to get the from email address.
189  * @uses apply_filters() Calls 'wp_mail_from_name' hook to get the from address name.
190  * @uses apply_filters() Calls 'wp_mail_content_type' hook to get the email content type.
191  * @uses apply_filters() Calls 'wp_mail_charset' hook to get the email charset
192  * @uses do_action_ref_array() Calls 'phpmailer_init' hook on the reference to
193  *              phpmailer object.
194  * @uses PHPMailer
195  *
196  * @param string|array $to Array or comma-separated list of email addresses to send message.
197  * @param string $subject Email subject
198  * @param string $message Message contents
199  * @param string|array $headers Optional. Additional headers.
200  * @param string|array $attachments Optional. Files to attach.
201  * @return bool Whether the email contents were sent successfully.
202  */
203 function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
204         // Compact the input, apply the filters, and extract them back out
205         extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
206
207         if ( !is_array($attachments) )
208                 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
209
210         global $phpmailer;
211
212         // (Re)create it, if it's gone missing
213         if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) {
214                 require_once ABSPATH . WPINC . '/class-phpmailer.php';
215                 require_once ABSPATH . WPINC . '/class-smtp.php';
216                 $phpmailer = new PHPMailer( true );
217         }
218
219         // Headers
220         if ( empty( $headers ) ) {
221                 $headers = array();
222         } else {
223                 if ( !is_array( $headers ) ) {
224                         // Explode the headers out, so this function can take both
225                         // string headers and an array of headers.
226                         $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
227                 } else {
228                         $tempheaders = $headers;
229                 }
230                 $headers = array();
231                 $cc = array();
232                 $bcc = array();
233
234                 // If it's actually got contents
235                 if ( !empty( $tempheaders ) ) {
236                         // Iterate through the raw headers
237                         foreach ( (array) $tempheaders as $header ) {
238                                 if ( strpos($header, ':') === false ) {
239                                         if ( false !== stripos( $header, 'boundary=' ) ) {
240                                                 $parts = preg_split('/boundary=/i', trim( $header ) );
241                                                 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
242                                         }
243                                         continue;
244                                 }
245                                 // Explode them out
246                                 list( $name, $content ) = explode( ':', trim( $header ), 2 );
247
248                                 // Cleanup crew
249                                 $name    = trim( $name    );
250                                 $content = trim( $content );
251
252                                 switch ( strtolower( $name ) ) {
253                                         // Mainly for legacy -- process a From: header if it's there
254                                         case 'from':
255                                                 if ( strpos($content, '<' ) !== false ) {
256                                                         // So... making my life hard again?
257                                                         $from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
258                                                         $from_name = str_replace( '"', '', $from_name );
259                                                         $from_name = trim( $from_name );
260
261                                                         $from_email = substr( $content, strpos( $content, '<' ) + 1 );
262                                                         $from_email = str_replace( '>', '', $from_email );
263                                                         $from_email = trim( $from_email );
264                                                 } else {
265                                                         $from_email = trim( $content );
266                                                 }
267                                                 break;
268                                         case 'content-type':
269                                                 if ( strpos( $content, ';' ) !== false ) {
270                                                         list( $type, $charset ) = explode( ';', $content );
271                                                         $content_type = trim( $type );
272                                                         if ( false !== stripos( $charset, 'charset=' ) ) {
273                                                                 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) );
274                                                         } elseif ( false !== stripos( $charset, 'boundary=' ) ) {
275                                                                 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) );
276                                                                 $charset = '';
277                                                         }
278                                                 } else {
279                                                         $content_type = trim( $content );
280                                                 }
281                                                 break;
282                                         case 'cc':
283                                                 $cc = array_merge( (array) $cc, explode( ',', $content ) );
284                                                 break;
285                                         case 'bcc':
286                                                 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
287                                                 break;
288                                         default:
289                                                 // Add it to our grand headers array
290                                                 $headers[trim( $name )] = trim( $content );
291                                                 break;
292                                 }
293                         }
294                 }
295         }
296
297         // Empty out the values that may be set
298         $phpmailer->ClearAddresses();
299         $phpmailer->ClearAllRecipients();
300         $phpmailer->ClearAttachments();
301         $phpmailer->ClearBCCs();
302         $phpmailer->ClearCCs();
303         $phpmailer->ClearCustomHeaders();
304         $phpmailer->ClearReplyTos();
305
306         // From email and name
307         // If we don't have a name from the input headers
308         if ( !isset( $from_name ) )
309                 $from_name = 'WordPress';
310
311         /* If we don't have an email from the input headers default to wordpress@$sitename
312          * Some hosts will block outgoing mail from this address if it doesn't exist but
313          * there's no easy alternative. Defaulting to admin_email might appear to be another
314          * option but some hosts may refuse to relay mail from an unknown domain. See
315          * http://trac.wordpress.org/ticket/5007.
316          */
317
318         if ( !isset( $from_email ) ) {
319                 // Get the site domain and get rid of www.
320                 $sitename = strtolower( $_SERVER['SERVER_NAME'] );
321                 if ( substr( $sitename, 0, 4 ) == 'www.' ) {
322                         $sitename = substr( $sitename, 4 );
323                 }
324
325                 $from_email = 'wordpress@' . $sitename;
326         }
327
328         // Plugin authors can override the potentially troublesome default
329         $phpmailer->From     = apply_filters( 'wp_mail_from'     , $from_email );
330         $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name  );
331
332         // Set destination addresses
333         if ( !is_array( $to ) )
334                 $to = explode( ',', $to );
335
336         foreach ( (array) $to as $recipient ) {
337                 try {
338                         // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
339                         $recipient_name = '';
340                         if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
341                                 if ( count( $matches ) == 3 ) {
342                                         $recipient_name = $matches[1];
343                                         $recipient = $matches[2];
344                                 }
345                         }
346                         $phpmailer->AddAddress( $recipient, $recipient_name);
347                 } catch ( phpmailerException $e ) {
348                         continue;
349                 }
350         }
351
352         // Set mail's subject and body
353         $phpmailer->Subject = $subject;
354         $phpmailer->Body    = $message;
355
356         // Add any CC and BCC recipients
357         if ( !empty( $cc ) ) {
358                 foreach ( (array) $cc as $recipient ) {
359                         try {
360                                 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
361                                 $recipient_name = '';
362                                 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
363                                         if ( count( $matches ) == 3 ) {
364                                                 $recipient_name = $matches[1];
365                                                 $recipient = $matches[2];
366                                         }
367                                 }
368                                 $phpmailer->AddCc( $recipient, $recipient_name );
369                         } catch ( phpmailerException $e ) {
370                                 continue;
371                         }
372                 }
373         }
374
375         if ( !empty( $bcc ) ) {
376                 foreach ( (array) $bcc as $recipient) {
377                         try {
378                                 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
379                                 $recipient_name = '';
380                                 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
381                                         if ( count( $matches ) == 3 ) {
382                                                 $recipient_name = $matches[1];
383                                                 $recipient = $matches[2];
384                                         }
385                                 }
386                                 $phpmailer->AddBcc( $recipient, $recipient_name );
387                         } catch ( phpmailerException $e ) {
388                                 continue;
389                         }
390                 }
391         }
392
393         // Set to use PHP's mail()
394         $phpmailer->IsMail();
395
396         // Set Content-Type and charset
397         // If we don't have a content-type from the input headers
398         if ( !isset( $content_type ) )
399                 $content_type = 'text/plain';
400
401         $content_type = apply_filters( 'wp_mail_content_type', $content_type );
402
403         $phpmailer->ContentType = $content_type;
404
405         // Set whether it's plaintext, depending on $content_type
406         if ( 'text/html' == $content_type )
407                 $phpmailer->IsHTML( true );
408
409         // If we don't have a charset from the input headers
410         if ( !isset( $charset ) )
411                 $charset = get_bloginfo( 'charset' );
412
413         // Set the content-type and charset
414         $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
415
416         // Set custom headers
417         if ( !empty( $headers ) ) {
418                 foreach( (array) $headers as $name => $content ) {
419                         $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
420                 }
421
422                 if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
423                         $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
424         }
425
426         if ( !empty( $attachments ) ) {
427                 foreach ( $attachments as $attachment ) {
428                         try {
429                                 $phpmailer->AddAttachment($attachment);
430                         } catch ( phpmailerException $e ) {
431                                 continue;
432                         }
433                 }
434         }
435
436         do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
437
438         // Send!
439         try {
440                 $phpmailer->Send();
441         } catch ( phpmailerException $e ) {
442                 return false;
443         }
444
445         return true;
446 }
447 endif;
448
449 if ( !function_exists('wp_authenticate') ) :
450 /**
451  * Checks a user's login information and logs them in if it checks out.
452  *
453  * @since 2.5.0
454  *
455  * @param string $username User's username
456  * @param string $password User's password
457  * @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object.
458  */
459 function wp_authenticate($username, $password) {
460         $username = sanitize_user($username);
461         $password = trim($password);
462
463         $user = apply_filters('authenticate', null, $username, $password);
464
465         if ( $user == null ) {
466                 // TODO what should the error message be? (Or would these even happen?)
467                 // Only needed if all authentication handlers fail to return anything.
468                 $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
469         }
470
471         $ignore_codes = array('empty_username', 'empty_password');
472
473         if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
474                 do_action('wp_login_failed', $username);
475         }
476
477         return $user;
478 }
479 endif;
480
481 if ( !function_exists('wp_logout') ) :
482 /**
483  * Log the current user out.
484  *
485  * @since 2.5.0
486  */
487 function wp_logout() {
488         wp_clear_auth_cookie();
489         do_action('wp_logout');
490 }
491 endif;
492
493 if ( !function_exists('wp_validate_auth_cookie') ) :
494 /**
495  * Validates authentication cookie.
496  *
497  * The checks include making sure that the authentication cookie is set and
498  * pulling in the contents (if $cookie is not used).
499  *
500  * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
501  * should be and compares the two.
502  *
503  * @since 2.5
504  *
505  * @param string $cookie Optional. If used, will validate contents instead of cookie's
506  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
507  * @return bool|int False if invalid cookie, User ID if valid.
508  */
509 function wp_validate_auth_cookie($cookie = '', $scheme = '') {
510         if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
511                 do_action('auth_cookie_malformed', $cookie, $scheme);
512                 return false;
513         }
514
515         extract($cookie_elements, EXTR_OVERWRITE);
516
517         $expired = $expiration;
518
519         // Allow a grace period for POST and AJAX requests
520         if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] )
521                 $expired += 3600;
522
523         // Quick check to see if an honest cookie has expired
524         if ( $expired < time() ) {
525                 do_action('auth_cookie_expired', $cookie_elements);
526                 return false;
527         }
528
529         $user = get_user_by('login', $username);
530         if ( ! $user ) {
531                 do_action('auth_cookie_bad_username', $cookie_elements);
532                 return false;
533         }
534
535         $pass_frag = substr($user->user_pass, 8, 4);
536
537         $key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme);
538         $hash = hash_hmac('md5', $username . '|' . $expiration, $key);
539
540         if ( $hmac != $hash ) {
541                 do_action('auth_cookie_bad_hash', $cookie_elements);
542                 return false;
543         }
544
545         if ( $expiration < time() ) // AJAX/POST grace period set above
546                 $GLOBALS['login_grace_period'] = 1;
547
548         do_action('auth_cookie_valid', $cookie_elements, $user);
549
550         return $user->ID;
551 }
552 endif;
553
554 if ( !function_exists('wp_generate_auth_cookie') ) :
555 /**
556  * Generate authentication cookie contents.
557  *
558  * @since 2.5
559  * @uses apply_filters() Calls 'auth_cookie' hook on $cookie contents, User ID
560  *              and expiration of cookie.
561  *
562  * @param int $user_id User ID
563  * @param int $expiration Cookie expiration in seconds
564  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
565  * @return string Authentication cookie contents
566  */
567 function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') {
568         $user = get_userdata($user_id);
569
570         $pass_frag = substr($user->user_pass, 8, 4);
571
572         $key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme);
573         $hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key);
574
575         $cookie = $user->user_login . '|' . $expiration . '|' . $hash;
576
577         return apply_filters('auth_cookie', $cookie, $user_id, $expiration, $scheme);
578 }
579 endif;
580
581 if ( !function_exists('wp_parse_auth_cookie') ) :
582 /**
583  * Parse a cookie into its components
584  *
585  * @since 2.7
586  *
587  * @param string $cookie
588  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
589  * @return array Authentication cookie components
590  */
591 function wp_parse_auth_cookie($cookie = '', $scheme = '') {
592         if ( empty($cookie) ) {
593                 switch ($scheme){
594                         case 'auth':
595                                 $cookie_name = AUTH_COOKIE;
596                                 break;
597                         case 'secure_auth':
598                                 $cookie_name = SECURE_AUTH_COOKIE;
599                                 break;
600                         case "logged_in":
601                                 $cookie_name = LOGGED_IN_COOKIE;
602                                 break;
603                         default:
604                                 if ( is_ssl() ) {
605                                         $cookie_name = SECURE_AUTH_COOKIE;
606                                         $scheme = 'secure_auth';
607                                 } else {
608                                         $cookie_name = AUTH_COOKIE;
609                                         $scheme = 'auth';
610                                 }
611             }
612
613                 if ( empty($_COOKIE[$cookie_name]) )
614                         return false;
615                 $cookie = $_COOKIE[$cookie_name];
616         }
617
618         $cookie_elements = explode('|', $cookie);
619         if ( count($cookie_elements) != 3 )
620                 return false;
621
622         list($username, $expiration, $hmac) = $cookie_elements;
623
624         return compact('username', 'expiration', 'hmac', 'scheme');
625 }
626 endif;
627
628 if ( !function_exists('wp_set_auth_cookie') ) :
629 /**
630  * Sets the authentication cookies based User ID.
631  *
632  * The $remember parameter increases the time that the cookie will be kept. The
633  * default the cookie is kept without remembering is two days. When $remember is
634  * set, the cookies will be kept for 14 days or two weeks.
635  *
636  * @since 2.5
637  *
638  * @param int $user_id User ID
639  * @param bool $remember Whether to remember the user
640  */
641 function wp_set_auth_cookie($user_id, $remember = false, $secure = '') {
642         if ( $remember ) {
643                 $expiration = $expire = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, $remember);
644         } else {
645                 $expiration = time() + apply_filters('auth_cookie_expiration', 172800, $user_id, $remember);
646                 $expire = 0;
647         }
648
649         if ( '' === $secure )
650                 $secure = is_ssl();
651
652         $secure = apply_filters('secure_auth_cookie', $secure, $user_id);
653         $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', false, $user_id, $secure);
654
655         if ( $secure ) {
656                 $auth_cookie_name = SECURE_AUTH_COOKIE;
657                 $scheme = 'secure_auth';
658         } else {
659                 $auth_cookie_name = AUTH_COOKIE;
660                 $scheme = 'auth';
661         }
662
663         $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme);
664         $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
665
666         do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme);
667         do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in');
668
669         setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
670         setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
671         setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
672         if ( COOKIEPATH != SITECOOKIEPATH )
673                 setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
674 }
675 endif;
676
677 if ( !function_exists('wp_clear_auth_cookie') ) :
678 /**
679  * Removes all of the cookies associated with authentication.
680  *
681  * @since 2.5
682  */
683 function wp_clear_auth_cookie() {
684         do_action('clear_auth_cookie');
685
686         setcookie(AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
687         setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
688         setcookie(AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
689         setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
690         setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
691         setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
692
693         // Old cookies
694         setcookie(AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
695         setcookie(AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
696         setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
697         setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
698
699         // Even older cookies
700         setcookie(USER_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
701         setcookie(PASS_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
702         setcookie(USER_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
703         setcookie(PASS_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
704 }
705 endif;
706
707 if ( !function_exists('is_user_logged_in') ) :
708 /**
709  * Checks if the current visitor is a logged in user.
710  *
711  * @since 2.0.0
712  *
713  * @return bool True if user is logged in, false if not logged in.
714  */
715 function is_user_logged_in() {
716         $user = wp_get_current_user();
717
718         if ( empty( $user->ID ) )
719                 return false;
720
721         return true;
722 }
723 endif;
724
725 if ( !function_exists('auth_redirect') ) :
726 /**
727  * Checks if a user is logged in, if not it redirects them to the login page.
728  *
729  * @since 1.5
730  */
731 function auth_redirect() {
732         // Checks if a user is logged in, if not redirects them to the login page
733
734         $secure = ( is_ssl() || force_ssl_admin() );
735
736         $secure = apply_filters('secure_auth_redirect', $secure);
737
738         // If https is required and request is http, redirect
739         if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
740                 if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
741                         wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
742                         exit();
743                 } else {
744                         wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
745                         exit();
746                 }
747         }
748
749         if ( is_user_admin() )
750                 $scheme = 'logged_in';
751         else
752                 $scheme = apply_filters( 'auth_redirect_scheme', '' );
753
754         if ( $user_id = wp_validate_auth_cookie( '',  $scheme) ) {
755                 do_action('auth_redirect', $user_id);
756
757                 // If the user wants ssl but the session is not ssl, redirect.
758                 if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
759                         if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
760                                 wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
761                                 exit();
762                         } else {
763                                 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
764                                 exit();
765                         }
766                 }
767
768                 return;  // The cookie is good so we're done
769         }
770
771         // The cookie is no good so force login
772         nocache_headers();
773
774         if ( is_ssl() )
775                 $proto = 'https://';
776         else
777                 $proto = 'http://';
778
779         $redirect = ( strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ) ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
780
781         $login_url = wp_login_url($redirect, true);
782
783         wp_redirect($login_url);
784         exit();
785 }
786 endif;
787
788 if ( !function_exists('check_admin_referer') ) :
789 /**
790  * Makes sure that a user was referred from another admin page.
791  *
792  * To avoid security exploits.
793  *
794  * @since 1.2.0
795  * @uses do_action() Calls 'check_admin_referer' on $action.
796  *
797  * @param string $action Action nonce
798  * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
799  */
800 function check_admin_referer($action = -1, $query_arg = '_wpnonce') {
801         if ( -1 == $action )
802                 _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
803
804         $adminurl = strtolower(admin_url());
805         $referer = strtolower(wp_get_referer());
806         $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
807         if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
808                 wp_nonce_ays($action);
809                 die();
810         }
811         do_action('check_admin_referer', $action, $result);
812         return $result;
813 }endif;
814
815 if ( !function_exists('check_ajax_referer') ) :
816 /**
817  * Verifies the AJAX request to prevent processing requests external of the blog.
818  *
819  * @since 2.0.3
820  *
821  * @param string $action Action nonce
822  * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
823  */
824 function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
825         if ( $query_arg )
826                 $nonce = $_REQUEST[$query_arg];
827         else
828                 $nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce'];
829
830         $result = wp_verify_nonce( $nonce, $action );
831
832         if ( $die && false == $result )
833                 die('-1');
834
835         do_action('check_ajax_referer', $action, $result);
836
837         return $result;
838 }
839 endif;
840
841 if ( !function_exists('wp_redirect') ) :
842 /**
843  * Redirects to another page.
844  *
845  * @since 1.5.1
846  * @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
847  *
848  * @param string $location The path to redirect to
849  * @param int $status Status code to use
850  * @return bool False if $location is not set
851  */
852 function wp_redirect($location, $status = 302) {
853         global $is_IIS;
854
855         $location = apply_filters('wp_redirect', $location, $status);
856         $status = apply_filters('wp_redirect_status', $status, $location);
857
858         if ( !$location ) // allows the wp_redirect filter to cancel a redirect
859                 return false;
860
861         $location = wp_sanitize_redirect($location);
862
863         if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
864                 status_header($status); // This causes problems on IIS and some FastCGI setups
865
866         header("Location: $location", true, $status);
867 }
868 endif;
869
870 if ( !function_exists('wp_sanitize_redirect') ) :
871 /**
872  * Sanitizes a URL for use in a redirect.
873  *
874  * @since 2.3
875  *
876  * @return string redirect-sanitized URL
877  **/
878 function wp_sanitize_redirect($location) {
879         $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location);
880         $location = wp_kses_no_null($location);
881
882         // remove %0d and %0a from location
883         $strip = array('%0d', '%0a', '%0D', '%0A');
884         $location = _deep_replace($strip, $location);
885         return $location;
886 }
887 endif;
888
889 if ( !function_exists('wp_safe_redirect') ) :
890 /**
891  * Performs a safe (local) redirect, using wp_redirect().
892  *
893  * Checks whether the $location is using an allowed host, if it has an absolute
894  * path. A plugin can therefore set or remove allowed host(s) to or from the
895  * list.
896  *
897  * If the host is not allowed, then the redirect is to wp-admin on the siteurl
898  * instead. This prevents malicious redirects which redirect to another host,
899  * but only used in a few places.
900  *
901  * @since 2.3
902  * @uses wp_validate_redirect() To validate the redirect is to an allowed host.
903  *
904  * @return void Does not return anything
905  **/
906 function wp_safe_redirect($location, $status = 302) {
907
908         // Need to look at the URL the way it will end up in wp_redirect()
909         $location = wp_sanitize_redirect($location);
910
911         $location = wp_validate_redirect($location, admin_url());
912
913         wp_redirect($location, $status);
914 }
915 endif;
916
917 if ( !function_exists('wp_validate_redirect') ) :
918 /**
919  * Validates a URL for use in a redirect.
920  *
921  * Checks whether the $location is using an allowed host, if it has an absolute
922  * path. A plugin can therefore set or remove allowed host(s) to or from the
923  * list.
924  *
925  * If the host is not allowed, then the redirect is to $default supplied
926  *
927  * @since 2.8.1
928  * @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing
929  *              WordPress host string and $location host string.
930  *
931  * @param string $location The redirect to validate
932  * @param string $default The value to return is $location is not allowed
933  * @return string redirect-sanitized URL
934  **/
935 function wp_validate_redirect($location, $default = '') {
936         // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
937         if ( substr($location, 0, 2) == '//' )
938                 $location = 'http:' . $location;
939
940         // In php 5 parse_url may fail if the URL query part contains http://, bug #38143
941         $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
942
943         $lp  = parse_url($test);
944
945         // Give up if malformed URL
946         if ( false === $lp )
947                 return $default;
948
949         // Allow only http and https schemes. No data:, etc.
950         if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
951                 return $default;
952
953         // 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.
954         if ( isset($lp['scheme'])  && !isset($lp['host']) )
955                 return $default;
956
957         $wpp = parse_url(home_url());
958
959         $allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '');
960
961         if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
962                 $location = $default;
963
964         return $location;
965 }
966 endif;
967
968 if ( ! function_exists('wp_notify_postauthor') ) :
969 /**
970  * Notify an author of a comment/trackback/pingback to one of their posts.
971  *
972  * @since 1.0.0
973  *
974  * @param int $comment_id Comment ID
975  * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback'
976  * @return bool False if user email does not exist. True on completion.
977  */
978 function wp_notify_postauthor( $comment_id, $comment_type = '' ) {
979         $comment = get_comment( $comment_id );
980         $post    = get_post( $comment->comment_post_ID );
981         $author  = get_userdata( $post->post_author );
982
983         // The comment was left by the author
984         if ( $comment->user_id == $post->post_author )
985                 return false;
986
987         // The author moderated a comment on his own post
988         if ( $post->post_author == get_current_user_id() )
989                 return false;
990
991         // If there's no email to send the comment to
992         if ( '' == $author->user_email )
993                 return false;
994
995         $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
996
997         // The blogname option is escaped with esc_html on the way into the database in sanitize_option
998         // we want to reverse this for the plain text arena of emails.
999         $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1000
1001         if ( empty( $comment_type ) ) $comment_type = 'comment';
1002
1003         if ('comment' == $comment_type) {
1004                 $notify_message  = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
1005                 /* translators: 1: comment author, 2: author IP, 3: author domain */
1006                 $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1007                 $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
1008                 $notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
1009                 $notify_message .= sprintf( __('Whois  : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
1010                 $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1011                 $notify_message .= __('You can see all comments on this post here: ') . "\r\n";
1012                 /* translators: 1: blog name, 2: post title */
1013                 $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
1014         } elseif ('trackback' == $comment_type) {
1015                 $notify_message  = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
1016                 /* translators: 1: website name, 2: author IP, 3: author domain */
1017                 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1018                 $notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
1019                 $notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1020                 $notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n";
1021                 /* translators: 1: blog name, 2: post title */
1022                 $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
1023         } elseif ('pingback' == $comment_type) {
1024                 $notify_message  = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
1025                 /* translators: 1: comment author, 2: author IP, 3: author domain */
1026                 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1027                 $notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
1028                 $notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n";
1029                 $notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n";
1030                 /* translators: 1: blog name, 2: post title */
1031                 $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
1032         }
1033         $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
1034         $notify_message .= sprintf( __('Permalink: %s'), get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment_id ) . "\r\n";
1035         if ( EMPTY_TRASH_DAYS )
1036                 $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
1037         else
1038                 $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
1039         $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
1040
1041         $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
1042
1043         if ( '' == $comment->comment_author ) {
1044                 $from = "From: \"$blogname\" <$wp_email>";
1045                 if ( '' != $comment->comment_author_email )
1046                         $reply_to = "Reply-To: $comment->comment_author_email";
1047         } else {
1048                 $from = "From: \"$comment->comment_author\" <$wp_email>";
1049                 if ( '' != $comment->comment_author_email )
1050                         $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
1051         }
1052
1053         $message_headers = "$from\n"
1054                 . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1055
1056         if ( isset($reply_to) )
1057                 $message_headers .= $reply_to . "\n";
1058
1059         $notify_message = apply_filters('comment_notification_text', $notify_message, $comment_id);
1060         $subject = apply_filters('comment_notification_subject', $subject, $comment_id);
1061         $message_headers = apply_filters('comment_notification_headers', $message_headers, $comment_id);
1062
1063         @wp_mail( $author->user_email, $subject, $notify_message, $message_headers );
1064
1065         return true;
1066 }
1067 endif;
1068
1069 if ( !function_exists('wp_notify_moderator') ) :
1070 /**
1071  * Notifies the moderator of the blog about a new comment that is awaiting approval.
1072  *
1073  * @since 1.0
1074  * @uses $wpdb
1075  *
1076  * @param int $comment_id Comment ID
1077  * @return bool Always returns true
1078  */
1079 function wp_notify_moderator($comment_id) {
1080         global $wpdb;
1081
1082         if ( 0 == get_option( 'moderation_notify' ) )
1083                 return true;
1084
1085         $comment = get_comment($comment_id);
1086         $post = get_post($comment->comment_post_ID);
1087         $user = get_userdata( $post->post_author );
1088         // Send to the administration and to the post author if the author can modify the comment.
1089         $email_to = array( get_option('admin_email') );
1090         if ( user_can($user->ID, 'edit_comment', $comment_id) && !empty($user->user_email) && ( get_option('admin_email') != $user->user_email) )
1091                 $email_to[] = $user->user_email;
1092
1093         $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
1094         $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
1095
1096         // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1097         // we want to reverse this for the plain text arena of emails.
1098         $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1099
1100         switch ($comment->comment_type)
1101         {
1102                 case 'trackback':
1103                         $notify_message  = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1104                         $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1105                         $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1106                         $notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
1107                         $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1108                         break;
1109                 case 'pingback':
1110                         $notify_message  = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1111                         $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1112                         $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1113                         $notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
1114                         $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1115                         break;
1116                 default: //Comments
1117                         $notify_message  = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1118                         $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1119                         $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1120                         $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
1121                         $notify_message .= sprintf( __('URL    : %s'), $comment->comment_author_url ) . "\r\n";
1122                         $notify_message .= sprintf( __('Whois  : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
1123                         $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1124                         break;
1125         }
1126
1127         $notify_message .= sprintf( __('Approve it: %s'),  admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n";
1128         if ( EMPTY_TRASH_DAYS )
1129                 $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
1130         else
1131                 $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
1132         $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
1133
1134         $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
1135                 'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
1136         $notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n";
1137
1138         $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
1139         $message_headers = '';
1140
1141         $notify_message = apply_filters('comment_moderation_text', $notify_message, $comment_id);
1142         $subject = apply_filters('comment_moderation_subject', $subject, $comment_id);
1143         $message_headers = apply_filters('comment_moderation_headers', $message_headers);
1144
1145         foreach ( $email_to as $email )
1146                 @wp_mail($email, $subject, $notify_message, $message_headers);
1147
1148         return true;
1149 }
1150 endif;
1151
1152 if ( !function_exists('wp_password_change_notification') ) :
1153 /**
1154  * Notify the blog admin of a user changing password, normally via email.
1155  *
1156  * @since 2.7
1157  *
1158  * @param object $user User Object
1159  */
1160 function wp_password_change_notification(&$user) {
1161         // send a copy of password change notification to the admin
1162         // but check to see if it's the admin whose password we're changing, and skip this
1163         if ( $user->user_email != get_option('admin_email') ) {
1164                 $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
1165                 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1166                 // we want to reverse this for the plain text arena of emails.
1167                 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1168                 wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message);
1169         }
1170 }
1171 endif;
1172
1173 if ( !function_exists('wp_new_user_notification') ) :
1174 /**
1175  * Notify the blog admin of a new user, normally via email.
1176  *
1177  * @since 2.0
1178  *
1179  * @param int $user_id User ID
1180  * @param string $plaintext_pass Optional. The user's plaintext password
1181  */
1182 function wp_new_user_notification($user_id, $plaintext_pass = '') {
1183         $user = new WP_User($user_id);
1184
1185         $user_login = stripslashes($user->user_login);
1186         $user_email = stripslashes($user->user_email);
1187
1188         // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1189         // we want to reverse this for the plain text arena of emails.
1190         $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1191
1192         $message  = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
1193         $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
1194         $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";
1195
1196         @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
1197
1198         if ( empty($plaintext_pass) )
1199                 return;
1200
1201         $message  = sprintf(__('Username: %s'), $user_login) . "\r\n";
1202         $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
1203         $message .= wp_login_url() . "\r\n";
1204
1205         wp_mail($user_email, sprintf(__('[%s] Your username and password'), $blogname), $message);
1206
1207 }
1208 endif;
1209
1210 if ( !function_exists('wp_nonce_tick') ) :
1211 /**
1212  * Get the time-dependent variable for nonce creation.
1213  *
1214  * A nonce has a lifespan of two ticks. Nonces in their second tick may be
1215  * updated, e.g. by autosave.
1216  *
1217  * @since 2.5
1218  *
1219  * @return int
1220  */
1221 function wp_nonce_tick() {
1222         $nonce_life = apply_filters('nonce_life', 86400);
1223
1224         return ceil(time() / ( $nonce_life / 2 ));
1225 }
1226 endif;
1227
1228 if ( !function_exists('wp_verify_nonce') ) :
1229 /**
1230  * Verify that correct nonce was used with time limit.
1231  *
1232  * The user is given an amount of time to use the token, so therefore, since the
1233  * UID and $action remain the same, the independent variable is the time.
1234  *
1235  * @since 2.0.3
1236  *
1237  * @param string $nonce Nonce that was used in the form to verify
1238  * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
1239  * @return bool Whether the nonce check passed or failed.
1240  */
1241 function wp_verify_nonce($nonce, $action = -1) {
1242         $user = wp_get_current_user();
1243         $uid = (int) $user->ID;
1244
1245         $i = wp_nonce_tick();
1246
1247         // Nonce generated 0-12 hours ago
1248         if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce )
1249                 return 1;
1250         // Nonce generated 12-24 hours ago
1251         if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce )
1252                 return 2;
1253         // Invalid nonce
1254         return false;
1255 }
1256 endif;
1257
1258 if ( !function_exists('wp_create_nonce') ) :
1259 /**
1260  * Creates a random, one time use token.
1261  *
1262  * @since 2.0.3
1263  *
1264  * @param string|int $action Scalar value to add context to the nonce.
1265  * @return string The one use form token
1266  */
1267 function wp_create_nonce($action = -1) {
1268         $user = wp_get_current_user();
1269         $uid = (int) $user->ID;
1270
1271         $i = wp_nonce_tick();
1272
1273         return substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10);
1274 }
1275 endif;
1276
1277 if ( !function_exists('wp_salt') ) :
1278 /**
1279  * Get salt to add to hashes to help prevent attacks.
1280  *
1281  * The secret key is located in two places: the database in case the secret key
1282  * isn't defined in the second place, which is in the wp-config.php file. If you
1283  * are going to set the secret key, then you must do so in the wp-config.php
1284  * file.
1285  *
1286  * The secret key in the database is randomly generated and will be appended to
1287  * the secret key that is in wp-config.php file in some instances. It is
1288  * important to have the secret key defined or changed in wp-config.php.
1289  *
1290  * If you have installed WordPress 2.5 or later, then you will have the
1291  * SECRET_KEY defined in the wp-config.php already. You will want to change the
1292  * value in it because hackers will know what it is. If you have upgraded to
1293  * WordPress 2.5 or later version from a version before WordPress 2.5, then you
1294  * should add the constant to your wp-config.php file.
1295  *
1296  * Below is an example of how the SECRET_KEY constant is defined with a value.
1297  * You must not copy the below example and paste into your wp-config.php. If you
1298  * need an example, then you can have a
1299  * {@link https://api.wordpress.org/secret-key/1.1/ secret key created} for you.
1300  *
1301  * <code>
1302  * define('SECRET_KEY', 'mAry1HadA15|\/|b17w55w1t3asSn09w');
1303  * </code>
1304  *
1305  * Salting passwords helps against tools which has stored hashed values of
1306  * common dictionary strings. The added values makes it harder to crack if given
1307  * salt string is not weak.
1308  *
1309  * @since 2.5
1310  * @link https://api.wordpress.org/secret-key/1.1/ Create a Secret Key for wp-config.php
1311  *
1312  * @param string $scheme Authentication scheme
1313  * @return string Salt value
1314  */
1315 function wp_salt($scheme = 'auth') {
1316         global $wp_default_secret_key;
1317         $secret_key = '';
1318         if ( defined('SECRET_KEY') && ('' != SECRET_KEY) && ( $wp_default_secret_key != SECRET_KEY) )
1319                 $secret_key = SECRET_KEY;
1320
1321         if ( 'auth' == $scheme ) {
1322                 if ( defined('AUTH_KEY') && ('' != AUTH_KEY) && ( $wp_default_secret_key != AUTH_KEY) )
1323                         $secret_key = AUTH_KEY;
1324
1325                 if ( defined('AUTH_SALT') && ('' != AUTH_SALT) && ( $wp_default_secret_key != AUTH_SALT) ) {
1326                         $salt = AUTH_SALT;
1327                 } elseif ( defined('SECRET_SALT') && ('' != SECRET_SALT) && ( $wp_default_secret_key != SECRET_SALT) ) {
1328                         $salt = SECRET_SALT;
1329                 } else {
1330                         $salt = get_site_option('auth_salt');
1331                         if ( empty($salt) ) {
1332                                 $salt = wp_generate_password( 64, true, true );
1333                                 update_site_option('auth_salt', $salt);
1334                         }
1335                 }
1336         } elseif ( 'secure_auth' == $scheme ) {
1337                 if ( defined('SECURE_AUTH_KEY') && ('' != SECURE_AUTH_KEY) && ( $wp_default_secret_key != SECURE_AUTH_KEY) )
1338                         $secret_key = SECURE_AUTH_KEY;
1339
1340                 if ( defined('SECURE_AUTH_SALT') && ('' != SECURE_AUTH_SALT) && ( $wp_default_secret_key != SECURE_AUTH_SALT) ) {
1341                         $salt = SECURE_AUTH_SALT;
1342                 } else {
1343                         $salt = get_site_option('secure_auth_salt');
1344                         if ( empty($salt) ) {
1345                                 $salt = wp_generate_password( 64, true, true );
1346                                 update_site_option('secure_auth_salt', $salt);
1347                         }
1348                 }
1349         } elseif ( 'logged_in' == $scheme ) {
1350                 if ( defined('LOGGED_IN_KEY') && ('' != LOGGED_IN_KEY) && ( $wp_default_secret_key != LOGGED_IN_KEY) )
1351                         $secret_key = LOGGED_IN_KEY;
1352
1353                 if ( defined('LOGGED_IN_SALT') && ('' != LOGGED_IN_SALT) && ( $wp_default_secret_key != LOGGED_IN_SALT) ) {
1354                         $salt = LOGGED_IN_SALT;
1355                 } else {
1356                         $salt = get_site_option('logged_in_salt');
1357                         if ( empty($salt) ) {
1358                                 $salt = wp_generate_password( 64, true, true );
1359                                 update_site_option('logged_in_salt', $salt);
1360                         }
1361                 }
1362         } elseif ( 'nonce' == $scheme ) {
1363                 if ( defined('NONCE_KEY') && ('' != NONCE_KEY) && ( $wp_default_secret_key != NONCE_KEY) )
1364                         $secret_key = NONCE_KEY;
1365
1366                 if ( defined('NONCE_SALT') && ('' != NONCE_SALT) && ( $wp_default_secret_key != NONCE_SALT) ) {
1367                         $salt = NONCE_SALT;
1368                 } else {
1369                         $salt = get_site_option('nonce_salt');
1370                         if ( empty($salt) ) {
1371                                 $salt = wp_generate_password( 64, true, true );
1372                                 update_site_option('nonce_salt', $salt);
1373                         }
1374                 }
1375         } else {
1376                 // ensure each auth scheme has its own unique salt
1377                 $salt = hash_hmac('md5', $scheme, $secret_key);
1378         }
1379
1380         return apply_filters('salt', $secret_key . $salt, $scheme);
1381 }
1382 endif;
1383
1384 if ( !function_exists('wp_hash') ) :
1385 /**
1386  * Get hash of given string.
1387  *
1388  * @since 2.0.3
1389  * @uses wp_salt() Get WordPress salt
1390  *
1391  * @param string $data Plain text to hash
1392  * @return string Hash of $data
1393  */
1394 function wp_hash($data, $scheme = 'auth') {
1395         $salt = wp_salt($scheme);
1396
1397         return hash_hmac('md5', $data, $salt);
1398 }
1399 endif;
1400
1401 if ( !function_exists('wp_hash_password') ) :
1402 /**
1403  * Create a hash (encrypt) of a plain text password.
1404  *
1405  * For integration with other applications, this function can be overwritten to
1406  * instead use the other package password checking algorithm.
1407  *
1408  * @since 2.5
1409  * @global object $wp_hasher PHPass object
1410  * @uses PasswordHash::HashPassword
1411  *
1412  * @param string $password Plain text user password to hash
1413  * @return string The hash string of the password
1414  */
1415 function wp_hash_password($password) {
1416         global $wp_hasher;
1417
1418         if ( empty($wp_hasher) ) {
1419                 require_once( ABSPATH . 'wp-includes/class-phpass.php');
1420                 // By default, use the portable hash from phpass
1421                 $wp_hasher = new PasswordHash(8, TRUE);
1422         }
1423
1424         return $wp_hasher->HashPassword($password);
1425 }
1426 endif;
1427
1428 if ( !function_exists('wp_check_password') ) :
1429 /**
1430  * Checks the plaintext password against the encrypted Password.
1431  *
1432  * Maintains compatibility between old version and the new cookie authentication
1433  * protocol using PHPass library. The $hash parameter is the encrypted password
1434  * and the function compares the plain text password when encrypted similarly
1435  * against the already encrypted password to see if they match.
1436  *
1437  * For integration with other applications, this function can be overwritten to
1438  * instead use the other package password checking algorithm.
1439  *
1440  * @since 2.5
1441  * @global object $wp_hasher PHPass object used for checking the password
1442  *      against the $hash + $password
1443  * @uses PasswordHash::CheckPassword
1444  *
1445  * @param string $password Plaintext user's password
1446  * @param string $hash Hash of the user's password to check against.
1447  * @return bool False, if the $password does not match the hashed password
1448  */
1449 function wp_check_password($password, $hash, $user_id = '') {
1450         global $wp_hasher;
1451
1452         // If the hash is still md5...
1453         if ( strlen($hash) <= 32 ) {
1454                 $check = ( $hash == md5($password) );
1455                 if ( $check && $user_id ) {
1456                         // Rehash using new hash.
1457                         wp_set_password($password, $user_id);
1458                         $hash = wp_hash_password($password);
1459                 }
1460
1461                 return apply_filters('check_password', $check, $password, $hash, $user_id);
1462         }
1463
1464         // If the stored hash is longer than an MD5, presume the
1465         // new style phpass portable hash.
1466         if ( empty($wp_hasher) ) {
1467                 require_once( ABSPATH . 'wp-includes/class-phpass.php');
1468                 // By default, use the portable hash from phpass
1469                 $wp_hasher = new PasswordHash(8, TRUE);
1470         }
1471
1472         $check = $wp_hasher->CheckPassword($password, $hash);
1473
1474         return apply_filters('check_password', $check, $password, $hash, $user_id);
1475 }
1476 endif;
1477
1478 if ( !function_exists('wp_generate_password') ) :
1479 /**
1480  * Generates a random password drawn from the defined set of characters.
1481  *
1482  * @since 2.5
1483  *
1484  * @param int $length The length of password to generate
1485  * @param bool $special_chars Whether to include standard special characters. Default true.
1486  * @param bool $extra_special_chars Whether to include other special characters. Used when
1487  *   generating secret keys and salts. Default false.
1488  * @return string The random password
1489  **/
1490 function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
1491         $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
1492         if ( $special_chars )
1493                 $chars .= '!@#$%^&*()';
1494         if ( $extra_special_chars )
1495                 $chars .= '-_ []{}<>~`+=,.;:/?|';
1496
1497         $password = '';
1498         for ( $i = 0; $i < $length; $i++ ) {
1499                 $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
1500         }
1501
1502         // random_password filter was previously in random_password function which was deprecated
1503         return apply_filters('random_password', $password);
1504 }
1505 endif;
1506
1507 if ( !function_exists('wp_rand') ) :
1508  /**
1509  * Generates a random number
1510  *
1511  * @since 2.6.2
1512  *
1513  * @param int $min Lower limit for the generated number (optional, default is 0)
1514  * @param int $max Upper limit for the generated number (optional, default is 4294967295)
1515  * @return int A random number between min and max
1516  */
1517 function wp_rand( $min = 0, $max = 0 ) {
1518         global $rnd_value;
1519
1520         // Reset $rnd_value after 14 uses
1521         // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
1522         if ( strlen($rnd_value) < 8 ) {
1523                 if ( defined( 'WP_SETUP_CONFIG' ) )
1524                         static $seed = '';
1525                 else
1526                         $seed = get_transient('random_seed');
1527                 $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
1528                 $rnd_value .= sha1($rnd_value);
1529                 $rnd_value .= sha1($rnd_value . $seed);
1530                 $seed = md5($seed . $rnd_value);
1531                 if ( ! defined( 'WP_SETUP_CONFIG' ) )
1532                         set_transient('random_seed', $seed);
1533         }
1534
1535         // Take the first 8 digits for our value
1536         $value = substr($rnd_value, 0, 8);
1537
1538         // Strip the first eight, leaving the remainder for the next call to wp_rand().
1539         $rnd_value = substr($rnd_value, 8);
1540
1541         $value = abs(hexdec($value));
1542
1543         // Reduce the value to be within the min - max range
1544         // 4294967295 = 0xffffffff = max random number
1545         if ( $max != 0 )
1546                 $value = $min + (($max - $min + 1) * ($value / (4294967295 + 1)));
1547
1548         return abs(intval($value));
1549 }
1550 endif;
1551
1552 if ( !function_exists('wp_set_password') ) :
1553 /**
1554  * Updates the user's password with a new encrypted one.
1555  *
1556  * For integration with other applications, this function can be overwritten to
1557  * instead use the other package password checking algorithm.
1558  *
1559  * @since 2.5
1560  * @uses $wpdb WordPress database object for queries
1561  * @uses wp_hash_password() Used to encrypt the user's password before passing to the database
1562  *
1563  * @param string $password The plaintext new user password
1564  * @param int $user_id User ID
1565  */
1566 function wp_set_password( $password, $user_id ) {
1567         global $wpdb;
1568
1569         $hash = wp_hash_password($password);
1570         $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
1571
1572         wp_cache_delete($user_id, 'users');
1573 }
1574 endif;
1575
1576 if ( !function_exists( 'get_avatar' ) ) :
1577 /**
1578  * Retrieve the avatar for a user who provided a user ID or email address.
1579  *
1580  * @since 2.5
1581  * @param int|string|object $id_or_email A user ID,  email address, or comment object
1582  * @param int $size Size of the avatar image
1583  * @param string $default URL to a default image to use if no avatar is available
1584  * @param string $alt Alternate text to use in image tag. Defaults to blank
1585  * @return string <img> tag for the user's avatar
1586 */
1587 function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
1588         if ( ! get_option('show_avatars') )
1589                 return false;
1590
1591         if ( false === $alt)
1592                 $safe_alt = '';
1593         else
1594                 $safe_alt = esc_attr( $alt );
1595
1596         if ( !is_numeric($size) )
1597                 $size = '96';
1598
1599         $email = '';
1600         if ( is_numeric($id_or_email) ) {
1601                 $id = (int) $id_or_email;
1602                 $user = get_userdata($id);
1603                 if ( $user )
1604                         $email = $user->user_email;
1605         } elseif ( is_object($id_or_email) ) {
1606                 // No avatar for pingbacks or trackbacks
1607                 $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
1608                 if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
1609                         return false;
1610
1611                 if ( !empty($id_or_email->user_id) ) {
1612                         $id = (int) $id_or_email->user_id;
1613                         $user = get_userdata($id);
1614                         if ( $user)
1615                                 $email = $user->user_email;
1616                 } elseif ( !empty($id_or_email->comment_author_email) ) {
1617                         $email = $id_or_email->comment_author_email;
1618                 }
1619         } else {
1620                 $email = $id_or_email;
1621         }
1622
1623         if ( empty($default) ) {
1624                 $avatar_default = get_option('avatar_default');
1625                 if ( empty($avatar_default) )
1626                         $default = 'mystery';
1627                 else
1628                         $default = $avatar_default;
1629         }
1630
1631         if ( !empty($email) )
1632                 $email_hash = md5( strtolower( $email ) );
1633
1634         if ( is_ssl() ) {
1635                 $host = 'https://secure.gravatar.com';
1636         } else {
1637                 if ( !empty($email) )
1638                         $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) );
1639                 else
1640                         $host = 'http://0.gravatar.com';
1641         }
1642
1643         if ( 'mystery' == $default )
1644                 $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
1645         elseif ( 'blank' == $default )
1646                 $default = includes_url('images/blank.gif');
1647         elseif ( !empty($email) && 'gravatar_default' == $default )
1648                 $default = '';
1649         elseif ( 'gravatar_default' == $default )
1650                 $default = "$host/avatar/s={$size}";
1651         elseif ( empty($email) )
1652                 $default = "$host/avatar/?d=$default&amp;s={$size}";
1653         elseif ( strpos($default, 'http://') === 0 )
1654                 $default = add_query_arg( 's', $size, $default );
1655
1656         if ( !empty($email) ) {
1657                 $out = "$host/avatar/";
1658                 $out .= $email_hash;
1659                 $out .= '?s='.$size;
1660                 $out .= '&amp;d=' . urlencode( $default );
1661
1662                 $rating = get_option('avatar_rating');
1663                 if ( !empty( $rating ) )
1664                         $out .= "&amp;r={$rating}";
1665
1666                 $avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
1667         } else {
1668                 $avatar = "<img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
1669         }
1670
1671         return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt);
1672 }
1673 endif;
1674
1675 if ( !function_exists( 'wp_text_diff' ) ) :
1676 /**
1677  * Displays a human readable HTML representation of the difference between two strings.
1678  *
1679  * The Diff is available for getting the changes between versions. The output is
1680  * HTML, so the primary use is for displaying the changes. If the two strings
1681  * are equivalent, then an empty string will be returned.
1682  *
1683  * The arguments supported and can be changed are listed below.
1684  *
1685  * 'title' : Default is an empty string. Titles the diff in a manner compatible
1686  *              with the output.
1687  * 'title_left' : Default is an empty string. Change the HTML to the left of the
1688  *              title.
1689  * 'title_right' : Default is an empty string. Change the HTML to the right of
1690  *              the title.
1691  *
1692  * @since 2.6
1693  * @see wp_parse_args() Used to change defaults to user defined settings.
1694  * @uses Text_Diff
1695  * @uses WP_Text_Diff_Renderer_Table
1696  *
1697  * @param string $left_string "old" (left) version of string
1698  * @param string $right_string "new" (right) version of string
1699  * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
1700  * @return string Empty string if strings are equivalent or HTML with differences.
1701  */
1702 function wp_text_diff( $left_string, $right_string, $args = null ) {
1703         $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
1704         $args = wp_parse_args( $args, $defaults );
1705
1706         if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
1707                 require( ABSPATH . WPINC . '/wp-diff.php' );
1708
1709         $left_string  = normalize_whitespace($left_string);
1710         $right_string = normalize_whitespace($right_string);
1711
1712         $left_lines  = split("\n", $left_string);
1713         $right_lines = split("\n", $right_string);
1714
1715         $text_diff = new Text_Diff($left_lines, $right_lines);
1716         $renderer  = new WP_Text_Diff_Renderer_Table();
1717         $diff = $renderer->render($text_diff);
1718
1719         if ( !$diff )
1720                 return '';
1721
1722         $r  = "<table class='diff'>\n";
1723         $r .= "<col class='ltype' /><col class='content' /><col class='ltype' /><col class='content' />";
1724
1725         if ( $args['title'] || $args['title_left'] || $args['title_right'] )
1726                 $r .= "<thead>";
1727         if ( $args['title'] )
1728                 $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
1729         if ( $args['title_left'] || $args['title_right'] ) {
1730                 $r .= "<tr class='diff-sub-title'>\n";
1731                 $r .= "\t<td></td><th>$args[title_left]</th>\n";
1732                 $r .= "\t<td></td><th>$args[title_right]</th>\n";
1733                 $r .= "</tr>\n";
1734         }
1735         if ( $args['title'] || $args['title_left'] || $args['title_right'] )
1736                 $r .= "</thead>\n";
1737
1738         $r .= "<tbody>\n$diff\n</tbody>\n";
1739         $r .= "</table>";
1740
1741         return $r;
1742 }
1743 endif;