· 10 years ago · Dec 11, 2015, 02:57 PM
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
9if ( !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 */
27function wp_set_current_user($id, $name = '') {
28 global $current_user;
29
30 if ( isset( $current_user ) && ( $current_user instanceof WP_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}
41endif;
42
43if ( !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 */
51function wp_get_current_user() {
52 global $current_user;
53
54 get_currentuserinfo();
55
56 return $current_user;
57}
58endif;
59
60if ( !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 */
74function get_currentuserinfo() {
75 global $current_user;
76
77 if ( ! empty( $current_user ) ) {
78 if ( $current_user instanceof WP_User )
79 return;
80
81 // Upgrade stdClass to WP_User
82 if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
83 $cur_id = $current_user->ID;
84 $current_user = null;
85 wp_set_current_user( $cur_id );
86 return;
87 }
88
89 // $current_user has a junk value. Force to WP_User with ID 0.
90 $current_user = null;
91 wp_set_current_user( 0 );
92 return false;
93 }
94
95 if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
96 wp_set_current_user( 0 );
97 return false;
98 }
99
100 if ( ! $user = wp_validate_auth_cookie() ) {
101 if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) || !$user = wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' ) ) {
102 wp_set_current_user( 0 );
103 return false;
104 }
105 }
106
107 wp_set_current_user( $user );
108}
109endif;
110
111if ( !function_exists('get_userdata') ) :
112/**
113 * Retrieve user info by user ID.
114 *
115 * @since 0.71
116 *
117 * @param int $user_id User ID
118 * @return bool|object False on failure, WP_User object on success
119 */
120function get_userdata( $user_id ) {
121 return get_user_by( 'id', $user_id );
122}
123endif;
124
125if ( !function_exists('get_user_by') ) :
126/**
127 * Retrieve user info by a given field
128 *
129 * @since 2.8.0
130 *
131 * @param string $field The field to retrieve the user with. id | slug | email | login
132 * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
133 * @return bool|object False on failure, WP_User object on success
134 */
135function get_user_by( $field, $value ) {
136 $userdata = WP_User::get_data_by( $field, $value );
137
138 if ( !$userdata )
139 return false;
140
141 $user = new WP_User;
142 $user->init( $userdata );
143
144 return $user;
145}
146endif;
147
148if ( !function_exists('cache_users') ) :
149/**
150 * Retrieve info for user lists to prevent multiple queries by get_userdata()
151 *
152 * @since 3.0.0
153 *
154 * @param array $user_ids User ID numbers list
155 */
156function cache_users( $user_ids ) {
157 global $wpdb;
158
159 $clean = _get_non_cached_ids( $user_ids, 'users' );
160
161 if ( empty( $clean ) )
162 return;
163
164 $list = implode( ',', $clean );
165
166 $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
167
168 $ids = array();
169 foreach ( $users as $user ) {
170 update_user_caches( $user );
171 $ids[] = $user->ID;
172 }
173 update_meta_cache( 'user', $ids );
174}
175endif;
176
177if ( !function_exists( 'wp_mail' ) ) :
178/**
179 * Send mail, similar to PHP's mail
180 *
181 * A true return value does not automatically mean that the user received the
182 * email successfully. It just only means that the method used was able to
183 * process the request without any errors.
184 *
185 * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
186 * creating a from address like 'Name <email@address.com>' when both are set. If
187 * just 'wp_mail_from' is set, then just the email address will be used with no
188 * name.
189 *
190 * The default content type is 'text/plain' which does not allow using HTML.
191 * However, you can set the content type of the email by using the
192 * 'wp_mail_content_type' filter.
193 *
194 * The default charset is based on the charset used on the blog. The charset can
195 * be set using the 'wp_mail_charset' filter.
196 *
197 * @since 1.2.1
198 * @uses apply_filters() Calls 'wp_mail' hook on an array of all of the parameters.
199 * @uses apply_filters() Calls 'wp_mail_from' hook to get the from email address.
200 * @uses apply_filters() Calls 'wp_mail_from_name' hook to get the from address name.
201 * @uses apply_filters() Calls 'wp_mail_content_type' hook to get the email content type.
202 * @uses apply_filters() Calls 'wp_mail_charset' hook to get the email charset
203 * @uses do_action_ref_array() Calls 'phpmailer_init' hook on the reference to
204 * phpmailer object.
205 * @uses PHPMailer
206 *
207 * @param string|array $to Array or comma-separated list of email addresses to send message.
208 * @param string $subject Email subject
209 * @param string $message Message contents
210 * @param string|array $headers Optional. Additional headers.
211 * @param string|array $attachments Optional. Files to attach.
212 * @return bool Whether the email contents were sent successfully.
213 */
214function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
215 // Compact the input, apply the filters, and extract them back out
216 extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
217
218 if ( !is_array($attachments) )
219 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
220
221 global $phpmailer;
222
223 // (Re)create it, if it's gone missing
224 if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) {
225 require_once ABSPATH . WPINC . '/class-phpmailer.php';
226 require_once ABSPATH . WPINC . '/class-smtp.php';
227 $phpmailer = new PHPMailer( true );
228 }
229
230 // Headers
231 if ( empty( $headers ) ) {
232 $headers = array();
233 } else {
234 if ( !is_array( $headers ) ) {
235 // Explode the headers out, so this function can take both
236 // string headers and an array of headers.
237 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
238 } else {
239 $tempheaders = $headers;
240 }
241 $headers = array();
242 $cc = array();
243 $bcc = array();
244
245 // If it's actually got contents
246 if ( !empty( $tempheaders ) ) {
247 // Iterate through the raw headers
248 foreach ( (array) $tempheaders as $header ) {
249 if ( strpos($header, ':') === false ) {
250 if ( false !== stripos( $header, 'boundary=' ) ) {
251 $parts = preg_split('/boundary=/i', trim( $header ) );
252 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
253 }
254 continue;
255 }
256 // Explode them out
257 list( $name, $content ) = explode( ':', trim( $header ), 2 );
258
259 // Cleanup crew
260 $name = trim( $name );
261 $content = trim( $content );
262
263 switch ( strtolower( $name ) ) {
264 // Mainly for legacy -- process a From: header if it's there
265 case 'from':
266 if ( strpos($content, '<' ) !== false ) {
267 // So... making my life hard again?
268 $from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
269 $from_name = str_replace( '"', '', $from_name );
270 $from_name = trim( $from_name );
271
272 $from_email = substr( $content, strpos( $content, '<' ) + 1 );
273 $from_email = str_replace( '>', '', $from_email );
274 $from_email = trim( $from_email );
275 } else {
276 $from_email = trim( $content );
277 }
278 break;
279 case 'content-type':
280 if ( strpos( $content, ';' ) !== false ) {
281 list( $type, $charset ) = explode( ';', $content );
282 $content_type = trim( $type );
283 if ( false !== stripos( $charset, 'charset=' ) ) {
284 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) );
285 } elseif ( false !== stripos( $charset, 'boundary=' ) ) {
286 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) );
287 $charset = '';
288 }
289 } else {
290 $content_type = trim( $content );
291 }
292 break;
293 case 'cc':
294 $cc = array_merge( (array) $cc, explode( ',', $content ) );
295 break;
296 case 'bcc':
297 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
298 break;
299 default:
300 // Add it to our grand headers array
301 $headers[trim( $name )] = trim( $content );
302 break;
303 }
304 }
305 }
306 }
307
308 // Empty out the values that may be set
309 $phpmailer->ClearAddresses();
310 $phpmailer->ClearAllRecipients();
311 $phpmailer->ClearAttachments();
312 $phpmailer->ClearBCCs();
313 $phpmailer->ClearCCs();
314 $phpmailer->ClearCustomHeaders();
315 $phpmailer->ClearReplyTos();
316
317 // From email and name
318 // If we don't have a name from the input headers
319 if ( !isset( $from_name ) )
320 $from_name = 'WordPress';
321
322 /* If we don't have an email from the input headers default to wordpress@$sitename
323 * Some hosts will block outgoing mail from this address if it doesn't exist but
324 * there's no easy alternative. Defaulting to admin_email might appear to be another
325 * option but some hosts may refuse to relay mail from an unknown domain. See
326 * http://trac.wordpress.org/ticket/5007.
327 */
328
329 if ( !isset( $from_email ) ) {
330 // Get the site domain and get rid of www.
331 $sitename = strtolower( $_SERVER['SERVER_NAME'] );
332 if ( substr( $sitename, 0, 4 ) == 'www.' ) {
333 $sitename = substr( $sitename, 4 );
334 }
335
336 $from_email = 'wordpress@' . $sitename;
337 }
338
339 // Plugin authors can override the potentially troublesome default
340 $phpmailer->From = apply_filters( 'wp_mail_from' , $from_email );
341 $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
342
343 // Set destination addresses
344 if ( !is_array( $to ) )
345 $to = explode( ',', $to );
346
347 foreach ( (array) $to as $recipient ) {
348 try {
349 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
350 $recipient_name = '';
351 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
352 if ( count( $matches ) == 3 ) {
353 $recipient_name = $matches[1];
354 $recipient = $matches[2];
355 }
356 }
357 $phpmailer->AddAddress( $recipient, $recipient_name);
358 } catch ( phpmailerException $e ) {
359 continue;
360 }
361 }
362
363 // Set mail's subject and body
364 $phpmailer->Subject = $subject;
365 $phpmailer->Body = $message;
366
367 // Add any CC and BCC recipients
368 if ( !empty( $cc ) ) {
369 foreach ( (array) $cc as $recipient ) {
370 try {
371 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
372 $recipient_name = '';
373 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
374 if ( count( $matches ) == 3 ) {
375 $recipient_name = $matches[1];
376 $recipient = $matches[2];
377 }
378 }
379 $phpmailer->AddCc( $recipient, $recipient_name );
380 } catch ( phpmailerException $e ) {
381 continue;
382 }
383 }
384 }
385
386 if ( !empty( $bcc ) ) {
387 foreach ( (array) $bcc as $recipient) {
388 try {
389 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
390 $recipient_name = '';
391 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
392 if ( count( $matches ) == 3 ) {
393 $recipient_name = $matches[1];
394 $recipient = $matches[2];
395 }
396 }
397 $phpmailer->AddBcc( $recipient, $recipient_name );
398 } catch ( phpmailerException $e ) {
399 continue;
400 }
401 }
402 }
403
404 // Set to use PHP's mail()
405 $phpmailer->IsMail();
406
407 // Set Content-Type and charset
408 // If we don't have a content-type from the input headers
409 if ( !isset( $content_type ) )
410 $content_type = 'text/plain';
411
412 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
413
414 $phpmailer->ContentType = $content_type;
415
416 // Set whether it's plaintext, depending on $content_type
417 if ( 'text/html' == $content_type )
418 $phpmailer->IsHTML( true );
419
420 // If we don't have a charset from the input headers
421 if ( !isset( $charset ) )
422 $charset = get_bloginfo( 'charset' );
423
424 // Set the content-type and charset
425 $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
426
427 // Set custom headers
428 if ( !empty( $headers ) ) {
429 foreach( (array) $headers as $name => $content ) {
430 $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
431 }
432
433 if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
434 $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
435 }
436
437 if ( !empty( $attachments ) ) {
438 foreach ( $attachments as $attachment ) {
439 try {
440 $phpmailer->AddAttachment($attachment);
441 } catch ( phpmailerException $e ) {
442 continue;
443 }
444 }
445 }
446
447 do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
448
449 // Send!
450 try {
451 $phpmailer->Send();
452 } catch ( phpmailerException $e ) {
453 return false;
454 }
455
456 return true;
457}
458endif;
459
460if ( !function_exists('wp_authenticate') ) :
461/**
462 * Checks a user's login information and logs them in if it checks out.
463 *
464 * @since 2.5.0
465 *
466 * @param string $username User's username
467 * @param string $password User's password
468 * @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object.
469 */
470function wp_authenticate($username, $password) {
471 $username = sanitize_user($username);
472 $password = trim($password);
473
474 $user = apply_filters('authenticate', null, $username, $password);
475
476 if ( $user == null ) {
477 // TODO what should the error message be? (Or would these even happen?)
478 // Only needed if all authentication handlers fail to return anything.
479 $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
480 }
481
482 $ignore_codes = array('empty_username', 'empty_password');
483
484 if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
485 do_action('wp_login_failed', $username);
486 }
487
488 return $user;
489}
490endif;
491
492if ( !function_exists('wp_logout') ) :
493/**
494 * Log the current user out.
495 *
496 * @since 2.5.0
497 */
498function wp_logout() {
499 wp_clear_auth_cookie();
500 do_action('wp_logout');
501}
502endif;
503
504if ( !function_exists('wp_validate_auth_cookie') ) :
505/**
506 * Validates authentication cookie.
507 *
508 * The checks include making sure that the authentication cookie is set and
509 * pulling in the contents (if $cookie is not used).
510 *
511 * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
512 * should be and compares the two.
513 *
514 * @since 2.5
515 *
516 * @param string $cookie Optional. If used, will validate contents instead of cookie's
517 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
518 * @return bool|int False if invalid cookie, User ID if valid.
519 */
520function wp_validate_auth_cookie($cookie = '', $scheme = '') {
521 if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
522 do_action('auth_cookie_malformed', $cookie, $scheme);
523 return false;
524 }
525
526 extract($cookie_elements, EXTR_OVERWRITE);
527
528 $expired = $expiration;
529
530 // Allow a grace period for POST and AJAX requests
531 if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] )
532 $expired += 3600;
533
534 // Quick check to see if an honest cookie has expired
535 if ( $expired < time() ) {
536 do_action('auth_cookie_expired', $cookie_elements);
537 return false;
538 }
539
540 $user = get_user_by('login', $username);
541 if ( ! $user ) {
542 do_action('auth_cookie_bad_username', $cookie_elements);
543 return false;
544 }
545
546 $pass_frag = substr($user->user_pass, 8, 4);
547
548 $key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme);
549 $hash = hash_hmac('md5', $username . '|' . $expiration, $key);
550
551 if ( $hmac != $hash ) {
552 do_action('auth_cookie_bad_hash', $cookie_elements);
553 return false;
554 }
555
556 if ( $expiration < time() ) // AJAX/POST grace period set above
557 $GLOBALS['login_grace_period'] = 1;
558
559 do_action('auth_cookie_valid', $cookie_elements, $user);
560
561 return $user->ID;
562}
563endif;
564
565if ( !function_exists('wp_generate_auth_cookie') ) :
566/**
567 * Generate authentication cookie contents.
568 *
569 * @since 2.5
570 * @uses apply_filters() Calls 'auth_cookie' hook on $cookie contents, User ID
571 * and expiration of cookie.
572 *
573 * @param int $user_id User ID
574 * @param int $expiration Cookie expiration in seconds
575 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
576 * @return string Authentication cookie contents
577 */
578function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') {
579 $user = get_userdata($user_id);
580
581 $pass_frag = substr($user->user_pass, 8, 4);
582
583 $key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme);
584 $hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key);
585
586 $cookie = $user->user_login . '|' . $expiration . '|' . $hash;
587
588 return apply_filters('auth_cookie', $cookie, $user_id, $expiration, $scheme);
589}
590endif;
591
592if ( !function_exists('wp_parse_auth_cookie') ) :
593/**
594 * Parse a cookie into its components
595 *
596 * @since 2.7
597 *
598 * @param string $cookie
599 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
600 * @return array Authentication cookie components
601 */
602function wp_parse_auth_cookie($cookie = '', $scheme = '') {
603 if ( empty($cookie) ) {
604 switch ($scheme){
605 case 'auth':
606 $cookie_name = AUTH_COOKIE;
607 break;
608 case 'secure_auth':
609 $cookie_name = SECURE_AUTH_COOKIE;
610 break;
611 case "logged_in":
612 $cookie_name = LOGGED_IN_COOKIE;
613 break;
614 default:
615 if ( is_ssl() ) {
616 $cookie_name = SECURE_AUTH_COOKIE;
617 $scheme = 'secure_auth';
618 } else {
619 $cookie_name = AUTH_COOKIE;
620 $scheme = 'auth';
621 }
622 }
623
624 if ( empty($_COOKIE[$cookie_name]) )
625 return false;
626 $cookie = $_COOKIE[$cookie_name];
627 }
628
629 $cookie_elements = explode('|', $cookie);
630 if ( count($cookie_elements) != 3 )
631 return false;
632
633 list($username, $expiration, $hmac) = $cookie_elements;
634
635 return compact('username', 'expiration', 'hmac', 'scheme');
636}
637endif;
638
639if ( !function_exists('wp_set_auth_cookie') ) :
640/**
641 * Sets the authentication cookies based User ID.
642 *
643 * The $remember parameter increases the time that the cookie will be kept. The
644 * default the cookie is kept without remembering is two days. When $remember is
645 * set, the cookies will be kept for 14 days or two weeks.
646 *
647 * @since 2.5
648 *
649 * @param int $user_id User ID
650 * @param bool $remember Whether to remember the user
651 */
652function wp_set_auth_cookie($user_id, $remember = false, $secure = '') {
653 if ( $remember ) {
654 $expiration = $expire = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, $remember);
655 } else {
656 $expiration = time() + apply_filters('auth_cookie_expiration', 172800, $user_id, $remember);
657 $expire = 0;
658 }
659
660 if ( '' === $secure )
661 $secure = is_ssl();
662
663 $secure = apply_filters('secure_auth_cookie', $secure, $user_id);
664 $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', false, $user_id, $secure);
665
666 if ( $secure ) {
667 $auth_cookie_name = SECURE_AUTH_COOKIE;
668 $scheme = 'secure_auth';
669 } else {
670 $auth_cookie_name = AUTH_COOKIE;
671 $scheme = 'auth';
672 }
673
674 $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme);
675 $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
676
677 do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme);
678 do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in');
679
680 setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
681 setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
682 setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
683 if ( COOKIEPATH != SITECOOKIEPATH )
684 setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
685}
686endif;
687
688if ( !function_exists('wp_clear_auth_cookie') ) :
689/**
690 * Removes all of the cookies associated with authentication.
691 *
692 * @since 2.5
693 */
694function wp_clear_auth_cookie() {
695 do_action('clear_auth_cookie');
696
697 setcookie(AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
698 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
699 setcookie(AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
700 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
701 setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
702 setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
703
704 // Old cookies
705 setcookie(AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
706 setcookie(AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
707 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
708 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
709
710 // Even older cookies
711 setcookie(USER_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
712 setcookie(PASS_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
713 setcookie(USER_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
714 setcookie(PASS_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
715}
716endif;
717
718if ( !function_exists('is_user_logged_in') ) :
719/**
720 * Checks if the current visitor is a logged in user.
721 *
722 * @since 2.0.0
723 *
724 * @return bool True if user is logged in, false if not logged in.
725 */
726function is_user_logged_in() {
727 $user = wp_get_current_user();
728
729 if ( ! $user->exists() )
730 return false;
731
732 return true;
733}
734endif;
735
736if ( !function_exists('auth_redirect') ) :
737/**
738 * Checks if a user is logged in, if not it redirects them to the login page.
739 *
740 * @since 1.5
741 */
742function auth_redirect() {
743 // Checks if a user is logged in, if not redirects them to the login page
744
745 $secure = ( is_ssl() || force_ssl_admin() );
746
747 $secure = apply_filters('secure_auth_redirect', $secure);
748
749 // If https is required and request is http, redirect
750 if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
751 if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
752 wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
753 exit();
754 } else {
755 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
756 exit();
757 }
758 }
759
760 if ( is_user_admin() )
761 $scheme = 'logged_in';
762 else
763 $scheme = apply_filters( 'auth_redirect_scheme', '' );
764
765 if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) {
766 do_action('auth_redirect', $user_id);
767
768 // If the user wants ssl but the session is not ssl, redirect.
769 if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
770 if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
771 wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
772 exit();
773 } else {
774 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
775 exit();
776 }
777 }
778
779 return; // The cookie is good so we're done
780 }
781
782 // The cookie is no good so force login
783 nocache_headers();
784
785 if ( is_ssl() )
786 $proto = 'https://';
787 else
788 $proto = 'http://';
789
790 $redirect = ( strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ) ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
791
792 $login_url = wp_login_url($redirect, true);
793
794 wp_redirect($login_url);
795 exit();
796}
797endif;
798
799if ( !function_exists('check_admin_referer') ) :
800/**
801 * Makes sure that a user was referred from another admin page.
802 *
803 * To avoid security exploits.
804 *
805 * @since 1.2.0
806 * @uses do_action() Calls 'check_admin_referer' on $action.
807 *
808 * @param string $action Action nonce
809 * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
810 */
811function check_admin_referer($action = -1, $query_arg = '_wpnonce') {
812 if ( -1 == $action )
813 _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
814
815 $adminurl = strtolower(admin_url());
816 $referer = strtolower(wp_get_referer());
817 $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
818 if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
819 wp_nonce_ays($action);
820 die();
821 }
822 do_action('check_admin_referer', $action, $result);
823 return $result;
824}endif;
825
826if ( !function_exists('check_ajax_referer') ) :
827/**
828 * Verifies the AJAX request to prevent processing requests external of the blog.
829 *
830 * @since 2.0.3
831 *
832 * @param string $action Action nonce
833 * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
834 */
835function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
836 if ( $query_arg )
837 $nonce = $_REQUEST[$query_arg];
838 else
839 $nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce'];
840
841 $result = wp_verify_nonce( $nonce, $action );
842
843 if ( $die && false == $result ) {
844 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
845 wp_die( -1 );
846 else
847 die( '-1' );
848 }
849
850 do_action('check_ajax_referer', $action, $result);
851
852 return $result;
853}
854endif;
855
856if ( !function_exists('wp_redirect') ) :
857/**
858 * Redirects to another page.
859 *
860 * @since 1.5.1
861 * @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
862 *
863 * @param string $location The path to redirect to
864 * @param int $status Status code to use
865 * @return bool False if $location is not set
866 */
867function wp_redirect($location, $status = 302) {
868 global $is_IIS;
869
870 $location = apply_filters('wp_redirect', $location, $status);
871 $status = apply_filters('wp_redirect_status', $status, $location);
872
873 if ( !$location ) // allows the wp_redirect filter to cancel a redirect
874 return false;
875
876 $location = wp_sanitize_redirect($location);
877
878 if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
879 status_header($status); // This causes problems on IIS and some FastCGI setups
880
881 header("Location: $location", true, $status);
882}
883endif;
884
885if ( !function_exists('wp_sanitize_redirect') ) :
886/**
887 * Sanitizes a URL for use in a redirect.
888 *
889 * @since 2.3
890 *
891 * @return string redirect-sanitized URL
892 **/
893function wp_sanitize_redirect($location) {
894 $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location);
895 $location = wp_kses_no_null($location);
896
897 // remove %0d and %0a from location
898 $strip = array('%0d', '%0a', '%0D', '%0A');
899 $location = _deep_replace($strip, $location);
900 return $location;
901}
902endif;
903
904if ( !function_exists('wp_safe_redirect') ) :
905/**
906 * Performs a safe (local) redirect, using wp_redirect().
907 *
908 * Checks whether the $location is using an allowed host, if it has an absolute
909 * path. A plugin can therefore set or remove allowed host(s) to or from the
910 * list.
911 *
912 * If the host is not allowed, then the redirect is to wp-admin on the siteurl
913 * instead. This prevents malicious redirects which redirect to another host,
914 * but only used in a few places.
915 *
916 * @since 2.3
917 * @uses wp_validate_redirect() To validate the redirect is to an allowed host.
918 *
919 * @return void Does not return anything
920 **/
921function wp_safe_redirect($location, $status = 302) {
922
923 // Need to look at the URL the way it will end up in wp_redirect()
924 $location = wp_sanitize_redirect($location);
925
926 $location = wp_validate_redirect($location, admin_url());
927
928 wp_redirect($location, $status);
929}
930endif;
931
932if ( !function_exists('wp_validate_redirect') ) :
933/**
934 * Validates a URL for use in a redirect.
935 *
936 * Checks whether the $location is using an allowed host, if it has an absolute
937 * path. A plugin can therefore set or remove allowed host(s) to or from the
938 * list.
939 *
940 * If the host is not allowed, then the redirect is to $default supplied
941 *
942 * @since 2.8.1
943 * @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing
944 * WordPress host string and $location host string.
945 *
946 * @param string $location The redirect to validate
947 * @param string $default The value to return if $location is not allowed
948 * @return string redirect-sanitized URL
949 **/
950function wp_validate_redirect($location, $default = '') {
951 // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
952 if ( substr($location, 0, 2) == '//' )
953 $location = 'http:' . $location;
954
955 // In php 5 parse_url may fail if the URL query part contains http://, bug #38143
956 $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
957
958 $lp = parse_url($test);
959
960 // Give up if malformed URL
961 if ( false === $lp )
962 return $default;
963
964 // Allow only http and https schemes. No data:, etc.
965 if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
966 return $default;
967
968 // 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.
969 if ( isset($lp['scheme']) && !isset($lp['host']) )
970 return $default;
971
972 $wpp = parse_url(home_url());
973
974 $allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '');
975
976 if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
977 $location = $default;
978
979 return $location;
980}
981endif;
982
983if ( ! function_exists('wp_notify_postauthor') ) :
984/**
985 * Notify an author of a comment/trackback/pingback to one of their posts.
986 *
987 * @since 1.0.0
988 *
989 * @param int $comment_id Comment ID
990 * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback'
991 * @return bool False if user email does not exist. True on completion.
992 */
993function wp_notify_postauthor( $comment_id, $comment_type = '' ) {
994 $comment = get_comment( $comment_id );
995 $post = get_post( $comment->comment_post_ID );
996 $author = get_userdata( $post->post_author );
997
998 // The comment was left by the author
999 if ( $comment->user_id == $post->post_author )
1000 return false;
1001
1002 // The author moderated a comment on his own post
1003 if ( $post->post_author == get_current_user_id() )
1004 return false;
1005
1006 // If there's no email to send the comment to
1007 if ( '' == $author->user_email )
1008 return false;
1009
1010 $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
1011
1012 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1013 // we want to reverse this for the plain text arena of emails.
1014 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1015
1016 if ( empty( $comment_type ) ) $comment_type = 'comment';
1017
1018 if ('comment' == $comment_type) {
1019 $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
1020 /* translators: 1: comment author, 2: author IP, 3: author domain */
1021 $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1022 $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
1023 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
1024 $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
1025 $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1026 $notify_message .= __('You can see all comments on this post here: ') . "\r\n";
1027 /* translators: 1: blog name, 2: post title */
1028 $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
1029 } elseif ('trackback' == $comment_type) {
1030 $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
1031 /* translators: 1: website name, 2: author IP, 3: author domain */
1032 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1033 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
1034 $notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1035 $notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n";
1036 /* translators: 1: blog name, 2: post title */
1037 $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
1038 } elseif ('pingback' == $comment_type) {
1039 $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
1040 /* translators: 1: comment author, 2: author IP, 3: author domain */
1041 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1042 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
1043 $notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n";
1044 $notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n";
1045 /* translators: 1: blog name, 2: post title */
1046 $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
1047 }
1048 $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
1049 $notify_message .= sprintf( __('Permalink: %s'), get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment_id ) . "\r\n";
1050 if ( EMPTY_TRASH_DAYS )
1051 $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
1052 else
1053 $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
1054 $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
1055
1056 $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
1057
1058 if ( '' == $comment->comment_author ) {
1059 $from = "From: \"$blogname\" <$wp_email>";
1060 if ( '' != $comment->comment_author_email )
1061 $reply_to = "Reply-To: $comment->comment_author_email";
1062 } else {
1063 $from = "From: \"$comment->comment_author\" <$wp_email>";
1064 if ( '' != $comment->comment_author_email )
1065 $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
1066 }
1067
1068 $message_headers = "$from\n"
1069 . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
1070
1071 if ( isset($reply_to) )
1072 $message_headers .= $reply_to . "\n";
1073
1074 $notify_message = apply_filters('comment_notification_text', $notify_message, $comment_id);
1075 $subject = apply_filters('comment_notification_subject', $subject, $comment_id);
1076 $message_headers = apply_filters('comment_notification_headers', $message_headers, $comment_id);
1077
1078 @wp_mail( $author->user_email, $subject, $notify_message, $message_headers );
1079
1080 return true;
1081}
1082endif;
1083
1084if ( !function_exists('wp_notify_moderator') ) :
1085/**
1086 * Notifies the moderator of the blog about a new comment that is awaiting approval.
1087 *
1088 * @since 1.0
1089 * @uses $wpdb
1090 *
1091 * @param int $comment_id Comment ID
1092 * @return bool Always returns true
1093 */
1094function wp_notify_moderator($comment_id) {
1095 global $wpdb;
1096
1097 if ( 0 == get_option( 'moderation_notify' ) )
1098 return true;
1099
1100 $comment = get_comment($comment_id);
1101 $post = get_post($comment->comment_post_ID);
1102 $user = get_userdata( $post->post_author );
1103 // Send to the administration and to the post author if the author can modify the comment.
1104 $email_to = array( get_option('admin_email') );
1105 if ( user_can($user->ID, 'edit_comment', $comment_id) && !empty($user->user_email) && ( get_option('admin_email') != $user->user_email) )
1106 $email_to[] = $user->user_email;
1107
1108 $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
1109 $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
1110
1111 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1112 // we want to reverse this for the plain text arena of emails.
1113 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1114
1115 switch ($comment->comment_type)
1116 {
1117 case 'trackback':
1118 $notify_message = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1119 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1120 $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1121 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
1122 $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1123 break;
1124 case 'pingback':
1125 $notify_message = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1126 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1127 $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1128 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
1129 $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1130 break;
1131 default: //Comments
1132 $notify_message = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
1133 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
1134 $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
1135 $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
1136 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
1137 $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
1138 $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
1139 break;
1140 }
1141
1142 $notify_message .= sprintf( __('Approve it: %s'), admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n";
1143 if ( EMPTY_TRASH_DAYS )
1144 $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
1145 else
1146 $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
1147 $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
1148
1149 $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
1150 'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
1151 $notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n";
1152
1153 $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
1154 $message_headers = '';
1155
1156 $notify_message = apply_filters('comment_moderation_text', $notify_message, $comment_id);
1157 $subject = apply_filters('comment_moderation_subject', $subject, $comment_id);
1158 $message_headers = apply_filters('comment_moderation_headers', $message_headers);
1159
1160 foreach ( $email_to as $email )
1161 @wp_mail($email, $subject, $notify_message, $message_headers);
1162
1163 return true;
1164}
1165endif;
1166
1167if ( !function_exists('wp_password_change_notification') ) :
1168/**
1169 * Notify the blog admin of a user changing password, normally via email.
1170 *
1171 * @since 2.7
1172 *
1173 * @param object $user User Object
1174 */
1175function wp_password_change_notification(&$user) {
1176 // send a copy of password change notification to the admin
1177 // but check to see if it's the admin whose password we're changing, and skip this
1178 if ( $user->user_email != get_option('admin_email') ) {
1179 $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
1180 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1181 // we want to reverse this for the plain text arena of emails.
1182 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1183 wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message);
1184 }
1185}
1186endif;
1187
1188if ( !function_exists('wp_new_user_notification') ) :
1189/**
1190 * Notify the blog admin of a new user, normally via email.
1191 *
1192 * @since 2.0
1193 *
1194 * @param int $user_id User ID
1195 * @param string $plaintext_pass Optional. The user's plaintext password
1196 */
1197function wp_new_user_notification($user_id, $plaintext_pass = '') {
1198 $user = new WP_User($user_id);
1199
1200 $user_login = stripslashes($user->user_login);
1201 $user_email = stripslashes($user->user_email);
1202
1203 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
1204 // we want to reverse this for the plain text arena of emails.
1205 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
1206
1207 $message = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
1208 $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
1209 $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";
1210
1211 @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
1212
1213 if ( empty($plaintext_pass) )
1214 return;
1215
1216 $message = sprintf(__('Username: %s'), $user_login) . "\r\n";
1217 $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
1218 $message .= wp_login_url() . "\r\n";
1219
1220 wp_mail($user_email, sprintf(__('[%s] Your username and password'), $blogname), $message);
1221
1222}
1223endif;
1224
1225if ( !function_exists('wp_nonce_tick') ) :
1226/**
1227 * Get the time-dependent variable for nonce creation.
1228 *
1229 * A nonce has a lifespan of two ticks. Nonces in their second tick may be
1230 * updated, e.g. by autosave.
1231 *
1232 * @since 2.5
1233 *
1234 * @return int
1235 */
1236function wp_nonce_tick() {
1237 $nonce_life = apply_filters('nonce_life', 86400);
1238
1239 return ceil(time() / ( $nonce_life / 2 ));
1240}
1241endif;
1242
1243if ( !function_exists('wp_verify_nonce') ) :
1244/**
1245 * Verify that correct nonce was used with time limit.
1246 *
1247 * The user is given an amount of time to use the token, so therefore, since the
1248 * UID and $action remain the same, the independent variable is the time.
1249 *
1250 * @since 2.0.3
1251 *
1252 * @param string $nonce Nonce that was used in the form to verify
1253 * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
1254 * @return bool Whether the nonce check passed or failed.
1255 */
1256function wp_verify_nonce($nonce, $action = -1) {
1257 $user = wp_get_current_user();
1258 $uid = (int) $user->ID;
1259
1260 $i = wp_nonce_tick();
1261
1262 // Nonce generated 0-12 hours ago
1263 if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce )
1264 return 1;
1265 // Nonce generated 12-24 hours ago
1266 if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce )
1267 return 2;
1268 // Invalid nonce
1269 return false;
1270}
1271endif;
1272
1273if ( !function_exists('wp_create_nonce') ) :
1274/**
1275 * Creates a random, one time use token.
1276 *
1277 * @since 2.0.3
1278 *
1279 * @param string|int $action Scalar value to add context to the nonce.
1280 * @return string The one use form token
1281 */
1282function wp_create_nonce($action = -1) {
1283 $user = wp_get_current_user();
1284 $uid = (int) $user->ID;
1285
1286 $i = wp_nonce_tick();
1287
1288 return substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10);
1289}
1290endif;
1291
1292if ( !function_exists('wp_salt') ) :
1293/**
1294 * Get salt to add to hashes.
1295 *
1296 * Salts are created using secret keys. Secret keys are located in two places:
1297 * in the database and in the wp-config.php file. The secret key in the database
1298 * is randomly generated and will be appended to the secret keys in wp-config.php.
1299 *
1300 * The secret keys in wp-config.php should be updated to strong, random keys to maximize
1301 * security. Below is an example of how the secret key constants are defined.
1302 * Do not paste this example directly into wp-config.php. Instead, have a
1303 * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
1304 * for you.
1305 *
1306 * <code>
1307 * define('AUTH_KEY', ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
1308 * define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
1309 * define('LOGGED_IN_KEY', '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
1310 * define('NONCE_KEY', '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
1311 * define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
1312 * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
1313 * define('LOGGED_IN_SALT', '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
1314 * define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
1315 * </code>
1316 *
1317 * Salting passwords helps against tools which has stored hashed values of
1318 * common dictionary strings. The added values makes it harder to crack.
1319 *
1320 * @since 2.5
1321 *
1322 * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
1323 *
1324 * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
1325 * @return string Salt value
1326 */
1327function wp_salt( $scheme = 'auth' ) {
1328 static $cached_salts = array();
1329 if ( isset( $cached_salts[ $scheme ] ) )
1330 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
1331
1332 static $duplicated_keys;
1333 if ( null === $duplicated_keys ) {
1334 $duplicated_keys = array( 'put your unique phrase here' => true );
1335 foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
1336 foreach ( array( 'KEY', 'SALT' ) as $second ) {
1337 if ( ! defined( "{$first}_{$second}" ) )
1338 continue;
1339 $value = constant( "{$first}_{$second}" );
1340 $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
1341 }
1342 }
1343 }
1344
1345 $key = $salt = '';
1346 if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) )
1347 $key = SECRET_KEY;
1348 if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) )
1349 $salt = SECRET_SALT;
1350
1351 if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) {
1352 foreach ( array( 'key', 'salt' ) as $type ) {
1353 $const = strtoupper( "{$scheme}_{$type}" );
1354 if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
1355 $$type = constant( $const );
1356 } elseif ( ! $$type ) {
1357 $$type = get_site_option( "{$scheme}_{$type}" );
1358 if ( ! $$type ) {
1359 $$type = wp_generate_password( 64, true, true );
1360 update_site_option( "{$scheme}_{$type}", $$type );
1361 }
1362 }
1363 }
1364 } else {
1365 if ( ! $key ) {
1366 $key = get_site_option( 'secret_key' );
1367 if ( ! $key ) {
1368 $key = wp_generate_password( 64, true, true );
1369 update_site_option( 'secret_key', $key );
1370 }
1371 }
1372 $salt = hash_hmac( 'md5', $scheme, $key );
1373 }
1374
1375 $cached_salts[ $scheme ] = $key . $salt;
1376 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
1377}
1378endif;
1379
1380if ( !function_exists('wp_hash') ) :
1381/**
1382 * Get hash of given string.
1383 *
1384 * @since 2.0.3
1385 * @uses wp_salt() Get WordPress salt
1386 *
1387 * @param string $data Plain text to hash
1388 * @return string Hash of $data
1389 */
1390function wp_hash($data, $scheme = 'auth') {
1391 $salt = wp_salt($scheme);
1392
1393 return hash_hmac('md5', $data, $salt);
1394}
1395endif;
1396
1397if ( !function_exists('wp_hash_password') ) :
1398/**
1399 * Create a hash (encrypt) of a plain text password.
1400 *
1401 * For integration with other applications, this function can be overwritten to
1402 * instead use the other package password checking algorithm.
1403 *
1404 * @since 2.5
1405 * @global object $wp_hasher PHPass object
1406 * @uses PasswordHash::HashPassword
1407 *
1408 * @param string $password Plain text user password to hash
1409 * @return string The hash string of the password
1410 */
1411function wp_hash_password($password) {
1412 global $wp_hasher;
1413
1414 if ( empty($wp_hasher) ) {
1415 require_once( ABSPATH . 'wp-includes/class-phpass.php');
1416 // By default, use the portable hash from phpass
1417 $wp_hasher = new PasswordHash(8, true);
1418 }
1419
1420 return $wp_hasher->HashPassword($password);
1421}
1422endif;
1423
1424if ( !function_exists('wp_check_password') ) :
1425/**
1426 * Checks the plaintext password against the encrypted Password.
1427 *
1428 * Maintains compatibility between old version and the new cookie authentication
1429 * protocol using PHPass library. The $hash parameter is the encrypted password
1430 * and the function compares the plain text password when encrypted similarly
1431 * against the already encrypted password to see if they match.
1432 *
1433 * For integration with other applications, this function can be overwritten to
1434 * instead use the other package password checking algorithm.
1435 *
1436 * @since 2.5
1437 * @global object $wp_hasher PHPass object used for checking the password
1438 * against the $hash + $password
1439 * @uses PasswordHash::CheckPassword
1440 *
1441 * @param string $password Plaintext user's password
1442 * @param string $hash Hash of the user's password to check against.
1443 * @return bool False, if the $password does not match the hashed password
1444 */
1445function wp_check_password($password, $hash, $user_id = '') {
1446 global $wp_hasher;
1447
1448 // If the hash is still md5...
1449 if ( strlen($hash) <= 32 ) {
1450 $check = ( $hash == md5($password) );
1451 if ( $check && $user_id ) {
1452 // Rehash using new hash.
1453 wp_set_password($password, $user_id);
1454 $hash = wp_hash_password($password);
1455 }
1456
1457 return apply_filters('check_password', $check, $password, $hash, $user_id);
1458 }
1459
1460 // If the stored hash is longer than an MD5, presume the
1461 // new style phpass portable hash.
1462 if ( empty($wp_hasher) ) {
1463 require_once( ABSPATH . 'wp-includes/class-phpass.php');
1464 // By default, use the portable hash from phpass
1465 $wp_hasher = new PasswordHash(8, true);
1466 }
1467
1468 $check = $wp_hasher->CheckPassword($password, $hash);
1469
1470 return apply_filters('check_password', $check, $password, $hash, $user_id);
1471}
1472endif;
1473
1474if ( !function_exists('wp_generate_password') ) :
1475/**
1476 * Generates a random password drawn from the defined set of characters.
1477 *
1478 * @since 2.5
1479 *
1480 * @param int $length The length of password to generate
1481 * @param bool $special_chars Whether to include standard special characters. Default true.
1482 * @param bool $extra_special_chars Whether to include other special characters. Used when
1483 * generating secret keys and salts. Default false.
1484 * @return string The random password
1485 **/
1486function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
1487 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
1488 if ( $special_chars )
1489 $chars .= '!@#$%^&*()';
1490 if ( $extra_special_chars )
1491 $chars .= '-_ []{}<>~`+=,.;:/?|';
1492
1493 $password = '';
1494 for ( $i = 0; $i < $length; $i++ ) {
1495 $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
1496 }
1497
1498 // random_password filter was previously in random_password function which was deprecated
1499 return apply_filters('random_password', $password);
1500}
1501endif;
1502
1503if ( !function_exists('wp_rand') ) :
1504 /**
1505 * Generates a random number
1506 *
1507 * @since 2.6.2
1508 *
1509 * @param int $min Lower limit for the generated number (optional, default is 0)
1510 * @param int $max Upper limit for the generated number (optional, default is 4294967295)
1511 * @return int A random number between min and max
1512 */
1513function wp_rand( $min = 0, $max = 0 ) {
1514 global $rnd_value;
1515
1516 // Reset $rnd_value after 14 uses
1517 // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
1518 if ( strlen($rnd_value) < 8 ) {
1519 if ( defined( 'WP_SETUP_CONFIG' ) )
1520 static $seed = '';
1521 else
1522 $seed = get_transient('random_seed');
1523 $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
1524 $rnd_value .= sha1($rnd_value);
1525 $rnd_value .= sha1($rnd_value . $seed);
1526 $seed = md5($seed . $rnd_value);
1527 if ( ! defined( 'WP_SETUP_CONFIG' ) )
1528 set_transient('random_seed', $seed);
1529 }
1530
1531 // Take the first 8 digits for our value
1532 $value = substr($rnd_value, 0, 8);
1533
1534 // Strip the first eight, leaving the remainder for the next call to wp_rand().
1535 $rnd_value = substr($rnd_value, 8);
1536
1537 $value = abs(hexdec($value));
1538
1539 // Reduce the value to be within the min - max range
1540 // 4294967295 = 0xffffffff = max random number
1541 if ( $max != 0 )
1542 $value = $min + (($max - $min + 1) * ($value / (4294967295 + 1)));
1543
1544 return abs(intval($value));
1545}
1546endif;
1547
1548if ( !function_exists('wp_set_password') ) :
1549/**
1550 * Updates the user's password with a new encrypted one.
1551 *
1552 * For integration with other applications, this function can be overwritten to
1553 * instead use the other package password checking algorithm.
1554 *
1555 * @since 2.5
1556 * @uses $wpdb WordPress database object for queries
1557 * @uses wp_hash_password() Used to encrypt the user's password before passing to the database
1558 *
1559 * @param string $password The plaintext new user password
1560 * @param int $user_id User ID
1561 */
1562function wp_set_password( $password, $user_id ) {
1563 global $wpdb;
1564
1565 $hash = wp_hash_password($password);
1566 $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
1567
1568 wp_cache_delete($user_id, 'users');
1569}
1570endif;
1571
1572if ( !function_exists( 'get_avatar' ) ) :
1573/**
1574 * Retrieve the avatar for a user who provided a user ID or email address.
1575 *
1576 * @since 2.5
1577 * @param int|string|object $id_or_email A user ID, email address, or comment object
1578 * @param int $size Size of the avatar image
1579 * @param string $default URL to a default image to use if no avatar is available
1580 * @param string $alt Alternate text to use in image tag. Defaults to blank
1581 * @return string <img> tag for the user's avatar
1582*/
1583function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
1584 if ( ! get_option('show_avatars') )
1585 return false;
1586
1587 if ( false === $alt)
1588 $safe_alt = '';
1589 else
1590 $safe_alt = esc_attr( $alt );
1591
1592 if ( !is_numeric($size) )
1593 $size = '96';
1594
1595 $email = '';
1596 if ( is_numeric($id_or_email) ) {
1597 $id = (int) $id_or_email;
1598 $user = get_userdata($id);
1599 if ( $user )
1600 $email = $user->user_email;
1601 } elseif ( is_object($id_or_email) ) {
1602 // No avatar for pingbacks or trackbacks
1603 $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
1604 if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
1605 return false;
1606
1607 if ( !empty($id_or_email->user_id) ) {
1608 $id = (int) $id_or_email->user_id;
1609 $user = get_userdata($id);
1610 if ( $user)
1611 $email = $user->user_email;
1612 } elseif ( !empty($id_or_email->comment_author_email) ) {
1613 $email = $id_or_email->comment_author_email;
1614 }
1615 } else {
1616 $email = $id_or_email;
1617 }
1618
1619 if ( empty($default) ) {
1620 $avatar_default = get_option('avatar_default');
1621 if ( empty($avatar_default) )
1622 $default = 'mystery';
1623 else
1624 $default = $avatar_default;
1625 }
1626
1627 if ( !empty($email) )
1628 $email_hash = md5( strtolower( trim( $email ) ) );
1629
1630 if ( is_ssl() ) {
1631 $host = 'https://secure.gravatar.com';
1632 } else {
1633 if ( !empty($email) )
1634 $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) );
1635 else
1636 $host = 'http://0.gravatar.com';
1637 }
1638
1639 if ( 'mystery' == $default )
1640 $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
1641 elseif ( 'blank' == $default )
1642 $default = includes_url('images/blank.gif');
1643 elseif ( !empty($email) && 'gravatar_default' == $default )
1644 $default = '';
1645 elseif ( 'gravatar_default' == $default )
1646 $default = "$host/avatar/?s={$size}";
1647 elseif ( empty($email) )
1648 $default = "$host/avatar/?d=$default&s={$size}";
1649 elseif ( strpos($default, 'http://') === 0 )
1650 $default = add_query_arg( 's', $size, $default );
1651
1652 if ( !empty($email) ) {
1653 $out = "$host/avatar/";
1654 $out .= $email_hash;
1655 $out .= '?s='.$size;
1656 $out .= '&d=' . urlencode( $default );
1657
1658 $rating = get_option('avatar_rating');
1659 if ( !empty( $rating ) )
1660 $out .= "&r={$rating}";
1661
1662 $avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
1663 } else {
1664 $avatar = "<img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
1665 }
1666
1667 return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt);
1668}
1669endif;
1670
1671if ( !function_exists( 'wp_text_diff' ) ) :
1672/**
1673 * Displays a human readable HTML representation of the difference between two strings.
1674 *
1675 * The Diff is available for getting the changes between versions. The output is
1676 * HTML, so the primary use is for displaying the changes. If the two strings
1677 * are equivalent, then an empty string will be returned.
1678 *
1679 * The arguments supported and can be changed are listed below.
1680 *
1681 * 'title' : Default is an empty string. Titles the diff in a manner compatible
1682 * with the output.
1683 * 'title_left' : Default is an empty string. Change the HTML to the left of the
1684 * title.
1685 * 'title_right' : Default is an empty string. Change the HTML to the right of
1686 * the title.
1687 *
1688 * @since 2.6
1689 * @see wp_parse_args() Used to change defaults to user defined settings.
1690 * @uses Text_Diff
1691 * @uses WP_Text_Diff_Renderer_Table
1692 *
1693 * @param string $left_string "old" (left) version of string
1694 * @param string $right_string "new" (right) version of string
1695 * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
1696 * @return string Empty string if strings are equivalent or HTML with differences.
1697 */
1698function wp_text_diff( $left_string, $right_string, $args = null ) {
1699 $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
1700 $args = wp_parse_args( $args, $defaults );
1701
1702 if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
1703 require( ABSPATH . WPINC . '/wp-diff.php' );
1704
1705 $left_string = normalize_whitespace($left_string);
1706 $right_string = normalize_whitespace($right_string);
1707
1708 $left_lines = explode("\n", $left_string);
1709 $right_lines = explode("\n", $right_string);
1710
1711 $text_diff = new Text_Diff($left_lines, $right_lines);
1712 $renderer = new WP_Text_Diff_Renderer_Table();
1713 $diff = $renderer->render($text_diff);
1714
1715 if ( !$diff )
1716 return '';
1717
1718 $r = "<table class='diff'>\n";
1719 $r .= "<col class='ltype' /><col class='content' /><col class='ltype' /><col class='content' />";
1720
1721 if ( $args['title'] || $args['title_left'] || $args['title_right'] )
1722 $r .= "<thead>";
1723 if ( $args['title'] )
1724 $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
1725 if ( $args['title_left'] || $args['title_right'] ) {
1726 $r .= "<tr class='diff-sub-title'>\n";
1727 $r .= "\t<td></td><th>$args[title_left]</th>\n";
1728 $r .= "\t<td></td><th>$args[title_right]</th>\n";
1729 $r .= "</tr>\n";
1730 }
1731 if ( $args['title'] || $args['title_left'] || $args['title_right'] )
1732 $r .= "</thead>\n";
1733
1734 $r .= "<tbody>\n$diff\n</tbody>\n";
1735 $r .= "</table>";
1736
1737 return $r;
1738}
1739endif;
1740<?php
1741/**
1742 * These functions can be replaced via plugins. If plugins do not redefine these
1743 * functions, then these will be used instead.
1744 *
1745 * @package WordPress
1746 */
1747
1748if ( !function_exists('wp_set_current_user') ) :
1749/**
1750 * Changes the current user by ID or name.
1751 *
1752 * Set $id to null and specify a name if you do not know a user's ID.
1753 *
1754 * Some WordPress functionality is based on the current user and not based on
1755 * the signed in user. Therefore, it opens the ability to edit and perform
1756 * actions on users who aren't signed in.
1757 *
1758 * @since 2.0.3
1759 * @global object $current_user The current user object which holds the user data.
1760 * @uses do_action() Calls 'set_current_user' hook after setting the current user.
1761 *
1762 * @param int $id User ID
1763 * @param string $name User's username
1764 * @return WP_User Current user User object
1765 */
1766function wp_set_current_user($id, $name = '') {
1767 global $current_user;
1768
1769 if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) )
1770 return $current_user;
1771
1772 $current_user = new WP_User( $id, $name );
1773
1774 setup_userdata( $current_user->ID );
1775
1776 do_action('set_current_user');
1777
1778 return $current_user;
1779}
1780endif;
1781
1782if ( !function_exists('wp_get_current_user') ) :
1783/**
1784 * Retrieve the current user object.
1785 *
1786 * @since 2.0.3
1787 *
1788 * @return WP_User Current user WP_User object
1789 */
1790function wp_get_current_user() {
1791 global $current_user;
1792
1793 get_currentuserinfo();
1794
1795 return $current_user;
1796}
1797endif;
1798
1799if ( !function_exists('get_currentuserinfo') ) :
1800/**
1801 * Populate global variables with information about the currently logged in user.
1802 *
1803 * Will set the current user, if the current user is not set. The current user
1804 * will be set to the logged in person. If no user is logged in, then it will
1805 * set the current user to 0, which is invalid and won't have any permissions.
1806 *
1807 * @since 0.71
1808 * @uses $current_user Checks if the current user is set
1809 * @uses wp_validate_auth_cookie() Retrieves current logged in user.
1810 *
1811 * @return bool|null False on XMLRPC Request and invalid auth cookie. Null when current user set
1812 */
1813function get_currentuserinfo() {
1814 global $current_user;
1815
1816 if ( ! empty( $current_user ) ) {
1817 if ( $current_user instanceof WP_User )
1818 return;
1819
1820 // Upgrade stdClass to WP_User
1821 if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
1822 $cur_id = $current_user->ID;
1823 $current_user = null;
1824 wp_set_current_user( $cur_id );
1825 return;
1826 }
1827
1828 // $current_user has a junk value. Force to WP_User with ID 0.
1829 $current_user = null;
1830 wp_set_current_user( 0 );
1831 return false;
1832 }
1833
1834 if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
1835 wp_set_current_user( 0 );
1836 return false;
1837 }
1838
1839 if ( ! $user = wp_validate_auth_cookie() ) {
1840 if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) || !$user = wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' ) ) {
1841 wp_set_current_user( 0 );
1842 return false;
1843 }
1844 }
1845
1846 wp_set_current_user( $user );
1847}
1848endif;
1849
1850if ( !function_exists('get_userdata') ) :
1851/**
1852 * Retrieve user info by user ID.
1853 *
1854 * @since 0.71
1855 *
1856 * @param int $user_id User ID
1857 * @return bool|object False on failure, WP_User object on success
1858 */
1859function get_userdata( $user_id ) {
1860 return get_user_by( 'id', $user_id );
1861}
1862endif;
1863
1864if ( !function_exists('get_user_by') ) :
1865/**
1866 * Retrieve user info by a given field
1867 *
1868 * @since 2.8.0
1869 *
1870 * @param string $field The field to retrieve the user with. id | slug | email | login
1871 * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
1872 * @return bool|object False on failure, WP_User object on success
1873 */
1874function get_user_by( $field, $value ) {
1875 $userdata = WP_User::get_data_by( $field, $value );
1876
1877 if ( !$userdata )
1878 return false;
1879
1880 $user = new WP_User;
1881 $user->init( $userdata );
1882
1883 return $user;
1884}
1885endif;
1886
1887if ( !function_exists('cache_users') ) :
1888/**
1889 * Retrieve info for user lists to prevent multiple queries by get_userdata()
1890 *
1891 * @since 3.0.0
1892 *
1893 * @param array $user_ids User ID numbers list
1894 */
1895function cache_users( $user_ids ) {
1896 global $wpdb;
1897
1898 $clean = _get_non_cached_ids( $user_ids, 'users' );
1899
1900 if ( empty( $clean ) )
1901 return;
1902
1903 $list = implode( ',', $clean );
1904
1905 $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
1906
1907 $ids = array();
1908 foreach ( $users as $user ) {
1909 update_user_caches( $user );
1910 $ids[] = $user->ID;
1911 }
1912 update_meta_cache( 'user', $ids );
1913}
1914endif;
1915
1916if ( !function_exists( 'wp_mail' ) ) :
1917/**
1918 * Send mail, similar to PHP's mail
1919 *
1920 * A true return value does not automatically mean that the user received the
1921 * email successfully. It just only means that the method used was able to
1922 * process the request without any errors.
1923 *
1924 * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
1925 * creating a from address like 'Name <email@address.com>' when both are set. If
1926 * just 'wp_mail_from' is set, then just the email address will be used with no
1927 * name.
1928 *
1929 * The default content type is 'text/plain' which does not allow using HTML.
1930 * However, you can set the content type of the email by using the
1931 * 'wp_mail_content_type' filter.
1932 *
1933 * The default charset is based on the charset used on the blog. The charset can
1934 * be set using the 'wp_mail_charset' filter.
1935 *
1936 * @since 1.2.1
1937 * @uses apply_filters() Calls 'wp_mail' hook on an array of all of the parameters.
1938 * @uses apply_filters() Calls 'wp_mail_from' hook to get the from email address.
1939 * @uses apply_filters() Calls 'wp_mail_from_name' hook to get the from address name.
1940 * @uses apply_filters() Calls 'wp_mail_content_type' hook to get the email content type.
1941 * @uses apply_filters() Calls 'wp_mail_charset' hook to get the email charset
1942 * @uses do_action_ref_array() Calls 'phpmailer_init' hook on the reference to
1943 * phpmailer object.
1944 * @uses PHPMailer
1945 *
1946 * @param string|array $to Array or comma-separated list of email addresses to send message.
1947 * @param string $subject Email subject
1948 * @param string $message Message contents
1949 * @param string|array $headers Optional. Additional headers.
1950 * @param string|array $attachments Optional. Files to attach.
1951 * @return bool Whether the email contents were sent successfully.
1952 */
1953function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
1954 // Compact the input, apply the filters, and extract them back out
1955 extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
1956
1957 if ( !is_array($attachments) )
1958 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
1959
1960 global $phpmailer;
1961
1962 // (Re)create it, if it's gone missing
1963 if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) {
1964 require_once ABSPATH . WPINC . '/class-phpmailer.php';
1965 require_once ABSPATH . WPINC . '/class-smtp.php';
1966 $phpmailer = new PHPMailer( true );
1967 }
1968
1969 // Headers
1970 if ( empty( $headers ) ) {
1971 $headers = array();
1972 } else {
1973 if ( !is_array( $headers ) ) {
1974 // Explode the headers out, so this function can take both
1975 // string headers and an array of headers.
1976 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
1977 } else {
1978 $tempheaders = $headers;
1979 }
1980 $headers = array();
1981 $cc = array();
1982 $bcc = array();
1983
1984 // If it's actually got contents
1985 if ( !empty( $tempheaders ) ) {
1986 // Iterate through the raw headers
1987 foreach ( (array) $tempheaders as $header ) {
1988 if ( strpos($header, ':') === false ) {
1989 if ( false !== stripos( $header, 'boundary=' ) ) {
1990 $parts = preg_split('/boundary=/i', trim( $header ) );
1991 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
1992 }
1993 continue;
1994 }
1995 // Explode them out
1996 list( $name, $content ) = explode( ':', trim( $header ), 2 );
1997
1998 // Cleanup crew
1999 $name = trim( $name );
2000 $content = trim( $content );
2001
2002 switch ( strtolower( $name ) ) {
2003 // Mainly for legacy -- process a From: header if it's there
2004 case 'from':
2005 if ( strpos($content, '<' ) !== false ) {
2006 // So... making my life hard again?
2007 $from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
2008 $from_name = str_replace( '"', '', $from_name );
2009 $from_name = trim( $from_name );
2010
2011 $from_email = substr( $content, strpos( $content, '<' ) + 1 );
2012 $from_email = str_replace( '>', '', $from_email );
2013 $from_email = trim( $from_email );
2014 } else {
2015 $from_email = trim( $content );
2016 }
2017 break;
2018 case 'content-type':
2019 if ( strpos( $content, ';' ) !== false ) {
2020 list( $type, $charset ) = explode( ';', $content );
2021 $content_type = trim( $type );
2022 if ( false !== stripos( $charset, 'charset=' ) ) {
2023 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) );
2024 } elseif ( false !== stripos( $charset, 'boundary=' ) ) {
2025 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) );
2026 $charset = '';
2027 }
2028 } else {
2029 $content_type = trim( $content );
2030 }
2031 break;
2032 case 'cc':
2033 $cc = array_merge( (array) $cc, explode( ',', $content ) );
2034 break;
2035 case 'bcc':
2036 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
2037 break;
2038 default:
2039 // Add it to our grand headers array
2040 $headers[trim( $name )] = trim( $content );
2041 break;
2042 }
2043 }
2044 }
2045 }
2046
2047 // Empty out the values that may be set
2048 $phpmailer->ClearAddresses();
2049 $phpmailer->ClearAllRecipients();
2050 $phpmailer->ClearAttachments();
2051 $phpmailer->ClearBCCs();
2052 $phpmailer->ClearCCs();
2053 $phpmailer->ClearCustomHeaders();
2054 $phpmailer->ClearReplyTos();
2055
2056 // From email and name
2057 // If we don't have a name from the input headers
2058 if ( !isset( $from_name ) )
2059 $from_name = 'WordPress';
2060
2061 /* If we don't have an email from the input headers default to wordpress@$sitename
2062 * Some hosts will block outgoing mail from this address if it doesn't exist but
2063 * there's no easy alternative. Defaulting to admin_email might appear to be another
2064 * option but some hosts may refuse to relay mail from an unknown domain. See
2065 * http://trac.wordpress.org/ticket/5007.
2066 */
2067
2068 if ( !isset( $from_email ) ) {
2069 // Get the site domain and get rid of www.
2070 $sitename = strtolower( $_SERVER['SERVER_NAME'] );
2071 if ( substr( $sitename, 0, 4 ) == 'www.' ) {
2072 $sitename = substr( $sitename, 4 );
2073 }
2074
2075 $from_email = 'wordpress@' . $sitename;
2076 }
2077
2078 // Plugin authors can override the potentially troublesome default
2079 $phpmailer->From = apply_filters( 'wp_mail_from' , $from_email );
2080 $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
2081
2082 // Set destination addresses
2083 if ( !is_array( $to ) )
2084 $to = explode( ',', $to );
2085
2086 foreach ( (array) $to as $recipient ) {
2087 try {
2088 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
2089 $recipient_name = '';
2090 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
2091 if ( count( $matches ) == 3 ) {
2092 $recipient_name = $matches[1];
2093 $recipient = $matches[2];
2094 }
2095 }
2096 $phpmailer->AddAddress( $recipient, $recipient_name);
2097 } catch ( phpmailerException $e ) {
2098 continue;
2099 }
2100 }
2101
2102 // Set mail's subject and body
2103 $phpmailer->Subject = $subject;
2104 $phpmailer->Body = $message;
2105
2106 // Add any CC and BCC recipients
2107 if ( !empty( $cc ) ) {
2108 foreach ( (array) $cc as $recipient ) {
2109 try {
2110 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
2111 $recipient_name = '';
2112 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
2113 if ( count( $matches ) == 3 ) {
2114 $recipient_name = $matches[1];
2115 $recipient = $matches[2];
2116 }
2117 }
2118 $phpmailer->AddCc( $recipient, $recipient_name );
2119 } catch ( phpmailerException $e ) {
2120 continue;
2121 }
2122 }
2123 }
2124
2125 if ( !empty( $bcc ) ) {
2126 foreach ( (array) $bcc as $recipient) {
2127 try {
2128 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
2129 $recipient_name = '';
2130 if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
2131 if ( count( $matches ) == 3 ) {
2132 $recipient_name = $matches[1];
2133 $recipient = $matches[2];
2134 }
2135 }
2136 $phpmailer->AddBcc( $recipient, $recipient_name );
2137 } catch ( phpmailerException $e ) {
2138 continue;
2139 }
2140 }
2141 }
2142
2143 // Set to use PHP's mail()
2144 $phpmailer->IsMail();
2145
2146 // Set Content-Type and charset
2147 // If we don't have a content-type from the input headers
2148 if ( !isset( $content_type ) )
2149 $content_type = 'text/plain';
2150
2151 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
2152
2153 $phpmailer->ContentType = $content_type;
2154
2155 // Set whether it's plaintext, depending on $content_type
2156 if ( 'text/html' == $content_type )
2157 $phpmailer->IsHTML( true );
2158
2159 // If we don't have a charset from the input headers
2160 if ( !isset( $charset ) )
2161 $charset = get_bloginfo( 'charset' );
2162
2163 // Set the content-type and charset
2164 $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
2165
2166 // Set custom headers
2167 if ( !empty( $headers ) ) {
2168 foreach( (array) $headers as $name => $content ) {
2169 $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
2170 }
2171
2172 if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
2173 $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
2174 }
2175
2176 if ( !empty( $attachments ) ) {
2177 foreach ( $attachments as $attachment ) {
2178 try {
2179 $phpmailer->AddAttachment($attachment);
2180 } catch ( phpmailerException $e ) {
2181 continue;
2182 }
2183 }
2184 }
2185
2186 do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
2187
2188 // Send!
2189 try {
2190 $phpmailer->Send();
2191 } catch ( phpmailerException $e ) {
2192 return false;
2193 }
2194
2195 return true;
2196}
2197endif;
2198
2199if ( !function_exists('wp_authenticate') ) :
2200/**
2201 * Checks a user's login information and logs them in if it checks out.
2202 *
2203 * @since 2.5.0
2204 *
2205 * @param string $username User's username
2206 * @param string $password User's password
2207 * @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object.
2208 */
2209function wp_authenticate($username, $password) {
2210 $username = sanitize_user($username);
2211 $password = trim($password);
2212
2213 $user = apply_filters('authenticate', null, $username, $password);
2214
2215 if ( $user == null ) {
2216 // TODO what should the error message be? (Or would these even happen?)
2217 // Only needed if all authentication handlers fail to return anything.
2218 $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
2219 }
2220
2221 $ignore_codes = array('empty_username', 'empty_password');
2222
2223 if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
2224 do_action('wp_login_failed', $username);
2225 }
2226
2227 return $user;
2228}
2229endif;
2230
2231if ( !function_exists('wp_logout') ) :
2232/**
2233 * Log the current user out.
2234 *
2235 * @since 2.5.0
2236 */
2237function wp_logout() {
2238 wp_clear_auth_cookie();
2239 do_action('wp_logout');
2240}
2241endif;
2242
2243if ( !function_exists('wp_validate_auth_cookie') ) :
2244/**
2245 * Validates authentication cookie.
2246 *
2247 * The checks include making sure that the authentication cookie is set and
2248 * pulling in the contents (if $cookie is not used).
2249 *
2250 * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
2251 * should be and compares the two.
2252 *
2253 * @since 2.5
2254 *
2255 * @param string $cookie Optional. If used, will validate contents instead of cookie's
2256 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
2257 * @return bool|int False if invalid cookie, User ID if valid.
2258 */
2259function wp_validate_auth_cookie($cookie = '', $scheme = '') {
2260 if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
2261 do_action('auth_cookie_malformed', $cookie, $scheme);
2262 return false;
2263 }
2264
2265 extract($cookie_elements, EXTR_OVERWRITE);
2266
2267 $expired = $expiration;
2268
2269 // Allow a grace period for POST and AJAX requests
2270 if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] )
2271 $expired += 3600;
2272
2273 // Quick check to see if an honest cookie has expired
2274 if ( $expired < time() ) {
2275 do_action('auth_cookie_expired', $cookie_elements);
2276 return false;
2277 }
2278
2279 $user = get_user_by('login', $username);
2280 if ( ! $user ) {
2281 do_action('auth_cookie_bad_username', $cookie_elements);
2282 return false;
2283 }
2284
2285 $pass_frag = substr($user->user_pass, 8, 4);
2286
2287 $key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme);
2288 $hash = hash_hmac('md5', $username . '|' . $expiration, $key);
2289
2290 if ( $hmac != $hash ) {
2291 do_action('auth_cookie_bad_hash', $cookie_elements);
2292 return false;
2293 }
2294
2295 if ( $expiration < time() ) // AJAX/POST grace period set above
2296 $GLOBALS['login_grace_period'] = 1;
2297
2298 do_action('auth_cookie_valid', $cookie_elements, $user);
2299
2300 return $user->ID;
2301}
2302endif;
2303
2304if ( !function_exists('wp_generate_auth_cookie') ) :
2305/**
2306 * Generate authentication cookie contents.
2307 *
2308 * @since 2.5
2309 * @uses apply_filters() Calls 'auth_cookie' hook on $cookie contents, User ID
2310 * and expiration of cookie.
2311 *
2312 * @param int $user_id User ID
2313 * @param int $expiration Cookie expiration in seconds
2314 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
2315 * @return string Authentication cookie contents
2316 */
2317function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') {
2318 $user = get_userdata($user_id);
2319
2320 $pass_frag = substr($user->user_pass, 8, 4);
2321
2322 $key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme);
2323 $hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key);
2324
2325 $cookie = $user->user_login . '|' . $expiration . '|' . $hash;
2326
2327 return apply_filters('auth_cookie', $cookie, $user_id, $expiration, $scheme);
2328}
2329endif;
2330
2331if ( !function_exists('wp_parse_auth_cookie') ) :
2332/**
2333 * Parse a cookie into its components
2334 *
2335 * @since 2.7
2336 *
2337 * @param string $cookie
2338 * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
2339 * @return array Authentication cookie components
2340 */
2341function wp_parse_auth_cookie($cookie = '', $scheme = '') {
2342 if ( empty($cookie) ) {
2343 switch ($scheme){
2344 case 'auth':
2345 $cookie_name = AUTH_COOKIE;
2346 break;
2347 case 'secure_auth':
2348 $cookie_name = SECURE_AUTH_COOKIE;
2349 break;
2350 case "logged_in":
2351 $cookie_name = LOGGED_IN_COOKIE;
2352 break;
2353 default:
2354 if ( is_ssl() ) {
2355 $cookie_name = SECURE_AUTH_COOKIE;
2356 $scheme = 'secure_auth';
2357 } else {
2358 $cookie_name = AUTH_COOKIE;
2359 $scheme = 'auth';
2360 }
2361 }
2362
2363 if ( empty($_COOKIE[$cookie_name]) )
2364 return false;
2365 $cookie = $_COOKIE[$cookie_name];
2366 }
2367
2368 $cookie_elements = explode('|', $cookie);
2369 if ( count($cookie_elements) != 3 )
2370 return false;
2371
2372 list($username, $expiration, $hmac) = $cookie_elements;
2373
2374 return compact('username', 'expiration', 'hmac', 'scheme');
2375}
2376endif;
2377
2378if ( !function_exists('wp_set_auth_cookie') ) :
2379/**
2380 * Sets the authentication cookies based User ID.
2381 *
2382 * The $remember parameter increases the time that the cookie will be kept. The
2383 * default the cookie is kept without remembering is two days. When $remember is
2384 * set, the cookies will be kept for 14 days or two weeks.
2385 *
2386 * @since 2.5
2387 *
2388 * @param int $user_id User ID
2389 * @param bool $remember Whether to remember the user
2390 */
2391function wp_set_auth_cookie($user_id, $remember = false, $secure = '') {
2392 if ( $remember ) {
2393 $expiration = $expire = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, $remember);
2394 } else {
2395 $expiration = time() + apply_filters('auth_cookie_expiration', 172800, $user_id, $remember);
2396 $expire = 0;
2397 }
2398
2399 if ( '' === $secure )
2400 $secure = is_ssl();
2401
2402 $secure = apply_filters('secure_auth_cookie', $secure, $user_id);
2403 $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', false, $user_id, $secure);
2404
2405 if ( $secure ) {
2406 $auth_cookie_name = SECURE_AUTH_COOKIE;
2407 $scheme = 'secure_auth';
2408 } else {
2409 $auth_cookie_name = AUTH_COOKIE;
2410 $scheme = 'auth';
2411 }
2412
2413 $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme);
2414 $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
2415
2416 do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme);
2417 do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in');
2418
2419 setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
2420 setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
2421 setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
2422 if ( COOKIEPATH != SITECOOKIEPATH )
2423 setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
2424}
2425endif;
2426
2427if ( !function_exists('wp_clear_auth_cookie') ) :
2428/**
2429 * Removes all of the cookies associated with authentication.
2430 *
2431 * @since 2.5
2432 */
2433function wp_clear_auth_cookie() {
2434 do_action('clear_auth_cookie');
2435
2436 setcookie(AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
2437 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
2438 setcookie(AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
2439 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
2440 setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
2441 setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
2442
2443 // Old cookies
2444 setcookie(AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
2445 setcookie(AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
2446 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
2447 setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
2448
2449 // Even older cookies
2450 setcookie(USER_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
2451 setcookie(PASS_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
2452 setcookie(USER_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
2453 setcookie(PASS_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
2454}
2455endif;
2456
2457if ( !function_exists('is_user_logged_in') ) :
2458/**
2459 * Checks if the current visitor is a logged in user.
2460 *
2461 * @since 2.0.0
2462 *
2463 * @return bool True if user is logged in, false if not logged in.
2464 */
2465function is_user_logged_in() {
2466 $user = wp_get_current_user();
2467
2468 if ( ! $user->exists() )
2469 return false;
2470
2471 return true;
2472}
2473endif;
2474
2475if ( !function_exists('auth_redirect') ) :
2476/**
2477 * Checks if a user is logged in, if not it redirects them to the login page.
2478 *
2479 * @since 1.5
2480 */
2481function auth_redirect() {
2482 // Checks if a user is logged in, if not redirects them to the login page
2483
2484 $secure = ( is_ssl() || force_ssl_admin() );
2485
2486 $secure = apply_filters('secure_auth_redirect', $secure);
2487
2488 // If https is required and request is http, redirect
2489 if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
2490 if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
2491 wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
2492 exit();
2493 } else {
2494 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
2495 exit();
2496 }
2497 }
2498
2499 if ( is_user_admin() )
2500 $scheme = 'logged_in';
2501 else
2502 $scheme = apply_filters( 'auth_redirect_scheme', '' );
2503
2504 if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) {
2505 do_action('auth_redirect', $user_id);
2506
2507 // If the user wants ssl but the session is not ssl, redirect.
2508 if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
2509 if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
2510 wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
2511 exit();
2512 } else {
2513 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
2514 exit();
2515 }
2516 }
2517
2518 return; // The cookie is good so we're done
2519 }
2520
2521 // The cookie is no good so force login
2522 nocache_headers();
2523
2524 if ( is_ssl() )
2525 $proto = 'https://';
2526 else
2527 $proto = 'http://';
2528
2529 $redirect = ( strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ) ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
2530
2531 $login_url = wp_login_url($redirect, true);
2532
2533 wp_redirect($login_url);
2534 exit();
2535}
2536endif;
2537
2538if ( !function_exists('check_admin_referer') ) :
2539/**
2540 * Makes sure that a user was referred from another admin page.
2541 *
2542 * To avoid security exploits.
2543 *
2544 * @since 1.2.0
2545 * @uses do_action() Calls 'check_admin_referer' on $action.
2546 *
2547 * @param string $action Action nonce
2548 * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
2549 */
2550function check_admin_referer($action = -1, $query_arg = '_wpnonce') {
2551 if ( -1 == $action )
2552 _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
2553
2554 $adminurl = strtolower(admin_url());
2555 $referer = strtolower(wp_get_referer());
2556 $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
2557 if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
2558 wp_nonce_ays($action);
2559 die();
2560 }
2561 do_action('check_admin_referer', $action, $result);
2562 return $result;
2563}endif;
2564
2565if ( !function_exists('check_ajax_referer') ) :
2566/**
2567 * Verifies the AJAX request to prevent processing requests external of the blog.
2568 *
2569 * @since 2.0.3
2570 *
2571 * @param string $action Action nonce
2572 * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
2573 */
2574function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
2575 if ( $query_arg )
2576 $nonce = $_REQUEST[$query_arg];
2577 else
2578 $nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce'];
2579
2580 $result = wp_verify_nonce( $nonce, $action );
2581
2582 if ( $die && false == $result ) {
2583 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2584 wp_die( -1 );
2585 else
2586 die( '-1' );
2587 }
2588
2589 do_action('check_ajax_referer', $action, $result);
2590
2591 return $result;
2592}
2593endif;
2594
2595if ( !function_exists('wp_redirect') ) :
2596/**
2597 * Redirects to another page.
2598 *
2599 * @since 1.5.1
2600 * @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
2601 *
2602 * @param string $location The path to redirect to
2603 * @param int $status Status code to use
2604 * @return bool False if $location is not set
2605 */
2606function wp_redirect($location, $status = 302) {
2607 global $is_IIS;
2608
2609 $location = apply_filters('wp_redirect', $location, $status);
2610 $status = apply_filters('wp_redirect_status', $status, $location);
2611
2612 if ( !$location ) // allows the wp_redirect filter to cancel a redirect
2613 return false;
2614
2615 $location = wp_sanitize_redirect($location);
2616
2617 if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
2618 status_header($status); // This causes problems on IIS and some FastCGI setups
2619
2620 header("Location: $location", true, $status);
2621}
2622endif;
2623
2624if ( !function_exists('wp_sanitize_redirect') ) :
2625/**
2626 * Sanitizes a URL for use in a redirect.
2627 *
2628 * @since 2.3
2629 *
2630 * @return string redirect-sanitized URL
2631 **/
2632function wp_sanitize_redirect($location) {
2633 $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location);
2634 $location = wp_kses_no_null($location);
2635
2636 // remove %0d and %0a from location
2637 $strip = array('%0d', '%0a', '%0D', '%0A');
2638 $location = _deep_replace($strip, $location);
2639 return $location;
2640}
2641endif;
2642
2643if ( !function_exists('wp_safe_redirect') ) :
2644/**
2645 * Performs a safe (local) redirect, using wp_redirect().
2646 *
2647 * Checks whether the $location is using an allowed host, if it has an absolute
2648 * path. A plugin can therefore set or remove allowed host(s) to or from the
2649 * list.
2650 *
2651 * If the host is not allowed, then the redirect is to wp-admin on the siteurl
2652 * instead. This prevents malicious redirects which redirect to another host,
2653 * but only used in a few places.
2654 *
2655 * @since 2.3
2656 * @uses wp_validate_redirect() To validate the redirect is to an allowed host.
2657 *
2658 * @return void Does not return anything
2659 **/
2660function wp_safe_redirect($location, $status = 302) {
2661
2662 // Need to look at the URL the way it will end up in wp_redirect()
2663 $location = wp_sanitize_redirect($location);
2664
2665 $location = wp_validate_redirect($location, admin_url());
2666
2667 wp_redirect($location, $status);
2668}
2669endif;
2670
2671if ( !function_exists('wp_validate_redirect') ) :
2672/**
2673 * Validates a URL for use in a redirect.
2674 *
2675 * Checks whether the $location is using an allowed host, if it has an absolute
2676 * path. A plugin can therefore set or remove allowed host(s) to or from the
2677 * list.
2678 *
2679 * If the host is not allowed, then the redirect is to $default supplied
2680 *
2681 * @since 2.8.1
2682 * @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing
2683 * WordPress host string and $location host string.
2684 *
2685 * @param string $location The redirect to validate
2686 * @param string $default The value to return if $location is not allowed
2687 * @return string redirect-sanitized URL
2688 **/
2689function wp_validate_redirect($location, $default = '') {
2690 // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
2691 if ( substr($location, 0, 2) == '//' )
2692 $location = 'http:' . $location;
2693
2694 // In php 5 parse_url may fail if the URL query part contains http://, bug #38143
2695 $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
2696
2697 $lp = parse_url($test);
2698
2699 // Give up if malformed URL
2700 if ( false === $lp )
2701 return $default;
2702
2703 // Allow only http and https schemes. No data:, etc.
2704 if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
2705 return $default;
2706
2707 // 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.
2708 if ( isset($lp['scheme']) && !isset($lp['host']) )
2709 return $default;
2710
2711 $wpp = parse_url(home_url());
2712
2713 $allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '');
2714
2715 if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
2716 $location = $default;
2717
2718 return $location;
2719}
2720endif;
2721
2722if ( ! function_exists('wp_notify_postauthor') ) :
2723/**
2724 * Notify an author of a comment/trackback/pingback to one of their posts.
2725 *
2726 * @since 1.0.0
2727 *
2728 * @param int $comment_id Comment ID
2729 * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback'
2730 * @return bool False if user email does not exist. True on completion.
2731 */
2732function wp_notify_postauthor( $comment_id, $comment_type = '' ) {
2733 $comment = get_comment( $comment_id );
2734 $post = get_post( $comment->comment_post_ID );
2735 $author = get_userdata( $post->post_author );
2736
2737 // The comment was left by the author
2738 if ( $comment->user_id == $post->post_author )
2739 return false;
2740
2741 // The author moderated a comment on his own post
2742 if ( $post->post_author == get_current_user_id() )
2743 return false;
2744
2745 // If there's no email to send the comment to
2746 if ( '' == $author->user_email )
2747 return false;
2748
2749 $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
2750
2751 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
2752 // we want to reverse this for the plain text arena of emails.
2753 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
2754
2755 if ( empty( $comment_type ) ) $comment_type = 'comment';
2756
2757 if ('comment' == $comment_type) {
2758 $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
2759 /* translators: 1: comment author, 2: author IP, 3: author domain */
2760 $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
2761 $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
2762 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
2763 $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
2764 $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
2765 $notify_message .= __('You can see all comments on this post here: ') . "\r\n";
2766 /* translators: 1: blog name, 2: post title */
2767 $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
2768 } elseif ('trackback' == $comment_type) {
2769 $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
2770 /* translators: 1: website name, 2: author IP, 3: author domain */
2771 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
2772 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
2773 $notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
2774 $notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n";
2775 /* translators: 1: blog name, 2: post title */
2776 $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
2777 } elseif ('pingback' == $comment_type) {
2778 $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
2779 /* translators: 1: comment author, 2: author IP, 3: author domain */
2780 $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
2781 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
2782 $notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n";
2783 $notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n";
2784 /* translators: 1: blog name, 2: post title */
2785 $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
2786 }
2787 $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
2788 $notify_message .= sprintf( __('Permalink: %s'), get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment_id ) . "\r\n";
2789 if ( EMPTY_TRASH_DAYS )
2790 $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
2791 else
2792 $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
2793 $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
2794
2795 $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
2796
2797 if ( '' == $comment->comment_author ) {
2798 $from = "From: \"$blogname\" <$wp_email>";
2799 if ( '' != $comment->comment_author_email )
2800 $reply_to = "Reply-To: $comment->comment_author_email";
2801 } else {
2802 $from = "From: \"$comment->comment_author\" <$wp_email>";
2803 if ( '' != $comment->comment_author_email )
2804 $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
2805 }
2806
2807 $message_headers = "$from\n"
2808 . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
2809
2810 if ( isset($reply_to) )
2811 $message_headers .= $reply_to . "\n";
2812
2813 $notify_message = apply_filters('comment_notification_text', $notify_message, $comment_id);
2814 $subject = apply_filters('comment_notification_subject', $subject, $comment_id);
2815 $message_headers = apply_filters('comment_notification_headers', $message_headers, $comment_id);
2816
2817 @wp_mail( $author->user_email, $subject, $notify_message, $message_headers );
2818
2819 return true;
2820}
2821endif;
2822
2823if ( !function_exists('wp_notify_moderator') ) :
2824/**
2825 * Notifies the moderator of the blog about a new comment that is awaiting approval.
2826 *
2827 * @since 1.0
2828 * @uses $wpdb
2829 *
2830 * @param int $comment_id Comment ID
2831 * @return bool Always returns true
2832 */
2833function wp_notify_moderator($comment_id) {
2834 global $wpdb;
2835
2836 if ( 0 == get_option( 'moderation_notify' ) )
2837 return true;
2838
2839 $comment = get_comment($comment_id);
2840 $post = get_post($comment->comment_post_ID);
2841 $user = get_userdata( $post->post_author );
2842 // Send to the administration and to the post author if the author can modify the comment.
2843 $email_to = array( get_option('admin_email') );
2844 if ( user_can($user->ID, 'edit_comment', $comment_id) && !empty($user->user_email) && ( get_option('admin_email') != $user->user_email) )
2845 $email_to[] = $user->user_email;
2846
2847 $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
2848 $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
2849
2850 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
2851 // we want to reverse this for the plain text arena of emails.
2852 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
2853
2854 switch ($comment->comment_type)
2855 {
2856 case 'trackback':
2857 $notify_message = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
2858 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
2859 $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
2860 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
2861 $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
2862 break;
2863 case 'pingback':
2864 $notify_message = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
2865 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
2866 $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
2867 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
2868 $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
2869 break;
2870 default: //Comments
2871 $notify_message = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
2872 $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
2873 $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
2874 $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
2875 $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
2876 $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
2877 $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
2878 break;
2879 }
2880
2881 $notify_message .= sprintf( __('Approve it: %s'), admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n";
2882 if ( EMPTY_TRASH_DAYS )
2883 $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
2884 else
2885 $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
2886 $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
2887
2888 $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
2889 'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
2890 $notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n";
2891
2892 $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
2893 $message_headers = '';
2894
2895 $notify_message = apply_filters('comment_moderation_text', $notify_message, $comment_id);
2896 $subject = apply_filters('comment_moderation_subject', $subject, $comment_id);
2897 $message_headers = apply_filters('comment_moderation_headers', $message_headers);
2898
2899 foreach ( $email_to as $email )
2900 @wp_mail($email, $subject, $notify_message, $message_headers);
2901
2902 return true;
2903}
2904endif;
2905
2906if ( !function_exists('wp_password_change_notification') ) :
2907/**
2908 * Notify the blog admin of a user changing password, normally via email.
2909 *
2910 * @since 2.7
2911 *
2912 * @param object $user User Object
2913 */
2914function wp_password_change_notification(&$user) {
2915 // send a copy of password change notification to the admin
2916 // but check to see if it's the admin whose password we're changing, and skip this
2917 if ( $user->user_email != get_option('admin_email') ) {
2918 $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
2919 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
2920 // we want to reverse this for the plain text arena of emails.
2921 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
2922 wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message);
2923 }
2924}
2925endif;
2926
2927if ( !function_exists('wp_new_user_notification') ) :
2928/**
2929 * Notify the blog admin of a new user, normally via email.
2930 *
2931 * @since 2.0
2932 *
2933 * @param int $user_id User ID
2934 * @param string $plaintext_pass Optional. The user's plaintext password
2935 */
2936function wp_new_user_notification($user_id, $plaintext_pass = '') {
2937 $user = new WP_User($user_id);
2938
2939 $user_login = stripslashes($user->user_login);
2940 $user_email = stripslashes($user->user_email);
2941
2942 // The blogname option is escaped with esc_html on the way into the database in sanitize_option
2943 // we want to reverse this for the plain text arena of emails.
2944 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
2945
2946 $message = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
2947 $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
2948 $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";
2949
2950 @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
2951
2952 if ( empty($plaintext_pass) )
2953 return;
2954
2955 $message = sprintf(__('Username: %s'), $user_login) . "\r\n";
2956 $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
2957 $message .= wp_login_url() . "\r\n";
2958
2959 wp_mail($user_email, sprintf(__('[%s] Your username and password'), $blogname), $message);
2960
2961}
2962endif;
2963
2964if ( !function_exists('wp_nonce_tick') ) :
2965/**
2966 * Get the time-dependent variable for nonce creation.
2967 *
2968 * A nonce has a lifespan of two ticks. Nonces in their second tick may be
2969 * updated, e.g. by autosave.
2970 *
2971 * @since 2.5
2972 *
2973 * @return int
2974 */
2975function wp_nonce_tick() {
2976 $nonce_life = apply_filters('nonce_life', 86400);
2977
2978 return ceil(time() / ( $nonce_life / 2 ));
2979}
2980endif;
2981
2982if ( !function_exists('wp_verify_nonce') ) :
2983/**
2984 * Verify that correct nonce was used with time limit.
2985 *
2986 * The user is given an amount of time to use the token, so therefore, since the
2987 * UID and $action remain the same, the independent variable is the time.
2988 *
2989 * @since 2.0.3
2990 *
2991 * @param string $nonce Nonce that was used in the form to verify
2992 * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
2993 * @return bool Whether the nonce check passed or failed.
2994 */
2995function wp_verify_nonce($nonce, $action = -1) {
2996 $user = wp_get_current_user();
2997 $uid = (int) $user->ID;
2998
2999 $i = wp_nonce_tick();
3000
3001 // Nonce generated 0-12 hours ago
3002 if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce )
3003 return 1;
3004 // Nonce generated 12-24 hours ago
3005 if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce )
3006 return 2;
3007 // Invalid nonce
3008 return false;
3009}
3010endif;
3011
3012if ( !function_exists('wp_create_nonce') ) :
3013/**
3014 * Creates a random, one time use token.
3015 *
3016 * @since 2.0.3
3017 *
3018 * @param string|int $action Scalar value to add context to the nonce.
3019 * @return string The one use form token
3020 */
3021function wp_create_nonce($action = -1) {
3022 $user = wp_get_current_user();
3023 $uid = (int) $user->ID;
3024
3025 $i = wp_nonce_tick();
3026
3027 return substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10);
3028}
3029endif;
3030
3031if ( !function_exists('wp_salt') ) :
3032/**
3033 * Get salt to add to hashes.
3034 *
3035 * Salts are created using secret keys. Secret keys are located in two places:
3036 * in the database and in the wp-config.php file. The secret key in the database
3037 * is randomly generated and will be appended to the secret keys in wp-config.php.
3038 *
3039 * The secret keys in wp-config.php should be updated to strong, random keys to maximize
3040 * security. Below is an example of how the secret key constants are defined.
3041 * Do not paste this example directly into wp-config.php. Instead, have a
3042 * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
3043 * for you.
3044 *
3045 * <code>
3046 * define('AUTH_KEY', ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
3047 * define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
3048 * define('LOGGED_IN_KEY', '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
3049 * define('NONCE_KEY', '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
3050 * define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
3051 * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
3052 * define('LOGGED_IN_SALT', '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
3053 * define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
3054 * </code>
3055 *
3056 * Salting passwords helps against tools which has stored hashed values of
3057 * common dictionary strings. The added values makes it harder to crack.
3058 *
3059 * @since 2.5
3060 *
3061 * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
3062 *
3063 * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
3064 * @return string Salt value
3065 */
3066function wp_salt( $scheme = 'auth' ) {
3067 static $cached_salts = array();
3068 if ( isset( $cached_salts[ $scheme ] ) )
3069 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
3070
3071 static $duplicated_keys;
3072 if ( null === $duplicated_keys ) {
3073 $duplicated_keys = array( 'put your unique phrase here' => true );
3074 foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
3075 foreach ( array( 'KEY', 'SALT' ) as $second ) {
3076 if ( ! defined( "{$first}_{$second}" ) )
3077 continue;
3078 $value = constant( "{$first}_{$second}" );
3079 $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
3080 }
3081 }
3082 }
3083
3084 $key = $salt = '';
3085 if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) )
3086 $key = SECRET_KEY;
3087 if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) )
3088 $salt = SECRET_SALT;
3089
3090 if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) {
3091 foreach ( array( 'key', 'salt' ) as $type ) {
3092 $const = strtoupper( "{$scheme}_{$type}" );
3093 if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
3094 $$type = constant( $const );
3095 } elseif ( ! $$type ) {
3096 $$type = get_site_option( "{$scheme}_{$type}" );
3097 if ( ! $$type ) {
3098 $$type = wp_generate_password( 64, true, true );
3099 update_site_option( "{$scheme}_{$type}", $$type );
3100 }
3101 }
3102 }
3103 } else {
3104 if ( ! $key ) {
3105 $key = get_site_option( 'secret_key' );
3106 if ( ! $key ) {
3107 $key = wp_generate_password( 64, true, true );
3108 update_site_option( 'secret_key', $key );
3109 }
3110 }
3111 $salt = hash_hmac( 'md5', $scheme, $key );
3112 }
3113
3114 $cached_salts[ $scheme ] = $key . $salt;
3115 return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
3116}
3117endif;
3118
3119if ( !function_exists('wp_hash') ) :
3120/**
3121 * Get hash of given string.
3122 *
3123 * @since 2.0.3
3124 * @uses wp_salt() Get WordPress salt
3125 *
3126 * @param string $data Plain text to hash
3127 * @return string Hash of $data
3128 */
3129function wp_hash($data, $scheme = 'auth') {
3130 $salt = wp_salt($scheme);
3131
3132 return hash_hmac('md5', $data, $salt);
3133}
3134endif;
3135
3136if ( !function_exists('wp_hash_password') ) :
3137/**
3138 * Create a hash (encrypt) of a plain text password.
3139 *
3140 * For integration with other applications, this function can be overwritten to
3141 * instead use the other package password checking algorithm.
3142 *
3143 * @since 2.5
3144 * @global object $wp_hasher PHPass object
3145 * @uses PasswordHash::HashPassword
3146 *
3147 * @param string $password Plain text user password to hash
3148 * @return string The hash string of the password
3149 */
3150function wp_hash_password($password) {
3151 global $wp_hasher;
3152
3153 if ( empty($wp_hasher) ) {
3154 require_once( ABSPATH . 'wp-includes/class-phpass.php');
3155 // By default, use the portable hash from phpass
3156 $wp_hasher = new PasswordHash(8, true);
3157 }
3158
3159 return $wp_hasher->HashPassword($password);
3160}
3161endif;
3162
3163if ( !function_exists('wp_check_password') ) :
3164/**
3165 * Checks the plaintext password against the encrypted Password.
3166 *
3167 * Maintains compatibility between old version and the new cookie authentication
3168 * protocol using PHPass library. The $hash parameter is the encrypted password
3169 * and the function compares the plain text password when encrypted similarly
3170 * against the already encrypted password to see if they match.
3171 *
3172 * For integration with other applications, this function can be overwritten to
3173 * instead use the other package password checking algorithm.
3174 *
3175 * @since 2.5
3176 * @global object $wp_hasher PHPass object used for checking the password
3177 * against the $hash + $password
3178 * @uses PasswordHash::CheckPassword
3179 *
3180 * @param string $password Plaintext user's password
3181 * @param string $hash Hash of the user's password to check against.
3182 * @return bool False, if the $password does not match the hashed password
3183 */
3184function wp_check_password($password, $hash, $user_id = '') {
3185 global $wp_hasher;
3186
3187 // If the hash is still md5...
3188 if ( strlen($hash) <= 32 ) {
3189 $check = ( $hash == md5($password) );
3190 if ( $check && $user_id ) {
3191 // Rehash using new hash.
3192 wp_set_password($password, $user_id);
3193 $hash = wp_hash_password($password);
3194 }
3195
3196 return apply_filters('check_password', $check, $password, $hash, $user_id);
3197 }
3198
3199 // If the stored hash is longer than an MD5, presume the
3200 // new style phpass portable hash.
3201 if ( empty($wp_hasher) ) {
3202 require_once( ABSPATH . 'wp-includes/class-phpass.php');
3203 // By default, use the portable hash from phpass
3204 $wp_hasher = new PasswordHash(8, true);
3205 }
3206
3207 $check = $wp_hasher->CheckPassword($password, $hash);
3208
3209 return apply_filters('check_password', $check, $password, $hash, $user_id);
3210}
3211endif;
3212
3213if ( !function_exists('wp_generate_password') ) :
3214/**
3215 * Generates a random password drawn from the defined set of characters.
3216 *
3217 * @since 2.5
3218 *
3219 * @param int $length The length of password to generate
3220 * @param bool $special_chars Whether to include standard special characters. Default true.
3221 * @param bool $extra_special_chars Whether to include other special characters. Used when
3222 * generating secret keys and salts. Default false.
3223 * @return string The random password
3224 **/
3225function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
3226 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
3227 if ( $special_chars )
3228 $chars .= '!@#$%^&*()';
3229 if ( $extra_special_chars )
3230 $chars .= '-_ []{}<>~`+=,.;:/?|';
3231
3232 $password = '';
3233 for ( $i = 0; $i < $length; $i++ ) {
3234 $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
3235 }
3236
3237 // random_password filter was previously in random_password function which was deprecated
3238 return apply_filters('random_password', $password);
3239}
3240endif;
3241
3242if ( !function_exists('wp_rand') ) :
3243 /**
3244 * Generates a random number
3245 *
3246 * @since 2.6.2
3247 *
3248 * @param int $min Lower limit for the generated number (optional, default is 0)
3249 * @param int $max Upper limit for the generated number (optional, default is 4294967295)
3250 * @return int A random number between min and max
3251 */
3252function wp_rand( $min = 0, $max = 0 ) {
3253 global $rnd_value;
3254
3255 // Reset $rnd_value after 14 uses
3256 // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
3257 if ( strlen($rnd_value) < 8 ) {
3258 if ( defined( 'WP_SETUP_CONFIG' ) )
3259 static $seed = '';
3260 else
3261 $seed = get_transient('random_seed');
3262 $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
3263 $rnd_value .= sha1($rnd_value);
3264 $rnd_value .= sha1($rnd_value . $seed);
3265 $seed = md5($seed . $rnd_value);
3266 if ( ! defined( 'WP_SETUP_CONFIG' ) )
3267 set_transient('random_seed', $seed);
3268 }
3269
3270 // Take the first 8 digits for our value
3271 $value = substr($rnd_value, 0, 8);
3272
3273 // Strip the first eight, leaving the remainder for the next call to wp_rand().
3274 $rnd_value = substr($rnd_value, 8);
3275
3276 $value = abs(hexdec($value));
3277
3278 // Reduce the value to be within the min - max range
3279 // 4294967295 = 0xffffffff = max random number
3280 if ( $max != 0 )
3281 $value = $min + (($max - $min + 1) * ($value / (4294967295 + 1)));
3282
3283 return abs(intval($value));
3284}
3285endif;
3286
3287if ( !function_exists('wp_set_password') ) :
3288/**
3289 * Updates the user's password with a new encrypted one.
3290 *
3291 * For integration with other applications, this function can be overwritten to
3292 * instead use the other package password checking algorithm.
3293 *
3294 * @since 2.5
3295 * @uses $wpdb WordPress database object for queries
3296 * @uses wp_hash_password() Used to encrypt the user's password before passing to the database
3297 *
3298 * @param string $password The plaintext new user password
3299 * @param int $user_id User ID
3300 */
3301function wp_set_password( $password, $user_id ) {
3302 global $wpdb;
3303
3304 $hash = wp_hash_password($password);
3305 $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
3306
3307 wp_cache_delete($user_id, 'users');
3308}
3309endif;
3310
3311if ( !function_exists( 'get_avatar' ) ) :
3312/**
3313 * Retrieve the avatar for a user who provided a user ID or email address.
3314 *
3315 * @since 2.5
3316 * @param int|string|object $id_or_email A user ID, email address, or comment object
3317 * @param int $size Size of the avatar image
3318 * @param string $default URL to a default image to use if no avatar is available
3319 * @param string $alt Alternate text to use in image tag. Defaults to blank
3320 * @return string <img> tag for the user's avatar
3321*/
3322function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
3323 if ( ! get_option('show_avatars') )
3324 return false;
3325
3326 if ( false === $alt)
3327 $safe_alt = '';
3328 else
3329 $safe_alt = esc_attr( $alt );
3330
3331 if ( !is_numeric($size) )
3332 $size = '96';
3333
3334 $email = '';
3335 if ( is_numeric($id_or_email) ) {
3336 $id = (int) $id_or_email;
3337 $user = get_userdata($id);
3338 if ( $user )
3339 $email = $user->user_email;
3340 } elseif ( is_object($id_or_email) ) {
3341 // No avatar for pingbacks or trackbacks
3342 $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
3343 if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
3344 return false;
3345
3346 if ( !empty($id_or_email->user_id) ) {
3347 $id = (int) $id_or_email->user_id;
3348 $user = get_userdata($id);
3349 if ( $user)
3350 $email = $user->user_email;
3351 } elseif ( !empty($id_or_email->comment_author_email) ) {
3352 $email = $id_or_email->comment_author_email;
3353 }
3354 } else {
3355 $email = $id_or_email;
3356 }
3357
3358 if ( empty($default) ) {
3359 $avatar_default = get_option('avatar_default');
3360 if ( empty($avatar_default) )
3361 $default = 'mystery';
3362 else
3363 $default = $avatar_default;
3364 }
3365
3366 if ( !empty($email) )
3367 $email_hash = md5( strtolower( trim( $email ) ) );
3368
3369 if ( is_ssl() ) {
3370 $host = 'https://secure.gravatar.com';
3371 } else {
3372 if ( !empty($email) )
3373 $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) );
3374 else
3375 $host = 'http://0.gravatar.com';
3376 }
3377
3378 if ( 'mystery' == $default )
3379 $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
3380 elseif ( 'blank' == $default )
3381 $default = includes_url('images/blank.gif');
3382 elseif ( !empty($email) && 'gravatar_default' == $default )
3383 $default = '';
3384 elseif ( 'gravatar_default' == $default )
3385 $default = "$host/avatar/?s={$size}";
3386 elseif ( empty($email) )
3387 $default = "$host/avatar/?d=$default&s={$size}";
3388 elseif ( strpos($default, 'http://') === 0 )
3389 $default = add_query_arg( 's', $size, $default );
3390
3391 if ( !empty($email) ) {
3392 $out = "$host/avatar/";
3393 $out .= $email_hash;
3394 $out .= '?s='.$size;
3395 $out .= '&d=' . urlencode( $default );
3396
3397 $rating = get_option('avatar_rating');
3398 if ( !empty( $rating ) )
3399 $out .= "&r={$rating}";
3400
3401 $avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
3402 } else {
3403 $avatar = "<img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
3404 }
3405
3406 return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt);
3407}
3408endif;
3409
3410if ( !function_exists( 'wp_text_diff' ) ) :
3411/**
3412 * Displays a human readable HTML representation of the difference between two strings.
3413 *
3414 * The Diff is available for getting the changes between versions. The output is
3415 * HTML, so the primary use is for displaying the changes. If the two strings
3416 * are equivalent, then an empty string will be returned.
3417 *
3418 * The arguments supported and can be changed are listed below.
3419 *
3420 * 'title' : Default is an empty string. Titles the diff in a manner compatible
3421 * with the output.
3422 * 'title_left' : Default is an empty string. Change the HTML to the left of the
3423 * title.
3424 * 'title_right' : Default is an empty string. Change the HTML to the right of
3425 * the title.
3426 *
3427 * @since 2.6
3428 * @see wp_parse_args() Used to change defaults to user defined settings.
3429 * @uses Text_Diff
3430 * @uses WP_Text_Diff_Renderer_Table
3431 *
3432 * @param string $left_string "old" (left) version of string
3433 * @param string $right_string "new" (right) version of string
3434 * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
3435 * @return string Empty string if strings are equivalent or HTML with differences.
3436 */
3437function wp_text_diff( $left_string, $right_string, $args = null ) {
3438 $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
3439 $args = wp_parse_args( $args, $defaults );
3440
3441 if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
3442 require( ABSPATH . WPINC . '/wp-diff.php' );
3443
3444 $left_string = normalize_whitespace($left_string);
3445 $right_string = normalize_whitespace($right_string);
3446
3447 $left_lines = explode("\n", $left_string);
3448 $right_lines = explode("\n", $right_string);
3449
3450 $text_diff = new Text_Diff($left_lines, $right_lines);
3451 $renderer = new WP_Text_Diff_Renderer_Table();
3452 $diff = $renderer->render($text_diff);
3453
3454 if ( !$diff )
3455 return '';
3456
3457 $r = "<table class='diff'>\n";
3458 $r .= "<col class='ltype' /><col class='content' /><col class='ltype' /><col class='content' />";
3459
3460 if ( $args['title'] || $args['title_left'] || $args['title_right'] )
3461 $r .= "<thead>";
3462 if ( $args['title'] )
3463 $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
3464 if ( $args['title_left'] || $args['title_right'] ) {
3465 $r .= "<tr class='diff-sub-title'>\n";
3466 $r .= "\t<td></td><th>$args[title_left]</th>\n";
3467 $r .= "\t<td></td><th>$args[title_right]</th>\n";
3468 $r .= "</tr>\n";
3469 }
3470 if ( $args['title'] || $args['title_left'] || $args['title_right'] )
3471 $r .= "</thead>\n";
3472
3473 $r .= "<tbody>\n$diff\n</tbody>\n";
3474 $r .= "</table>";
3475
3476 return $r;
3477}
3478endif;