[ Index ]

PHP Cross Reference of Wordpress 2.7.1

title

Body

[close]

/wp-includes/ -> pluggable.php (source)

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


Generated: Mon Mar 23 16:23:02 2009 Cross-referenced by PHPXref 0.7