[ Index ]

PHP Cross Reference of WordPress 3.0 beta 1

[ Index ]     [ Variables ]     [ Functions ]     [ Classes ]     [ Constants ]     [ Statistics ]

title

Body

[close]

/wp-includes/ -> class-http.php (source)

   1  <?php
   2  /**
   3   * Simple and uniform HTTP request API.
   4   *
   5   * Will eventually replace and standardize the WordPress HTTP requests made.
   6   *
   7   * @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal
   8   *
   9   * @package WordPress
  10   * @subpackage HTTP
  11   * @since 2.7.0
  12   */
  13  
  14  /**
  15   * WordPress HTTP Class for managing HTTP Transports and making HTTP requests.
  16   *
  17   * This class is called for the functionality of making HTTP requests and should replace Snoopy
  18   * functionality, eventually. There is no available functionality to add HTTP transport
  19   * implementations, since most of the HTTP transports are added and available for use.
  20   *
  21   * The exception is that cURL is not available as a transport and lacking an implementation. It will
  22   * be added later and should be a patch on the WordPress Trac.
  23   *
  24   * There are no properties, because none are needed and for performance reasons. Some of the
  25   * functions are static and while they do have some overhead over functions in PHP4, the purpose is
  26   * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword
  27   * to the code. It is not as easy to convert a function to a method after enough code uses the old
  28   * way.
  29   *
  30   * Debugging includes several actions, which pass different variables for debugging the HTTP API.
  31   *
  32   * <strong>http_transport_get_debug</strong> - gives working, nonblocking, and blocking transports.
  33   *
  34   * <strong>http_transport_post_debug</strong> - gives working, nonblocking, and blocking transports.
  35   *
  36   * @package WordPress
  37   * @subpackage HTTP
  38   * @since 2.7.0
  39   */
  40  class WP_Http {
  41  
  42      /**
  43       * PHP4 style Constructor - Calls PHP5 Style Constructor
  44       *
  45       * @since 2.7.0
  46       * @return WP_Http
  47       */
  48  	function WP_Http() {
  49          $this->__construct();
  50      }
  51  
  52      /**
  53       * PHP5 style Constructor - Set up available transport if not available.
  54       *
  55       * PHP4 does not have the 'self' keyword and since WordPress supports PHP4,
  56       * the class needs to be used for the static call.
  57       *
  58       * The transport are set up to save time. This should only be called once, so
  59       * the overhead should be fine.
  60       *
  61       * @since 2.7.0
  62       * @return WP_Http
  63       */
  64  	function __construct() {
  65          WP_Http::_getTransport();
  66          WP_Http::_postTransport();
  67      }
  68  
  69      /**
  70       * Tests the WordPress HTTP objects for an object to use and returns it.
  71       *
  72       * Tests all of the objects and returns the object that passes. Also caches
  73       * that object to be used later.
  74       *
  75       * The order for the GET/HEAD requests are HTTP Extension, cURL, Streams, Fopen,
  76       * and finally Fsockopen. fsockopen() is used last, because it has the most
  77       * overhead in its implementation. There isn't any real way around it, since
  78       * redirects have to be supported, much the same way the other transports
  79       * also handle redirects.
  80       *
  81       * There are currently issues with "localhost" not resolving correctly with
  82       * DNS. This may cause an error "failed to open stream: A connection attempt
  83       * failed because the connected party did not properly respond after a
  84       * period of time, or established connection failed because connected host
  85       * has failed to respond."
  86       *
  87       * @since 2.7.0
  88       * @access private
  89       *
  90       * @param array $args Request args, default us an empty array
  91       * @return object|null Null if no transports are available, HTTP transport object.
  92       */
  93      function &_getTransport( $args = array() ) {
  94          static $working_transport, $blocking_transport, $nonblocking_transport;
  95  
  96          if ( is_null($working_transport) ) {
  97              if ( true === WP_Http_ExtHttp::test($args) ) {
  98                  $working_transport['exthttp'] = new WP_Http_ExtHttp();
  99                  $blocking_transport[] = &$working_transport['exthttp'];
 100              } else if ( true === WP_Http_Curl::test($args) ) {
 101                  $working_transport['curl'] = new WP_Http_Curl();
 102                  $blocking_transport[] = &$working_transport['curl'];
 103              } else if ( true === WP_Http_Streams::test($args) ) {
 104                  $working_transport['streams'] = new WP_Http_Streams();
 105                  $blocking_transport[] = &$working_transport['streams'];
 106              } else if ( true === WP_Http_Fopen::test($args) ) {
 107                  $working_transport['fopen'] = new WP_Http_Fopen();
 108                  $blocking_transport[] = &$working_transport['fopen'];
 109              } else if ( true === WP_Http_Fsockopen::test($args) ) {
 110                  $working_transport['fsockopen'] = new WP_Http_Fsockopen();
 111                  $blocking_transport[] = &$working_transport['fsockopen'];
 112              }
 113  
 114              foreach ( array('curl', 'streams', 'fopen', 'fsockopen', 'exthttp') as $transport ) {
 115                  if ( isset($working_transport[$transport]) )
 116                      $nonblocking_transport[] = &$working_transport[$transport];
 117              }
 118          }
 119  
 120          do_action( 'http_transport_get_debug', $working_transport, $blocking_transport, $nonblocking_transport );
 121  
 122          if ( isset($args['blocking']) && !$args['blocking'] )
 123              return $nonblocking_transport;
 124          else
 125              return $blocking_transport;
 126      }
 127  
 128      /**
 129       * Tests the WordPress HTTP objects for an object to use and returns it.
 130       *
 131       * Tests all of the objects and returns the object that passes. Also caches
 132       * that object to be used later. This is for posting content to a URL and
 133       * is used when there is a body. The plain Fopen Transport can not be used
 134       * to send content, but the streams transport can. This is a limitation that
 135       * is addressed here, by just not including that transport.
 136       *
 137       * @since 2.7.0
 138       * @access private
 139       *
 140       * @param array $args Request args, default us an empty array
 141       * @return object|null Null if no transports are available, HTTP transport object.
 142       */
 143      function &_postTransport( $args = array() ) {
 144          static $working_transport, $blocking_transport, $nonblocking_transport;
 145  
 146          if ( is_null($working_transport) ) {
 147              if ( true === WP_Http_ExtHttp::test($args) ) {
 148                  $working_transport['exthttp'] = new WP_Http_ExtHttp();
 149                  $blocking_transport[] = &$working_transport['exthttp'];
 150              } else if ( true === WP_Http_Curl::test($args) ) {
 151                  $working_transport['curl'] = new WP_Http_Curl();
 152                  $blocking_transport[] = &$working_transport['curl'];
 153              } else if ( true === WP_Http_Streams::test($args) ) {
 154                  $working_transport['streams'] = new WP_Http_Streams();
 155                  $blocking_transport[] = &$working_transport['streams'];
 156              } else if ( true === WP_Http_Fsockopen::test($args) ) {
 157                  $working_transport['fsockopen'] = new WP_Http_Fsockopen();
 158                  $blocking_transport[] = &$working_transport['fsockopen'];
 159              }
 160  
 161              foreach ( array('curl', 'streams', 'fsockopen', 'exthttp') as $transport ) {
 162                  if ( isset($working_transport[$transport]) )
 163                      $nonblocking_transport[] = &$working_transport[$transport];
 164              }
 165          }
 166  
 167          do_action( 'http_transport_post_debug', $working_transport, $blocking_transport, $nonblocking_transport );
 168  
 169          if ( isset($args['blocking']) && !$args['blocking'] )
 170              return $nonblocking_transport;
 171          else
 172              return $blocking_transport;
 173      }
 174  
 175      /**
 176       * Send a HTTP request to a URI.
 177       *
 178       * The body and headers are part of the arguments. The 'body' argument is for the body and will
 179       * accept either a string or an array. The 'headers' argument should be an array, but a string
 180       * is acceptable. If the 'body' argument is an array, then it will automatically be escaped
 181       * using http_build_query().
 182       *
 183       * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS
 184       * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send
 185       * headers. Other protocols are unsupported and most likely will fail.
 186       *
 187       * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
 188       * 'user-agent'.
 189       *
 190       * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow
 191       * others, but should not be assumed. The 'timeout' is used to sent how long the connection
 192       * should stay open before failing when no response. 'redirection' is used to track how many
 193       * redirects were taken and used to sent the amount for other transports, but not all transports
 194       * accept setting that value.
 195       *
 196       * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and
 197       * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The
 198       * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is
 199       * 'WordPress/WP_Version', where WP_Version is the value from $wp_version.
 200       *
 201       * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP
 202       * while it performs the request or continue regardless. Actually, that isn't entirely correct.
 203       * Blocking mode really just means whether the fread should just pull what it can whenever it
 204       * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading
 205       * the entire content. It doesn't actually always mean that PHP will continue going after making
 206       * the request.
 207       *
 208       * @access public
 209       * @since 2.7.0
 210       * @todo Refactor this code. The code in this method extends the scope of its original purpose
 211       *        and should be refactored to allow for cleaner abstraction and reduce duplication of the
 212       *        code. One suggestion is to create a class specifically for the arguments, however
 213       *        preliminary refactoring to this affect has affect more than just the scope of the
 214       *        arguments. Something to ponder at least.
 215       *
 216       * @param string $url URI resource.
 217       * @param str|array $args Optional. Override the defaults.
 218       * @return array containing 'headers', 'body', 'response', 'cookies'
 219       */
 220  	function request( $url, $args = array() ) {
 221          global $wp_version;
 222  
 223          $defaults = array(
 224              'method' => 'GET',
 225              'timeout' => apply_filters( 'http_request_timeout', 5),
 226              'redirection' => apply_filters( 'http_request_redirection_count', 5),
 227              'httpversion' => apply_filters( 'http_request_version', '1.0'),
 228              'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' )  ),
 229              'blocking' => true,
 230              'headers' => array(),
 231              'cookies' => array(),
 232              'body' => null,
 233              'compress' => false,
 234              'decompress' => true,
 235              'sslverify' => true
 236          );
 237  
 238          $r = wp_parse_args( $args, $defaults );
 239          $r = apply_filters( 'http_request_args', $r, $url );
 240  
 241          // Allow plugins to short-circuit the request
 242          $pre = apply_filters( 'pre_http_request', false, $r, $url );
 243          if ( false !== $pre )
 244              return $pre;
 245  
 246          $arrURL = parse_url($url);
 247  
 248          if ( $this->block_request( $url ) )
 249              return new WP_Error('http_request_failed', __('User has blocked requests through HTTP.'));
 250  
 251          // Determine if this is a https call and pass that on to the transport functions
 252          // so that we can blacklist the transports that do not support ssl verification
 253          $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
 254  
 255          // Determine if this request is to OUR install of WordPress
 256          $homeURL = parse_url(get_bloginfo('url'));
 257          $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
 258          unset($homeURL);
 259  
 260          if ( is_null( $r['headers'] ) )
 261              $r['headers'] = array();
 262  
 263          if ( ! is_array($r['headers']) ) {
 264              $processedHeaders = WP_Http::processHeaders($r['headers']);
 265              $r['headers'] = $processedHeaders['headers'];
 266          }
 267  
 268          if ( isset($r['headers']['User-Agent']) ) {
 269              $r['user-agent'] = $r['headers']['User-Agent'];
 270              unset($r['headers']['User-Agent']);
 271          }
 272  
 273          if ( isset($r['headers']['user-agent']) ) {
 274              $r['user-agent'] = $r['headers']['user-agent'];
 275              unset($r['headers']['user-agent']);
 276          }
 277  
 278          // Construct Cookie: header if any cookies are set
 279          WP_Http::buildCookieHeader( $r );
 280  
 281          if ( WP_Http_Encoding::is_available() )
 282              $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding();
 283  
 284          if ( empty($r['body']) ) {
 285              // Some servers fail when sending content without the content-length header being set.
 286              // Also, to fix another bug, we only send when doing POST and PUT and the content-length
 287              // header isn't already set.
 288              if( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset($r['headers']['Content-Length']) )
 289                  $r['headers']['Content-Length'] = 0;
 290  
 291              // The method is ambiguous, because we aren't talking about HTTP methods, the "get" in
 292              // this case is simply that we aren't sending any bodies and to get the transports that
 293              // don't support sending bodies along with those which do.
 294              $transports = WP_Http::_getTransport($r);
 295          } else {
 296              if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
 297                  if ( ! version_compare(phpversion(), '5.1.2', '>=') )
 298                      $r['body'] = _http_build_query($r['body'], null, '&');
 299                  else
 300                      $r['body'] = http_build_query($r['body'], null, '&');
 301                  $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset');
 302                  $r['headers']['Content-Length'] = strlen($r['body']);
 303              }
 304  
 305              if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
 306                  $r['headers']['Content-Length'] = strlen($r['body']);
 307  
 308              // The method is ambiguous, because we aren't talking about HTTP methods, the "post" in
 309              // this case is simply that we are sending HTTP body and to get the transports that do
 310              // support sending the body. Not all do, depending on the limitations of the PHP core
 311              // limitations.
 312              $transports = WP_Http::_postTransport($r);
 313          }
 314  
 315          do_action( 'http_api_debug', $transports, 'transports_list' );
 316  
 317          $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
 318          foreach ( (array) $transports as $transport ) {
 319              $response = $transport->request($url, $r);
 320  
 321              do_action( 'http_api_debug', $response, 'response', get_class($transport) );
 322  
 323              if ( ! is_wp_error($response) )
 324                  return apply_filters( 'http_response', $response, $r, $url );
 325          }
 326  
 327          return $response;
 328      }
 329  
 330      /**
 331       * Uses the POST HTTP method.
 332       *
 333       * Used for sending data that is expected to be in the body.
 334       *
 335       * @access public
 336       * @since 2.7.0
 337       *
 338       * @param string $url URI resource.
 339       * @param str|array $args Optional. Override the defaults.
 340       * @return boolean
 341       */
 342  	function post($url, $args = array()) {
 343          $defaults = array('method' => 'POST');
 344          $r = wp_parse_args( $args, $defaults );
 345          return $this->request($url, $r);
 346      }
 347  
 348      /**
 349       * Uses the GET HTTP method.
 350       *
 351       * Used for sending data that is expected to be in the body.
 352       *
 353       * @access public
 354       * @since 2.7.0
 355       *
 356       * @param string $url URI resource.
 357       * @param str|array $args Optional. Override the defaults.
 358       * @return boolean
 359       */
 360  	function get($url, $args = array()) {
 361          $defaults = array('method' => 'GET');
 362          $r = wp_parse_args( $args, $defaults );
 363          return $this->request($url, $r);
 364      }
 365  
 366      /**
 367       * Uses the HEAD HTTP method.
 368       *
 369       * Used for sending data that is expected to be in the body.
 370       *
 371       * @access public
 372       * @since 2.7.0
 373       *
 374       * @param string $url URI resource.
 375       * @param str|array $args Optional. Override the defaults.
 376       * @return boolean
 377       */
 378  	function head($url, $args = array()) {
 379          $defaults = array('method' => 'HEAD');
 380          $r = wp_parse_args( $args, $defaults );
 381          return $this->request($url, $r);
 382      }
 383  
 384      /**
 385       * Parses the responses and splits the parts into headers and body.
 386       *
 387       * @access public
 388       * @static
 389       * @since 2.7.0
 390       *
 391       * @param string $strResponse The full response string
 392       * @return array Array with 'headers' and 'body' keys.
 393       */
 394  	function processResponse($strResponse) {
 395          $res = explode("\r\n\r\n", $strResponse, 2);
 396          
 397          return array('headers' => isset($res[0]) ? $res[0] : array(), 'body' => isset($res[1]) ? $res[1] : '');
 398      }
 399  
 400      /**
 401       * Transform header string into an array.
 402       *
 403       * If an array is given then it is assumed to be raw header data with numeric keys with the
 404       * headers as the values. No headers must be passed that were already processed.
 405       *
 406       * @access public
 407       * @static
 408       * @since 2.7.0
 409       *
 410       * @param string|array $headers
 411       * @return array Processed string headers. If duplicate headers are encountered,
 412       *                     Then a numbered array is returned as the value of that header-key.
 413       */
 414  	function processHeaders($headers) {
 415          // split headers, one per array element
 416          if ( is_string($headers) ) {
 417              // tolerate line terminator: CRLF = LF (RFC 2616 19.3)
 418              $headers = str_replace("\r\n", "\n", $headers);
 419              // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
 420              $headers = preg_replace('/\n[ \t]/', ' ', $headers);
 421              // create the headers array
 422              $headers = explode("\n", $headers);
 423          }
 424  
 425          $response = array('code' => 0, 'message' => '');
 426  
 427          // If a redirection has taken place, The headers for each page request may have been passed.
 428          // In this case, determine the final HTTP header and parse from there.
 429          for ( $i = count($headers)-1; $i >= 0; $i-- ) {
 430              if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
 431                  $headers = array_splice($headers, $i);
 432                  break;
 433              }
 434          }
 435  
 436          $cookies = array();
 437          $newheaders = array();
 438          foreach ( $headers as $tempheader ) {
 439              if ( empty($tempheader) )
 440                  continue;
 441  
 442              if ( false === strpos($tempheader, ':') ) {
 443                  list( , $response['code'], $response['message']) = explode(' ', $tempheader, 3);
 444                  continue;
 445              }
 446  
 447              list($key, $value) = explode(':', $tempheader, 2);
 448  
 449              if ( !empty( $value ) ) {
 450                  $key = strtolower( $key );
 451                  if ( isset( $newheaders[$key] ) ) {
 452                      if ( !is_array($newheaders[$key]) )
 453                          $newheaders[$key] = array($newheaders[$key]);
 454                      $newheaders[$key][] = trim( $value );
 455                  } else {
 456                      $newheaders[$key] = trim( $value );
 457                  }
 458                  if ( 'set-cookie' == strtolower( $key ) )
 459                      $cookies[] = new WP_Http_Cookie( $value );
 460              }
 461          }
 462  
 463          return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
 464      }
 465  
 466      /**
 467       * Takes the arguments for a ::request() and checks for the cookie array.
 468       *
 469       * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
 470       * into strings and added to the Cookie: header (within the arguments array). Edits the array by
 471       * reference.
 472       *
 473       * @access public
 474       * @version 2.8.0
 475       * @static
 476       *
 477       * @param array $r Full array of args passed into ::request()
 478       */
 479  	function buildCookieHeader( &$r ) {
 480          if ( ! empty($r['cookies']) ) {
 481              $cookies_header = '';
 482              foreach ( (array) $r['cookies'] as $cookie ) {
 483                  $cookies_header .= $cookie->getHeaderValue() . '; ';
 484              }
 485              $cookies_header = substr( $cookies_header, 0, -2 );
 486              $r['headers']['cookie'] = $cookies_header;
 487          }
 488      }
 489  
 490      /**
 491       * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
 492       *
 493       * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
 494       * returning footer headers. Shouldn't be too difficult to support it though.
 495       *
 496       * @todo Add support for footer chunked headers.
 497       * @access public
 498       * @since 2.7.0
 499       * @static
 500       *
 501       * @param string $body Body content
 502       * @return string Chunked decoded body on success or raw body on failure.
 503       */
 504  	function chunkTransferDecode($body) {
 505          $body = str_replace(array("\r\n", "\r"), "\n", $body);
 506          // The body is not chunked encoding or is malformed.
 507          if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
 508              return $body;
 509  
 510          $parsedBody = '';
 511          //$parsedHeaders = array(); Unsupported
 512  
 513          while ( true ) {
 514              $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
 515  
 516              if ( $hasChunk ) {
 517                  if ( empty( $match[1] ) )
 518                      return $body;
 519  
 520                  $length = hexdec( $match[1] );
 521                  $chunkLength = strlen( $match[0] );
 522  
 523                  $strBody = substr($body, $chunkLength, $length);
 524                  $parsedBody .= $strBody;
 525  
 526                  $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
 527  
 528                  if ( "0" == trim($body) )
 529                      return $parsedBody; // Ignore footer headers.
 530              } else {
 531                  return $body;
 532              }
 533          }
 534      }
 535  
 536      /**
 537       * Block requests through the proxy.
 538       *
 539       * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
 540       * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
 541       *
 542       * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
 543       * file and this will only allow localhost and your blog to make requests. The constant
 544       * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
 545       * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow.
 546       *
 547       * @since 2.8.0
 548       * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
 549       *
 550       * @param string $uri URI of url.
 551       * @return bool True to block, false to allow.
 552       */
 553  	function block_request($uri) {
 554          // We don't need to block requests, because nothing is blocked.
 555          if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
 556              return false;
 557  
 558          // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
 559          // This will be displayed on blogs, which is not reasonable.
 560          $check = @parse_url($uri);
 561  
 562          /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
 563           *
 564           * This isn't very security sound. There are instances where a hacker might attempt
 565           * to bypass the proxy and this check. However, the reason for this behavior is that
 566           * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
 567           * the default unsecure nature of the HTTP request.
 568           */
 569          if ( $check === false )
 570              return false;
 571  
 572          $home = parse_url( get_option('siteurl') );
 573  
 574          // Don't block requests back to ourselves by default
 575          if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
 576              return apply_filters('block_local_requests', false);
 577  
 578          if ( !defined('WP_ACCESSIBLE_HOSTS') )
 579              return true;
 580  
 581          static $accessible_hosts;
 582          if ( null == $accessible_hosts )
 583              $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
 584  
 585          return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
 586      }
 587  }
 588  
 589  /**
 590   * HTTP request method uses fsockopen function to retrieve the url.
 591   *
 592   * This would be the preferred method, but the fsockopen implementation has the most overhead of all
 593   * the HTTP transport implementations.
 594   *
 595   * @package WordPress
 596   * @subpackage HTTP
 597   * @since 2.7.0
 598   */
 599  class WP_Http_Fsockopen {
 600      /**
 601       * Send a HTTP request to a URI using fsockopen().
 602       *
 603       * Does not support non-blocking mode.
 604       *
 605       * @see WP_Http::request For default options descriptions.
 606       *
 607       * @since 2.7
 608       * @access public
 609       * @param string $url URI resource.
 610       * @param str|array $args Optional. Override the defaults.
 611       * @return array 'headers', 'body', 'cookies' and 'response' keys.
 612       */
 613  	function request($url, $args = array()) {
 614          $defaults = array(
 615              'method' => 'GET', 'timeout' => 5,
 616              'redirection' => 5, 'httpversion' => '1.0',
 617              'blocking' => true,
 618              'headers' => array(), 'body' => null, 'cookies' => array()
 619          );
 620  
 621          $r = wp_parse_args( $args, $defaults );
 622  
 623          if ( isset($r['headers']['User-Agent']) ) {
 624              $r['user-agent'] = $r['headers']['User-Agent'];
 625              unset($r['headers']['User-Agent']);
 626          } else if( isset($r['headers']['user-agent']) ) {
 627              $r['user-agent'] = $r['headers']['user-agent'];
 628              unset($r['headers']['user-agent']);
 629          }
 630  
 631          // Construct Cookie: header if any cookies are set
 632          WP_Http::buildCookieHeader( $r );
 633  
 634          $iError = null; // Store error number
 635          $strError = null; // Store error string
 636  
 637          $arrURL = parse_url($url);
 638  
 639          $fsockopen_host = $arrURL['host'];
 640  
 641          $secure_transport = false;
 642  
 643          if ( ! isset( $arrURL['port'] ) ) {
 644              if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
 645                  $fsockopen_host = "ssl://$fsockopen_host";
 646                  $arrURL['port'] = 443;
 647                  $secure_transport = true;
 648              } else {
 649                  $arrURL['port'] = 80;
 650              }
 651          }
 652  
 653          //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
 654          // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
 655          if ( 'localhost' == strtolower($fsockopen_host) )
 656              $fsockopen_host = '127.0.0.1';
 657  
 658          // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
 659          // ignored and should be ignored.
 660          if ( true === $secure_transport )
 661              $error_reporting = error_reporting(0);
 662  
 663          $startDelay = time();
 664  
 665          $proxy = new WP_HTTP_Proxy();
 666  
 667          if ( !WP_DEBUG ) {
 668              if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 669                  $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
 670              else
 671                  $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
 672          } else {
 673              if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 674                  $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
 675              else
 676                  $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
 677          }
 678  
 679          $endDelay = time();
 680  
 681          // If the delay is greater than the timeout then fsockopen should't be used, because it will
 682          // cause a long delay.
 683          $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
 684          if ( true === $elapseDelay )
 685              add_option( 'disable_fsockopen', $endDelay, null, true );
 686  
 687          if ( false === $handle )
 688              return new WP_Error('http_request_failed', $iError . ': ' . $strError);
 689  
 690          $timeout = (int) floor( $r['timeout'] );
 691          $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
 692          stream_set_timeout( $handle, $timeout, $utimeout );
 693  
 694          if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
 695              $requestPath = $url;
 696          else
 697              $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
 698  
 699          if ( empty($requestPath) )
 700              $requestPath .= '/';
 701  
 702          $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
 703  
 704          if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 705              $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
 706          else
 707              $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
 708  
 709          if ( isset($r['user-agent']) )
 710              $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
 711  
 712          if ( is_array($r['headers']) ) {
 713              foreach ( (array) $r['headers'] as $header => $headerValue )
 714                  $strHeaders .= $header . ': ' . $headerValue . "\r\n";
 715          } else {
 716              $strHeaders .= $r['headers'];
 717          }
 718  
 719          if ( $proxy->use_authentication() )
 720              $strHeaders .= $proxy->authentication_header() . "\r\n";
 721  
 722          $strHeaders .= "\r\n";
 723  
 724          if ( ! is_null($r['body']) )
 725              $strHeaders .= $r['body'];
 726  
 727          fwrite($handle, $strHeaders);
 728  
 729          if ( ! $r['blocking'] ) {
 730              fclose($handle);
 731              return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
 732          }
 733  
 734          $strResponse = '';
 735          while ( ! feof($handle) )
 736              $strResponse .= fread($handle, 4096);
 737  
 738          fclose($handle);
 739  
 740          if ( true === $secure_transport )
 741              error_reporting($error_reporting);
 742  
 743          $process = WP_Http::processResponse($strResponse);
 744          $arrHeaders = WP_Http::processHeaders($process['headers']);
 745  
 746          // Is the response code within the 400 range?
 747          if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 )
 748              return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']);
 749  
 750          // If location is found, then assume redirect and redirect to location.
 751          if ( 'HEAD' != $r['method'] && isset($arrHeaders['headers']['location']) ) {
 752              if ( $r['redirection']-- > 0 ) {
 753                  return $this->request($arrHeaders['headers']['location'], $r);
 754              } else {
 755                  return new WP_Error('http_request_failed', __('Too many redirects.'));
 756              }
 757          }
 758  
 759          // If the body was chunk encoded, then decode it.
 760          if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
 761              $process['body'] = WP_Http::chunkTransferDecode($process['body']);
 762  
 763          if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
 764              $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
 765  
 766          return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']);
 767      }
 768  
 769      /**
 770       * Whether this class can be used for retrieving an URL.
 771       *
 772       * @since 2.7.0
 773       * @static
 774       * @return boolean False means this class can not be used, true means it can.
 775       */
 776  	function test( $args = array() ) {
 777          if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
 778              return false;
 779  
 780          $is_ssl = isset($args['ssl']) && $args['ssl'];
 781  
 782          if ( ! $is_ssl && function_exists( 'fsockopen' ) )
 783              $use = true;
 784          elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) )
 785              $use = true;
 786          else
 787              $use = false;
 788  
 789          return apply_filters('use_fsockopen_transport', $use, $args);
 790      }
 791  }
 792  
 793  /**
 794   * HTTP request method uses fopen function to retrieve the url.
 795   *
 796   * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support,
 797   * but should still be okay, to write the headers, before getting the response. Also requires that
 798   * 'allow_url_fopen' to be enabled.
 799   *
 800   * @package WordPress
 801   * @subpackage HTTP
 802   * @since 2.7.0
 803   */
 804  class WP_Http_Fopen {
 805      /**
 806       * Send a HTTP request to a URI using fopen().
 807       *
 808       * This transport does not support sending of headers and body, therefore should not be used in
 809       * the instances, where there is a body and headers.
 810       *
 811       * Notes: Does not support non-blocking mode. Ignores 'redirection' option.
 812       *
 813       * @see WP_Http::retrieve For default options descriptions.
 814       *
 815       * @access public
 816       * @since 2.7.0
 817       *
 818       * @param string $url URI resource.
 819       * @param str|array $args Optional. Override the defaults.
 820       * @return array 'headers', 'body', 'cookies' and 'response' keys.
 821       */
 822  	function request($url, $args = array()) {
 823          $defaults = array(
 824              'method' => 'GET', 'timeout' => 5,
 825              'redirection' => 5, 'httpversion' => '1.0',
 826              'blocking' => true,
 827              'headers' => array(), 'body' => null, 'cookies' => array()
 828          );
 829  
 830          $r = wp_parse_args( $args, $defaults );
 831  
 832          $arrURL = parse_url($url);
 833  
 834          if ( false === $arrURL )
 835              return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
 836  
 837          if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
 838              $url = str_replace($arrURL['scheme'], 'http', $url);
 839  
 840          if ( is_null( $r['headers'] ) )
 841              $r['headers'] = array();
 842  
 843          if ( is_string($r['headers']) ) {
 844              $processedHeaders = WP_Http::processHeaders($r['headers']);
 845              $r['headers'] = $processedHeaders['headers'];
 846          }
 847  
 848          $initial_user_agent = ini_get('user_agent');
 849  
 850          if ( !empty($r['headers']) && is_array($r['headers']) ) {
 851              $user_agent_extra_headers = '';
 852              foreach ( $r['headers'] as $header => $value )
 853                  $user_agent_extra_headers .= "\r\n$header: $value";
 854              @ini_set('user_agent', $r['user-agent'] . $user_agent_extra_headers);
 855          } else {
 856              @ini_set('user_agent', $r['user-agent']);
 857          }
 858  
 859          if ( !WP_DEBUG )
 860              $handle = @fopen($url, 'r');
 861          else
 862              $handle = fopen($url, 'r');
 863  
 864          if (! $handle)
 865              return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
 866  
 867          $timeout = (int) floor( $r['timeout'] );
 868          $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
 869          stream_set_timeout( $handle, $timeout, $utimeout );
 870  
 871          if ( ! $r['blocking'] ) {
 872              fclose($handle);
 873              @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
 874              return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
 875          }
 876  
 877          $strResponse = '';
 878          while ( ! feof($handle) )
 879              $strResponse .= fread($handle, 4096);
 880  
 881          if ( function_exists('stream_get_meta_data') ) {
 882              $meta = stream_get_meta_data($handle);
 883  
 884              $theHeaders = $meta['wrapper_data'];
 885              if ( isset( $meta['wrapper_data']['headers'] ) )
 886                  $theHeaders = $meta['wrapper_data']['headers'];
 887          } else {
 888              //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper
 889              //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php
 890              $theHeaders = $http_response_header;
 891          }
 892  
 893          fclose($handle);
 894  
 895          @ini_set('user_agent', $initial_user_agent); //Clean up any extra headers added
 896  
 897          $processedHeaders = WP_Http::processHeaders($theHeaders);
 898  
 899          if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
 900              $strResponse = WP_Http::chunkTransferDecode($strResponse);
 901  
 902          if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
 903              $strResponse = WP_Http_Encoding::decompress( $strResponse );
 904  
 905          return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
 906      }
 907  
 908      /**
 909       * Whether this class can be used for retrieving an URL.
 910       *
 911       * @since 2.7.0
 912       * @static
 913       * @return boolean False means this class can not be used, true means it can.
 914       */
 915  	function test($args = array()) {
 916          if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
 917              return false;
 918  
 919          if ( isset($args['method']) && 'HEAD' == $args['method'] ) //This transport cannot make a HEAD request
 920              return false;
 921  
 922          $use = true;
 923          //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off.
 924          $is_ssl = isset($args['ssl']) && $args['ssl'];
 925          if ( $is_ssl ) {
 926              $is_local = isset($args['local']) && $args['local'];
 927              $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
 928              if ( $is_local && true != apply_filters('https_local_ssl_verify', true) )
 929                  $use = true;
 930              elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) )
 931                  $use = true;
 932              elseif ( !$ssl_verify )
 933                  $use = true;
 934              else
 935                  $use = false;
 936          }
 937  
 938          return apply_filters('use_fopen_transport', $use, $args);
 939      }
 940  }
 941  
 942  /**
 943   * HTTP request method uses Streams to retrieve the url.
 944   *
 945   * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
 946   * to be enabled.
 947   *
 948   * Second preferred method for getting the URL, for PHP 5.
 949   *
 950   * @package WordPress
 951   * @subpackage HTTP
 952   * @since 2.7.0
 953   */
 954  class WP_Http_Streams {
 955      /**
 956       * Send a HTTP request to a URI using streams with fopen().
 957       *
 958       * @access public
 959       * @since 2.7.0
 960       *
 961       * @param string $url
 962       * @param str|array $args Optional. Override the defaults.
 963       * @return array 'headers', 'body', 'cookies' and 'response' keys.
 964       */
 965  	function request($url, $args = array()) {
 966          $defaults = array(
 967              'method' => 'GET', 'timeout' => 5,
 968              'redirection' => 5, 'httpversion' => '1.0',
 969              'blocking' => true,
 970              'headers' => array(), 'body' => null, 'cookies' => array()
 971          );
 972  
 973          $r = wp_parse_args( $args, $defaults );
 974  
 975          if ( isset($r['headers']['User-Agent']) ) {
 976              $r['user-agent'] = $r['headers']['User-Agent'];
 977              unset($r['headers']['User-Agent']);
 978          } else if( isset($r['headers']['user-agent']) ) {
 979              $r['user-agent'] = $r['headers']['user-agent'];
 980              unset($r['headers']['user-agent']);
 981          }
 982  
 983          // Construct Cookie: header if any cookies are set
 984          WP_Http::buildCookieHeader( $r );
 985  
 986          $arrURL = parse_url($url);
 987  
 988          if ( false === $arrURL )
 989              return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
 990  
 991          if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
 992              $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
 993  
 994          // Convert Header array to string.
 995          $strHeaders = '';
 996          if ( is_array( $r['headers'] ) )
 997              foreach ( $r['headers'] as $name => $value )
 998                  $strHeaders .= "{$name}: $value\r\n";
 999          else if ( is_string( $r['headers'] ) )
1000              $strHeaders = $r['headers'];
1001  
1002          $is_local = isset($args['local']) && $args['local'];
1003          $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1004          if ( $is_local )
1005              $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1006          elseif ( ! $is_local )
1007              $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1008  
1009          $arrContext = array('http' =>
1010              array(
1011                  'method' => strtoupper($r['method']),
1012                  'user_agent' => $r['user-agent'],
1013                  'max_redirects' => $r['redirection'] + 1, // See #11557
1014                  'protocol_version' => (float) $r['httpversion'],
1015                  'header' => $strHeaders,
1016                  'ignore_errors' => true, // Return non-200 requests.
1017                  'timeout' => $r['timeout'],
1018                  'ssl' => array(
1019                          'verify_peer' => $ssl_verify,
1020                          'verify_host' => $ssl_verify
1021                  )
1022              )
1023          );
1024  
1025          $proxy = new WP_HTTP_Proxy();
1026  
1027          if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1028              $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
1029              $arrContext['http']['request_fulluri'] = true;
1030  
1031              // We only support Basic authentication so this will only work if that is what your proxy supports.
1032              if ( $proxy->use_authentication() )
1033                  $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
1034          }
1035  
1036          if ( 'HEAD' == $r['method'] ) // Disable redirects for HEAD requests
1037              $arrContext['http']['max_redirects'] = 1;
1038  
1039          if ( ! empty($r['body'] ) )
1040              $arrContext['http']['content'] = $r['body'];
1041  
1042          $context = stream_context_create($arrContext);
1043  
1044          if ( !WP_DEBUG )
1045              $handle = @fopen($url, 'r', false, $context);
1046          else
1047              $handle = fopen($url, 'r', false, $context);
1048  
1049          if ( ! $handle )
1050              return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
1051  
1052          $timeout = (int) floor( $r['timeout'] );
1053          $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
1054          stream_set_timeout( $handle, $timeout, $utimeout );
1055  
1056          if ( ! $r['blocking'] ) {
1057              stream_set_blocking($handle, 0);
1058              fclose($handle);
1059              return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1060          }
1061  
1062          $strResponse = stream_get_contents($handle);
1063          $meta = stream_get_meta_data($handle);
1064  
1065          fclose($handle);
1066  
1067          $processedHeaders = array();
1068          if ( isset( $meta['wrapper_data']['headers'] ) )
1069              $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
1070          else
1071              $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
1072  
1073          if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
1074              $strResponse = WP_Http::chunkTransferDecode($strResponse);
1075  
1076          if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
1077              $strResponse = WP_Http_Encoding::decompress( $strResponse );
1078  
1079          return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']);
1080      }
1081  
1082      /**
1083       * Whether this class can be used for retrieving an URL.
1084       *
1085       * @static
1086       * @access public
1087       * @since 2.7.0
1088       *
1089       * @return boolean False means this class can not be used, true means it can.
1090       */
1091  	function test($args = array()) {
1092          if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) )
1093              return false;
1094  
1095          if ( version_compare(PHP_VERSION, '5.0', '<') )
1096              return false;
1097  
1098          //HTTPS via Proxy was added in 5.1.0
1099          $is_ssl = isset($args['ssl']) && $args['ssl'];
1100          if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) {
1101              $proxy = new WP_HTTP_Proxy();
1102              /**
1103               * No URL check, as its not currently passed to the ::test() function
1104               * In the case where a Proxy is in use, Just bypass this transport for HTTPS.
1105               */
1106              if ( $proxy->is_enabled() )
1107                  return false;
1108          }
1109  
1110          return apply_filters('use_streams_transport', true, $args);
1111      }
1112  }
1113  
1114  /**
1115   * HTTP request method uses HTTP extension to retrieve the url.
1116   *
1117   * Requires the HTTP extension to be installed. This would be the preferred transport since it can
1118   * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+
1119   * is being used, it doesn't mean that the HTTP extension will be enabled.
1120   *
1121   * @package WordPress
1122   * @subpackage HTTP
1123   * @since 2.7.0
1124   */
1125  class WP_Http_ExtHTTP {
1126      /**
1127       * Send a HTTP request to a URI using HTTP extension.
1128       *
1129       * Does not support non-blocking.
1130       *
1131       * @access public
1132       * @since 2.7
1133       *
1134       * @param string $url
1135       * @param str|array $args Optional. Override the defaults.
1136       * @return array 'headers', 'body', 'cookies' and 'response' keys.
1137       */
1138  	function request($url, $args = array()) {
1139          $defaults = array(
1140              'method' => 'GET', 'timeout' => 5,
1141              'redirection' => 5, 'httpversion' => '1.0',
1142              'blocking' => true,
1143              'headers' => array(), 'body' => null, 'cookies' => array()
1144          );
1145  
1146          $r = wp_parse_args( $args, $defaults );
1147  
1148          if ( isset($r['headers']['User-Agent']) ) {
1149              $r['user-agent'] = $r['headers']['User-Agent'];
1150              unset($r['headers']['User-Agent']);
1151          } else if( isset($r['headers']['user-agent']) ) {
1152              $r['user-agent'] = $r['headers']['user-agent'];
1153              unset($r['headers']['user-agent']);
1154          }
1155  
1156          // Construct Cookie: header if any cookies are set
1157          WP_Http::buildCookieHeader( $r );
1158  
1159          switch ( $r['method'] ) {
1160              case 'POST':
1161                  $r['method'] = HTTP_METH_POST;
1162                  break;
1163              case 'HEAD':
1164                  $r['method'] = HTTP_METH_HEAD;
1165                  break;
1166              case 'PUT':
1167                  $r['method'] =  HTTP_METH_PUT;
1168                  break;
1169              case 'GET':
1170              default:
1171                  $r['method'] = HTTP_METH_GET;
1172          }
1173  
1174          $arrURL = parse_url($url);
1175  
1176          if ( 'http' != $arrURL['scheme'] || 'https' != $arrURL['scheme'] )
1177              $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
1178  
1179          $is_local = isset($args['local']) && $args['local'];
1180          $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1181          if ( $is_local )
1182              $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1183          elseif ( ! $is_local )
1184              $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1185  
1186          $r['timeout'] = (int) ceil( $r['timeout'] );
1187  
1188          $options = array(
1189              'timeout' => $r['timeout'],
1190              'connecttimeout' => $r['timeout'],
1191              'redirect' => $r['redirection'],
1192              'useragent' => $r['user-agent'],
1193              'headers' => $r['headers'],
1194              'ssl' => array(
1195                  'verifypeer' => $ssl_verify,
1196                  'verifyhost' => $ssl_verify
1197              )
1198          );
1199  
1200          if ( HTTP_METH_HEAD == $r['method'] )
1201              $options['redirect'] = 0; // Assumption: Docs seem to suggest that this means do not follow. Untested.
1202  
1203          // The HTTP extensions offers really easy proxy support.
1204          $proxy = new WP_HTTP_Proxy();
1205  
1206          if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1207              $options['proxyhost'] = $proxy->host();
1208              $options['proxyport'] = $proxy->port();
1209              $options['proxytype'] = HTTP_PROXY_HTTP;
1210  
1211              if ( $proxy->use_authentication() ) {
1212                  $options['proxyauth'] = $proxy->authentication();
1213                  $options['proxyauthtype'] = HTTP_AUTH_ANY;
1214              }
1215          }
1216  
1217          if ( !WP_DEBUG ) //Emits warning level notices for max redirects and timeouts
1218              $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
1219          else
1220              $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts
1221  
1222          // Error may still be set, Response may return headers or partial document, and error
1223          // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
1224          if ( false === $strResponse || ! empty($info['error']) )
1225              return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
1226  
1227          if ( ! $r['blocking'] )
1228              return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1229  
1230          $headers_body = WP_HTTP::processResponse($strResponse);
1231          $theHeaders = $headers_body['headers'];
1232          $theBody = $headers_body['body'];
1233          unset($headers_body);
1234  
1235          $theHeaders = WP_Http::processHeaders($theHeaders);
1236  
1237          if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) {
1238              if ( !WP_DEBUG )
1239                  $theBody = @http_chunked_decode($theBody);
1240              else
1241                  $theBody = http_chunked_decode($theBody);
1242          }
1243  
1244          if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1245              $theBody = http_inflate( $theBody );
1246  
1247          $theResponse = array();
1248          $theResponse['code'] = $info['response_code'];
1249          $theResponse['message'] = get_status_header_desc($info['response_code']);
1250  
1251          return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']);
1252      }
1253  
1254      /**
1255       * Whether this class can be used for retrieving an URL.
1256       *
1257       * @static
1258       * @since 2.7.0
1259       *
1260       * @return boolean False means this class can not be used, true means it can.
1261       */
1262  	function test($args = array()) {
1263          return apply_filters('use_http_extension_transport', function_exists('http_request'), $args );
1264      }
1265  }
1266  
1267  /**
1268   * HTTP request method uses Curl extension to retrieve the url.
1269   *
1270   * Requires the Curl extension to be installed.
1271   *
1272   * @package WordPress
1273   * @subpackage HTTP
1274   * @since 2.7
1275   */
1276  class WP_Http_Curl {
1277  
1278      /**
1279       * Send a HTTP request to a URI using cURL extension.
1280       *
1281       * @access public
1282       * @since 2.7.0
1283       *
1284       * @param string $url
1285       * @param str|array $args Optional. Override the defaults.
1286       * @return array 'headers', 'body', 'cookies' and 'response' keys.
1287       */
1288  	function request($url, $args = array()) {
1289          $defaults = array(
1290              'method' => 'GET', 'timeout' => 5,
1291              'redirection' => 5, 'httpversion' => '1.0',
1292              'blocking' => true,
1293              'headers' => array(), 'body' => null, 'cookies' => array()
1294          );
1295  
1296          $r = wp_parse_args( $args, $defaults );
1297  
1298          if ( isset($r['headers']['User-Agent']) ) {
1299              $r['user-agent'] = $r['headers']['User-Agent'];
1300              unset($r['headers']['User-Agent']);
1301          } else if( isset($r['headers']['user-agent']) ) {
1302              $r['user-agent'] = $r['headers']['user-agent'];
1303              unset($r['headers']['user-agent']);
1304          }
1305  
1306          // Construct Cookie: header if any cookies are set.
1307          WP_Http::buildCookieHeader( $r );
1308  
1309          $handle = curl_init();
1310  
1311          // cURL offers really easy proxy support.
1312          $proxy = new WP_HTTP_Proxy();
1313  
1314          if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1315  
1316              $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>=');
1317  
1318              if ( $isPHP5 ) {
1319                  curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1320                  curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1321                  curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1322              } else {
1323                  curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() );
1324              }
1325  
1326              if ( $proxy->use_authentication() ) {
1327                  if ( $isPHP5 )
1328                      curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1329  
1330                  curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1331              }
1332          }
1333  
1334          $is_local = isset($args['local']) && $args['local'];
1335          $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1336          if ( $is_local )
1337              $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1338          elseif ( ! $is_local )
1339              $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1340  
1341  
1342          // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers.  Have to use ceil since
1343          // a value of 0 will allow an ulimited timeout.
1344          $timeout = (int) ceil( $r['timeout'] );
1345          curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1346          curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1347  
1348          curl_setopt( $handle, CURLOPT_URL, $url);
1349          curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1350          curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify );
1351          curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1352          curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1353          curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] );
1354  
1355          switch ( $r['method'] ) {
1356              case 'HEAD':
1357                  curl_setopt( $handle, CURLOPT_NOBODY, true );
1358                  break;
1359              case 'POST':
1360                  curl_setopt( $handle, CURLOPT_POST, true );
1361                  curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1362                  break;
1363              case 'PUT':
1364                  curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1365                  curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1366                  break;
1367          }
1368  
1369          if ( true === $r['blocking'] )
1370              curl_setopt( $handle, CURLOPT_HEADER, true );
1371          else
1372              curl_setopt( $handle, CURLOPT_HEADER, false );
1373  
1374          // The option doesn't work with safe mode or when open_basedir is set.
1375          // Disable HEAD when making HEAD requests.
1376          if ( !ini_get('safe_mode') && !ini_get('open_basedir') && 'HEAD' != $r['method'] )
1377              curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
1378  
1379          if ( !empty( $r['headers'] ) ) {
1380              // cURL expects full header strings in each element
1381              $headers = array();
1382              foreach ( $r['headers'] as $name => $value ) {
1383                  $headers[] = "{$name}: $value";
1384              }
1385              curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1386          }
1387  
1388          if ( $r['httpversion'] == '1.0' )
1389              curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1390          else
1391              curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1392  
1393          // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1394          // themselves... Although, it is somewhat pointless without some reference.
1395          do_action_ref_array( 'http_api_curl', array(&$handle) );
1396  
1397          // We don't need to return the body, so don't. Just execute request and return.
1398          if ( ! $r['blocking'] ) {
1399              curl_exec( $handle );
1400              curl_close( $handle );
1401              return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1402          }
1403  
1404          $theResponse = curl_exec( $handle );
1405  
1406          if ( !empty($theResponse) ) {
1407              $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
1408              $theHeaders = trim( substr($theResponse, 0, $headerLength) );
1409              if ( strlen($theResponse) > $headerLength )
1410                  $theBody = substr( $theResponse, $headerLength );
1411              else
1412                  $theBody = '';
1413              if ( false !== strrpos($theHeaders, "\r\n\r\n") ) {
1414                  $headerParts = explode("\r\n\r\n", $theHeaders);
1415                  $theHeaders = $headerParts[ count($headerParts) -1 ];
1416              }
1417              $theHeaders = WP_Http::processHeaders($theHeaders);
1418          } else {
1419              if ( $curl_error = curl_error($handle) )
1420                  return new WP_Error('http_request_failed', $curl_error);
1421              if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) )
1422                  return new WP_Error('http_request_failed', __('Too many redirects.'));
1423  
1424              $theHeaders = array( 'headers' => array(), 'cookies' => array() );
1425              $theBody = '';
1426          }
1427  
1428          $response = array();
1429          $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1430          $response['message'] = get_status_header_desc($response['code']);
1431  
1432          curl_close( $handle );
1433  
1434          // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually.
1435          if ( !empty($theHeaders['headers']['location']) && (ini_get('safe_mode') || ini_get('open_basedir')) ) {
1436              if ( $r['redirection']-- > 0 ) {
1437                  return $this->request($theHeaders['headers']['location'], $r);
1438              } else {
1439                  return new WP_Error('http_request_failed', __('Too many redirects.'));
1440              }
1441          }
1442  
1443          if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1444              $theBody = WP_Http_Encoding::decompress( $theBody );
1445  
1446          return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']);
1447      }
1448  
1449      /**
1450       * Whether this class can be used for retrieving an URL.
1451       *
1452       * @static
1453       * @since 2.7.0
1454       *
1455       * @return boolean False means this class can not be used, true means it can.
1456       */
1457  	function test($args = array()) {
1458          if ( function_exists('curl_init') && function_exists('curl_exec') )
1459              return apply_filters('use_curl_transport', true, $args);
1460  
1461          return false;
1462      }
1463  }
1464  
1465  /**
1466   * Adds Proxy support to the WordPress HTTP API.
1467   *
1468   * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1469   * enable proxy support. There are also a few filters that plugins can hook into for some of the
1470   * constants.
1471   *
1472   * Please note that only BASIC authentication is supported by most transports.
1473   * cURL and the PHP HTTP Extension MAY support more methods (such as NTLM authentication) depending on your environment.
1474   *
1475   * The constants are as follows:
1476   * <ol>
1477   * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1478   * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1479   * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1480   * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1481   * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1482   * You do not need to have localhost and the blog host in this list, because they will not be passed
1483   * through the proxy. The list should be presented in a comma separated list</li>
1484   * </ol>
1485   *
1486   * An example can be as seen below.
1487   * <code>
1488   * define('WP_PROXY_HOST', '192.168.84.101');
1489   * define('WP_PROXY_PORT', '8080');
1490   * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com');
1491   * </code>
1492   *
1493   * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1494   * @since 2.8
1495   */
1496  class WP_HTTP_Proxy {
1497  
1498      /**
1499       * Whether proxy connection should be used.
1500       *
1501       * @since 2.8
1502       * @use WP_PROXY_HOST
1503       * @use WP_PROXY_PORT
1504       *
1505       * @return bool
1506       */
1507  	function is_enabled() {
1508          return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1509      }
1510  
1511      /**
1512       * Whether authentication should be used.
1513       *
1514       * @since 2.8
1515       * @use WP_PROXY_USERNAME
1516       * @use WP_PROXY_PASSWORD
1517       *
1518       * @return bool
1519       */
1520  	function use_authentication() {
1521          return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1522      }
1523  
1524      /**
1525       * Retrieve the host for the proxy server.
1526       *
1527       * @since 2.8
1528       *
1529       * @return string
1530       */
1531  	function host() {
1532          if ( defined('WP_PROXY_HOST') )
1533              return WP_PROXY_HOST;
1534  
1535          return '';
1536      }
1537  
1538      /**
1539       * Retrieve the port for the proxy server.
1540       *
1541       * @since 2.8
1542       *
1543       * @return string
1544       */
1545  	function port() {
1546          if ( defined('WP_PROXY_PORT') )
1547              return WP_PROXY_PORT;
1548  
1549          return '';
1550      }
1551  
1552      /**
1553       * Retrieve the username for proxy authentication.
1554       *
1555       * @since 2.8
1556       *
1557       * @return string
1558       */
1559  	function username() {
1560          if ( defined('WP_PROXY_USERNAME') )
1561              return WP_PROXY_USERNAME;
1562  
1563          return '';
1564      }
1565  
1566      /**
1567       * Retrieve the password for proxy authentication.
1568       *
1569       * @since 2.8
1570       *
1571       * @return string
1572       */
1573  	function password() {
1574          if ( defined('WP_PROXY_PASSWORD') )
1575              return WP_PROXY_PASSWORD;
1576  
1577          return '';
1578      }
1579  
1580      /**
1581       * Retrieve authentication string for proxy authentication.
1582       *
1583       * @since 2.8
1584       *
1585       * @return string
1586       */
1587  	function authentication() {
1588          return $this->username() . ':' . $this->password();
1589      }
1590  
1591      /**
1592       * Retrieve header string for proxy authentication.
1593       *
1594       * @since 2.8
1595       *
1596       * @return string
1597       */
1598  	function authentication_header() {
1599          return 'Proxy-Authentication: Basic ' . base64_encode( $this->authentication() );
1600      }
1601  
1602      /**
1603       * Whether URL should be sent through the proxy server.
1604       *
1605       * We want to keep localhost and the blog URL from being sent through the proxy server, because
1606       * some proxies can not handle this. We also have the constant available for defining other
1607       * hosts that won't be sent through the proxy.
1608       *
1609       * @uses WP_PROXY_BYPASS_HOSTS
1610       * @since unknown
1611       *
1612       * @param string $uri URI to check.
1613       * @return bool True, to send through the proxy and false if, the proxy should not be used.
1614       */
1615  	function send_through_proxy( $uri ) {
1616          // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1617          // This will be displayed on blogs, which is not reasonable.
1618          $check = @parse_url($uri);
1619  
1620          // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1621          if ( $check === false )
1622              return true;
1623  
1624          $home = parse_url( get_option('siteurl') );
1625  
1626          if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1627              return false;
1628  
1629          if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1630              return true;
1631  
1632          static $bypass_hosts;
1633          if ( null == $bypass_hosts )
1634              $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1635  
1636          return !in_array( $check['host'], $bypass_hosts );
1637      }
1638  }
1639  /**
1640   * Internal representation of a single cookie.
1641   *
1642   * Returned cookies are represented using this class, and when cookies are set, if they are not
1643   * already a WP_Http_Cookie() object, then they are turned into one.
1644   *
1645   * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1646   * names. Need to switch to use underscores instead for the methods.
1647   *
1648   * @package WordPress
1649   * @subpackage HTTP
1650   * @since 2.8.0
1651   */
1652  class WP_Http_Cookie {
1653  
1654      /**
1655       * Cookie name.
1656       *
1657       * @since 2.8.0
1658       * @var string
1659       */
1660      var $name;
1661  
1662      /**
1663       * Cookie value.
1664       *
1665       * @since 2.8.0
1666       * @var string
1667       */
1668      var $value;
1669  
1670      /**
1671       * When the cookie expires.
1672       *
1673       * @since 2.8.0
1674       * @var string
1675       */
1676      var $expires;
1677  
1678      /**
1679       * Cookie URL path.
1680       *
1681       * @since 2.8.0
1682       * @var string
1683       */
1684      var $path;
1685  
1686      /**
1687       * Cookie Domain.
1688       *
1689       * @since 2.8.0
1690       * @var string
1691       */
1692      var $domain;
1693  
1694      /**
1695       * PHP4 style Constructor - Calls PHP5 Style Constructor.
1696       *
1697       * @access public
1698       * @since 2.8.0
1699       * @param string|array $data Raw cookie data.
1700       */
1701  	function WP_Http_Cookie( $data ) {
1702          $this->__construct( $data );
1703      }
1704  
1705      /**
1706       * Sets up this cookie object.
1707       *
1708       * The parameter $data should be either an associative array containing the indices names below
1709       * or a header string detailing it.
1710       *
1711       * If it's an array, it should include the following elements:
1712       * <ol>
1713       * <li>Name</li>
1714       * <li>Value - should NOT be urlencoded already.</li>
1715       * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1716       * <li>Path (optional)</li>
1717       * <li>Domain (optional)</li>
1718       * </ol>
1719       *
1720       * @access public
1721       * @since 2.8.0
1722       *
1723       * @param string|array $data Raw cookie data.
1724       */
1725  	function __construct( $data ) {
1726          if ( is_string( $data ) ) {
1727              // Assume it's a header string direct from a previous request
1728              $pairs = explode( ';', $data );
1729  
1730              // Special handling for first pair; name=value. Also be careful of "=" in value
1731              $name  = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1732              $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1733              $this->name  = $name;
1734              $this->value = urldecode( $value );
1735              array_shift( $pairs ); //Removes name=value from items.
1736  
1737              // Set everything else as a property
1738              foreach ( $pairs as $pair ) {
1739                  $pair = rtrim($pair);
1740                  if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1741                      continue;
1742  
1743                  list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1744                  $key = strtolower( trim( $key ) );
1745                  if ( 'expires' == $key )
1746                      $val = strtotime( $val );
1747                  $this->$key = $val;
1748              }
1749          } else {
1750              if ( !isset( $data['name'] ) )
1751                  return false;
1752  
1753              // Set properties based directly on parameters
1754              $this->name   = $data['name'];
1755              $this->value  = isset( $data['value'] ) ? $data['value'] : '';
1756              $this->path   = isset( $data['path'] ) ? $data['path'] : '';
1757              $this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1758  
1759              if ( isset( $data['expires'] ) )
1760                  $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1761              else
1762                  $this->expires = null;
1763          }
1764      }
1765  
1766      /**
1767       * Confirms that it's OK to send this cookie to the URL checked against.
1768       *
1769       * Decision is based on RFC 2109/2965, so look there for details on validity.
1770       *
1771       * @access public
1772       * @since 2.8.0
1773       *
1774       * @param string $url URL you intend to send this cookie to
1775       * @return boolean TRUE if allowed, FALSE otherwise.
1776       */
1777  	function test( $url ) {
1778          // Expires - if expired then nothing else matters
1779          if ( time() > $this->expires )
1780              return false;
1781  
1782          // Get details on the URL we're thinking about sending to
1783          $url = parse_url( $url );
1784          $url['port'] = isset( $url['port'] ) ? $url['port'] : 80;
1785          $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
1786  
1787          // Values to use for comparison against the URL
1788          $path   = isset( $this->path )   ? $this->path   : '/';
1789          $port   = isset( $this->port )   ? $this->port   : 80;
1790          $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
1791          if ( false === stripos( $domain, '.' ) )
1792              $domain .= '.local';
1793  
1794          // Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
1795          $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
1796          if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
1797              return false;
1798  
1799          // Port - supports "port-lists" in the format: "80,8000,8080"
1800          if ( !in_array( $url['port'], explode( ',', $port) ) )
1801              return false;
1802  
1803          // Path - request path must start with path restriction
1804          if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
1805              return false;
1806  
1807          return true;
1808      }
1809  
1810      /**
1811       * Convert cookie name and value back to header string.
1812       *
1813       * @access public
1814       * @since 2.8.0
1815       *
1816       * @return string Header encoded cookie name and value.
1817       */
1818  	function getHeaderValue() {
1819          if ( empty( $this->name ) || empty( $this->value ) )
1820              return '';
1821  
1822          return $this->name . '=' . urlencode( $this->value );
1823      }
1824  
1825      /**
1826       * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
1827       *
1828       * @access public
1829       * @since 2.8.0
1830       *
1831       * @return string
1832       */
1833  	function getFullHeader() {
1834          return 'Cookie: ' . $this->getHeaderValue();
1835      }
1836  }
1837  
1838  /**
1839   * Implementation for deflate and gzip transfer encodings.
1840   *
1841   * Includes RFC 1950, RFC 1951, and RFC 1952.
1842   *
1843   * @since 2.8
1844   * @package WordPress
1845   * @subpackage HTTP
1846   */
1847  class WP_Http_Encoding {
1848  
1849      /**
1850       * Compress raw string using the deflate format.
1851       *
1852       * Supports the RFC 1951 standard.
1853       *
1854       * @since 2.8
1855       *
1856       * @param string $raw String to compress.
1857       * @param int $level Optional, default is 9. Compression level, 9 is highest.
1858       * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
1859       * @return string|bool False on failure.
1860       */
1861  	function compress( $raw, $level = 9, $supports = null ) {
1862          return gzdeflate( $raw, $level );
1863      }
1864  
1865      /**
1866       * Decompression of deflated string.
1867       *
1868       * Will attempt to decompress using the RFC 1950 standard, and if that fails
1869       * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
1870       * 1952 standard gzip decode will be attempted. If all fail, then the
1871       * original compressed string will be returned.
1872       *
1873       * @since 2.8
1874       *
1875       * @param string $compressed String to decompress.
1876       * @param int $length The optional length of the compressed data.
1877       * @return string|bool False on failure.
1878       */
1879  	function decompress( $compressed, $length = null ) {
1880  
1881          if ( empty($compressed) )
1882              return $compressed;
1883  
1884          if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
1885              return $decompressed;
1886  
1887          if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
1888              return $decompressed;
1889  
1890          if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
1891              return $decompressed;
1892  
1893          if ( function_exists('gzdecode') ) {
1894              $decompressed = @gzdecode( $compressed );
1895  
1896              if ( false !== $decompressed )
1897                  return $decompressed;
1898          }
1899  
1900          return $compressed;
1901      }
1902  
1903      /**
1904       * Decompression of deflated string while staying compatible with the majority of servers.
1905       *
1906       * Certain Servers will return deflated data with headers which PHP's gziniflate()
1907       * function cannot handle out of the box. The following function lifted from
1908       * http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate
1909       * the various return forms used.
1910       *
1911       * @since 2.8.1
1912       * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
1913       *
1914       * @param string $gzData String to decompress.
1915       * @return string|bool False on failure.
1916       */
1917  	function compatible_gzinflate($gzData) {
1918          if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
1919              $i = 10;
1920              $flg = ord( substr($gzData, 3, 1) );
1921              if ( $flg > 0 ) {
1922                  if ( $flg & 4 ) {
1923                      list($xlen) = unpack('v', substr($gzData, $i, 2) );
1924                      $i = $i + 2 + $xlen;
1925                  }
1926                  if ( $flg & 8 )
1927                      $i = strpos($gzData, "\0", $i) + 1;
1928                  if ( $flg & 16 )
1929                      $i = strpos($gzData, "\0", $i) + 1;
1930                  if ( $flg & 2 )
1931                      $i = $i + 2;
1932              }
1933              return gzinflate( substr($gzData, $i, -8) );
1934          } else {
1935              return false;
1936          }
1937      }
1938  
1939      /**
1940       * What encoding types to accept and their priority values.
1941       *
1942       * @since 2.8
1943       *
1944       * @return string Types of encoding to accept.
1945       */
1946  	function accept_encoding() {
1947          $type = array();
1948          if ( function_exists( 'gzinflate' ) )
1949              $type[] = 'deflate;q=1.0';
1950  
1951          if ( function_exists( 'gzuncompress' ) )
1952              $type[] = 'compress;q=0.5';
1953  
1954          if ( function_exists( 'gzdecode' ) )
1955              $type[] = 'gzip;q=0.5';
1956  
1957          return implode(', ', $type);
1958      }
1959  
1960      /**
1961       * What enconding the content used when it was compressed to send in the headers.
1962       *
1963       * @since 2.8
1964       *
1965       * @return string Content-Encoding string to send in the header.
1966       */
1967  	function content_encoding() {
1968          return 'deflate';
1969      }
1970  
1971      /**
1972       * Whether the content be decoded based on the headers.
1973       *
1974       * @since 2.8
1975       *
1976       * @param array|string $headers All of the available headers.
1977       * @return bool
1978       */
1979  	function should_decode($headers) {
1980          if ( is_array( $headers ) ) {
1981              if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
1982                  return true;
1983          } else if ( is_string( $headers ) ) {
1984              return ( stripos($headers, 'content-encoding:') !== false );
1985          }
1986  
1987          return false;
1988      }
1989  
1990      /**
1991       * Whether decompression and compression are supported by the PHP version.
1992       *
1993       * Each function is tested instead of checking for the zlib extension, to
1994       * ensure that the functions all exist in the PHP version and aren't
1995       * disabled.
1996       *
1997       * @since 2.8
1998       *
1999       * @return bool
2000       */
2001  	function is_available() {
2002          return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
2003      }
2004  }


Generated: Mon Apr 5 14:26:09 2010 Cross-referenced by PHPXref 0.7