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