3 * Simple and uniform HTTP request API.
5 * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk
6 * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations.
8 * @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal
16 * WordPress HTTP Class for managing HTTP Transports and making HTTP requests.
18 * This class is called for the functionality of making HTTP requests and replaces Snoopy
19 * functionality. There is no available functionality to add HTTP transport implementations, since
20 * most of the HTTP transports are added and available for use.
22 * There are no properties, because none are needed and for performance reasons. Some of the
23 * functions are static and while they do have some overhead over functions in PHP4, the purpose is
24 * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword
25 * to the code. It is not as easy to convert a function to a method after enough code uses the old
28 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
37 * Send a HTTP request to a URI.
39 * The body and headers are part of the arguments. The 'body' argument is for the body and will
40 * accept either a string or an array. The 'headers' argument should be an array, but a string
41 * is acceptable. If the 'body' argument is an array, then it will automatically be escaped
42 * using http_build_query().
44 * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS
45 * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send
46 * headers. Other protocols are unsupported and most likely will fail.
48 * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
51 * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow
52 * others, but should not be assumed. The 'timeout' is used to sent how long the connection
53 * should stay open before failing when no response. 'redirection' is used to track how many
54 * redirects were taken and used to sent the amount for other transports, but not all transports
55 * accept setting that value.
57 * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and
58 * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The
59 * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is
60 * 'WordPress/WP_Version', where WP_Version is the value from $wp_version.
62 * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP
63 * while it performs the request or continue regardless. Actually, that isn't entirely correct.
64 * Blocking mode really just means whether the fread should just pull what it can whenever it
65 * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading
66 * the entire content. It doesn't actually always mean that PHP will continue going after making
71 * @todo Refactor this code. The code in this method extends the scope of its original purpose
72 * and should be refactored to allow for cleaner abstraction and reduce duplication of the
73 * code. One suggestion is to create a class specifically for the arguments, however
74 * preliminary refactoring to this affect has affect more than just the scope of the
75 * arguments. Something to ponder at least.
77 * @param string $url URI resource.
78 * @param str|array $args Optional. Override the defaults.
79 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
81 function request( $url, $args = array() ) {
86 'timeout' => apply_filters( 'http_request_timeout', 5),
87 'redirection' => apply_filters( 'http_request_redirection_count', 5),
88 'httpversion' => apply_filters( 'http_request_version', '1.0'),
89 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
90 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
100 'limit_response_size' => null,
103 // Pre-parse for the HEAD checks.
104 $args = wp_parse_args( $args );
106 // By default, Head requests do not cause redirections.
107 if ( isset($args['method']) && 'HEAD' == $args['method'] )
108 $defaults['redirection'] = 0;
110 $r = wp_parse_args( $args, $defaults );
111 $r = apply_filters( 'http_request_args', $r, $url );
113 // The transports decrement this, store a copy of the original value for loop purposes.
114 if ( ! isset( $r['_redirection'] ) )
115 $r['_redirection'] = $r['redirection'];
117 // Allow plugins to short-circuit the request
118 $pre = apply_filters( 'pre_http_request', false, $r, $url );
119 if ( false !== $pre )
122 if ( function_exists( 'wp_kses_bad_protocol' ) ) {
123 if ( $r['reject_unsafe_urls'] )
124 $url = wp_http_validate_url( $url );
125 $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
128 $arrURL = @parse_url( $url );
130 if ( empty( $url ) || empty( $arrURL['scheme'] ) )
131 return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
133 if ( $this->block_request( $url ) )
134 return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
136 // Determine if this is a https call and pass that on to the transport functions
137 // so that we can blacklist the transports that do not support ssl verification
138 $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
140 // Determine if this request is to OUR install of WordPress
141 $homeURL = parse_url( get_bloginfo( 'url' ) );
142 $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
145 // If we are streaming to a file but no filename was given drop it in the WP temp dir
146 // and pick its name using the basename of the $url
147 if ( $r['stream'] && empty( $r['filename'] ) )
148 $r['filename'] = get_temp_dir() . basename( $url );
150 // Force some settings if we are streaming to a file and check for existence and perms of destination directory
151 if ( $r['stream'] ) {
152 $r['blocking'] = true;
153 if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
154 return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
157 if ( is_null( $r['headers'] ) )
158 $r['headers'] = array();
160 if ( ! is_array( $r['headers'] ) ) {
161 $processedHeaders = WP_Http::processHeaders( $r['headers'] );
162 $r['headers'] = $processedHeaders['headers'];
165 if ( isset( $r['headers']['User-Agent'] ) ) {
166 $r['user-agent'] = $r['headers']['User-Agent'];
167 unset( $r['headers']['User-Agent'] );
170 if ( isset( $r['headers']['user-agent'] ) ) {
171 $r['user-agent'] = $r['headers']['user-agent'];
172 unset( $r['headers']['user-agent'] );
175 // Construct Cookie: header if any cookies are set
176 WP_Http::buildCookieHeader( $r );
178 if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
179 if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
180 $r['headers']['Accept-Encoding'] = $encoding;
183 if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
184 if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
185 $r['body'] = http_build_query( $r['body'], null, '&' );
187 if ( ! isset( $r['headers']['Content-Type'] ) )
188 $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
191 if ( '' === $r['body'] )
194 if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
195 $r['headers']['Content-Length'] = strlen( $r['body'] );
198 return $this->_dispatch_request($url, $r);
202 * Tests which transports are capable of supporting the request.
207 * @param array $args Request arguments
208 * @param string $url URL to Request
210 * @return string|bool Class name for the first transport that claims to support the request. False if no transport claims to support the request.
212 public function _get_first_available_transport( $args, $url = null ) {
213 $request_order = array( 'curl', 'streams', 'fsockopen' );
215 // Loop over each transport on each HTTP request looking for one which will serve this request's needs
216 foreach ( $request_order as $transport ) {
217 $class = 'WP_HTTP_' . $transport;
219 // Check to see if this transport is a possibility, calls the transport statically
220 if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
230 * Dispatches a HTTP request to a supporting transport.
232 * Tests each transport in order to find a transport which matches the request arguments.
233 * Also caches the transport instance to be used later.
235 * The order for blocking requests is cURL, Streams, and finally Fsockopen.
236 * The order for non-blocking requests is cURL, Streams and Fsockopen().
238 * There are currently issues with "localhost" not resolving correctly with DNS. This may cause
239 * an error "failed to open stream: A connection attempt failed because the connected party did
240 * not properly respond after a period of time, or established connection failed because [the]
241 * connected host has failed to respond."
246 * @param string $url URL to Request
247 * @param array $args Request arguments
248 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
250 private function _dispatch_request( $url, $args ) {
251 static $transports = array();
253 $class = $this->_get_first_available_transport( $args, $url );
255 return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
257 // Transport claims to support request, instantiate it and give it a whirl.
258 if ( empty( $transports[$class] ) )
259 $transports[$class] = new $class;
261 $response = $transports[$class]->request( $url, $args );
263 do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
265 if ( is_wp_error( $response ) )
268 return apply_filters( 'http_response', $response, $args, $url );
272 * Uses the POST HTTP method.
274 * Used for sending data that is expected to be in the body.
279 * @param string $url URI resource.
280 * @param str|array $args Optional. Override the defaults.
281 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
283 function post($url, $args = array()) {
284 $defaults = array('method' => 'POST');
285 $r = wp_parse_args( $args, $defaults );
286 return $this->request($url, $r);
290 * Uses the GET HTTP method.
292 * Used for sending data that is expected to be in the body.
297 * @param string $url URI resource.
298 * @param str|array $args Optional. Override the defaults.
299 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
301 function get($url, $args = array()) {
302 $defaults = array('method' => 'GET');
303 $r = wp_parse_args( $args, $defaults );
304 return $this->request($url, $r);
308 * Uses the HEAD HTTP method.
310 * Used for sending data that is expected to be in the body.
315 * @param string $url URI resource.
316 * @param str|array $args Optional. Override the defaults.
317 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
319 function head($url, $args = array()) {
320 $defaults = array('method' => 'HEAD');
321 $r = wp_parse_args( $args, $defaults );
322 return $this->request($url, $r);
326 * Parses the responses and splits the parts into headers and body.
332 * @param string $strResponse The full response string
333 * @return array Array with 'headers' and 'body' keys.
335 public static function processResponse($strResponse) {
336 $res = explode("\r\n\r\n", $strResponse, 2);
338 return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
342 * Transform header string into an array.
344 * If an array is given then it is assumed to be raw header data with numeric keys with the
345 * headers as the values. No headers must be passed that were already processed.
351 * @param string|array $headers
352 * @return array Processed string headers. If duplicate headers are encountered,
353 * Then a numbered array is returned as the value of that header-key.
355 public static function processHeaders($headers) {
356 // split headers, one per array element
357 if ( is_string($headers) ) {
358 // tolerate line terminator: CRLF = LF (RFC 2616 19.3)
359 $headers = str_replace("\r\n", "\n", $headers);
360 // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
361 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
362 // create the headers array
363 $headers = explode("\n", $headers);
366 $response = array('code' => 0, 'message' => '');
368 // If a redirection has taken place, The headers for each page request may have been passed.
369 // In this case, determine the final HTTP header and parse from there.
370 for ( $i = count($headers)-1; $i >= 0; $i-- ) {
371 if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
372 $headers = array_splice($headers, $i);
378 $newheaders = array();
379 foreach ( (array) $headers as $tempheader ) {
380 if ( empty($tempheader) )
383 if ( false === strpos($tempheader, ':') ) {
384 $stack = explode(' ', $tempheader, 3);
386 list( , $response['code'], $response['message']) = $stack;
390 list($key, $value) = explode(':', $tempheader, 2);
392 $key = strtolower( $key );
393 $value = trim( $value );
395 if ( isset( $newheaders[ $key ] ) ) {
396 if ( ! is_array( $newheaders[ $key ] ) )
397 $newheaders[$key] = array( $newheaders[ $key ] );
398 $newheaders[ $key ][] = $value;
400 $newheaders[ $key ] = $value;
402 if ( 'set-cookie' == $key )
403 $cookies[] = new WP_Http_Cookie( $value );
406 return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
410 * Takes the arguments for a ::request() and checks for the cookie array.
412 * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
413 * into strings and added to the Cookie: header (within the arguments array). Edits the array by
420 * @param array $r Full array of args passed into ::request()
422 public static function buildCookieHeader( &$r ) {
423 if ( ! empty($r['cookies']) ) {
424 $cookies_header = '';
425 foreach ( (array) $r['cookies'] as $cookie ) {
426 $cookies_header .= $cookie->getHeaderValue() . '; ';
428 $cookies_header = substr( $cookies_header, 0, -2 );
429 $r['headers']['cookie'] = $cookies_header;
434 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
436 * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
437 * returning footer headers. Shouldn't be too difficult to support it though.
439 * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
441 * @todo Add support for footer chunked headers.
446 * @param string $body Body content
447 * @return string Chunked decoded body on success or raw body on failure.
449 function chunkTransferDecode($body) {
450 $body = str_replace(array("\r\n", "\r"), "\n", $body);
451 // The body is not chunked encoding or is malformed.
452 if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
456 //$parsedHeaders = array(); Unsupported
459 $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
462 if ( empty( $match[1] ) )
465 $length = hexdec( $match[1] );
466 $chunkLength = strlen( $match[0] );
468 $strBody = substr($body, $chunkLength, $length);
469 $parsedBody .= $strBody;
471 $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
473 if ( "0" == trim($body) )
474 return $parsedBody; // Ignore footer headers.
482 * Block requests through the proxy.
484 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
485 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
487 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
488 * file and this will only allow localhost and your blog to make requests. The constant
489 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
490 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
491 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
494 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
495 * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
497 * @param string $uri URI of url.
498 * @return bool True to block, false to allow.
500 function block_request($uri) {
501 // We don't need to block requests, because nothing is blocked.
502 if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
505 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
506 // This will be displayed on blogs, which is not reasonable.
507 $check = @parse_url($uri);
509 /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
511 * This isn't very security sound. There are instances where a hacker might attempt
512 * to bypass the proxy and this check. However, the reason for this behavior is that
513 * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
514 * the default unsecure nature of the HTTP request.
516 if ( $check === false )
519 $home = parse_url( get_option('siteurl') );
521 // Don't block requests back to ourselves by default
522 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
523 return apply_filters('block_local_requests', false);
525 if ( !defined('WP_ACCESSIBLE_HOSTS') )
528 static $accessible_hosts;
529 static $wildcard_regex = false;
530 if ( null == $accessible_hosts ) {
531 $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
533 if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
534 $wildcard_regex = array();
535 foreach ( $accessible_hosts as $host )
536 $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
537 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
541 if ( !empty($wildcard_regex) )
542 return !preg_match($wildcard_regex, $check['host']);
544 return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
548 static function make_absolute_url( $maybe_relative_path, $url ) {
550 return $maybe_relative_path;
552 // Check for a scheme
553 if ( false !== strpos( $maybe_relative_path, '://' ) )
554 return $maybe_relative_path;
556 if ( ! $url_parts = @parse_url( $url ) )
557 return $maybe_relative_path;
559 if ( ! $relative_url_parts = @parse_url( $maybe_relative_path ) )
560 return $maybe_relative_path;
562 $absolute_path = $url_parts['scheme'] . '://' . $url_parts['host'];
563 if ( isset( $url_parts['port'] ) )
564 $absolute_path .= ':' . $url_parts['port'];
566 // Start off with the Absolute URL path
567 $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
569 // If it's a root-relative path, then great
570 if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
571 $path = $relative_url_parts['path'];
573 // Else it's a relative path
574 } elseif ( ! empty( $relative_url_parts['path'] ) ) {
575 // Strip off any file components from the absolute path
576 $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
578 // Build the new path
579 $path .= $relative_url_parts['path'];
581 // Strip all /path/../ out of the path
582 while ( strpos( $path, '../' ) > 1 ) {
583 $path = preg_replace( '![^/]+/\.\./!', '', $path );
586 // Strip any final leading ../ from the path
587 $path = preg_replace( '!^/(\.\./)+!', '', $path );
590 // Add the Query string
591 if ( ! empty( $relative_url_parts['query'] ) )
592 $path .= '?' . $relative_url_parts['query'];
594 return $absolute_path . '/' . ltrim( $path, '/' );
599 * HTTP request method uses fsockopen function to retrieve the url.
601 * This would be the preferred method, but the fsockopen implementation has the most overhead of all
602 * the HTTP transport implementations.
608 class WP_Http_Fsockopen {
610 * Send a HTTP request to a URI using fsockopen().
612 * Does not support non-blocking mode.
614 * @see WP_Http::request For default options descriptions.
618 * @param string $url URI resource.
619 * @param str|array $args Optional. Override the defaults.
620 * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
622 function request($url, $args = array()) {
624 'method' => 'GET', 'timeout' => 5,
625 'redirection' => 5, 'httpversion' => '1.0',
627 'headers' => array(), 'body' => null, 'cookies' => array()
630 $r = wp_parse_args( $args, $defaults );
632 if ( isset($r['headers']['User-Agent']) ) {
633 $r['user-agent'] = $r['headers']['User-Agent'];
634 unset($r['headers']['User-Agent']);
635 } else if ( isset($r['headers']['user-agent']) ) {
636 $r['user-agent'] = $r['headers']['user-agent'];
637 unset($r['headers']['user-agent']);
640 // Construct Cookie: header if any cookies are set
641 WP_Http::buildCookieHeader( $r );
643 $iError = null; // Store error number
644 $strError = null; // Store error string
646 $arrURL = parse_url($url);
648 $fsockopen_host = $arrURL['host'];
650 $secure_transport = false;
652 if ( ! isset( $arrURL['port'] ) ) {
653 if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
654 $fsockopen_host = "ssl://$fsockopen_host";
655 $arrURL['port'] = 443;
656 $secure_transport = true;
658 $arrURL['port'] = 80;
662 //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
663 // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
664 if ( 'localhost' == strtolower($fsockopen_host) )
665 $fsockopen_host = '127.0.0.1';
667 // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
668 // ignored and should be ignored.
669 if ( true === $secure_transport )
670 $error_reporting = error_reporting(0);
672 $startDelay = time();
674 $proxy = new WP_HTTP_Proxy();
677 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
678 $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
680 $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
682 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
683 $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
685 $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
690 // If the delay is greater than the timeout then fsockopen shouldn't be used, because it will
691 // cause a long delay.
692 $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
693 if ( true === $elapseDelay )
694 add_option( 'disable_fsockopen', $endDelay, null, true );
696 if ( false === $handle )
697 return new WP_Error('http_request_failed', $iError . ': ' . $strError);
699 $timeout = (int) floor( $r['timeout'] );
700 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
701 stream_set_timeout( $handle, $timeout, $utimeout );
703 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
706 $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
708 if ( empty($requestPath) )
711 $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
713 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
714 $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
716 $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
718 if ( isset($r['user-agent']) )
719 $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
721 if ( is_array($r['headers']) ) {
722 foreach ( (array) $r['headers'] as $header => $headerValue )
723 $strHeaders .= $header . ': ' . $headerValue . "\r\n";
725 $strHeaders .= $r['headers'];
728 if ( $proxy->use_authentication() )
729 $strHeaders .= $proxy->authentication_header() . "\r\n";
731 $strHeaders .= "\r\n";
733 if ( ! is_null($r['body']) )
734 $strHeaders .= $r['body'];
736 fwrite($handle, $strHeaders);
738 if ( ! $r['blocking'] ) {
740 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
744 $bodyStarted = false;
745 $keep_reading = true;
747 if ( isset( $r['limit_response_size'] ) )
748 $block_size = min( $block_size, $r['limit_response_size'] );
750 // If streaming to a file setup the file handle
751 if ( $r['stream'] ) {
753 $stream_handle = @fopen( $r['filename'], 'w+' );
755 $stream_handle = fopen( $r['filename'], 'w+' );
756 if ( ! $stream_handle )
757 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
760 while ( ! feof($handle) && $keep_reading ) {
761 $block = fread( $handle, $block_size );
762 if ( ! $bodyStarted ) {
763 $strResponse .= $block;
764 if ( strpos( $strResponse, "\r\n\r\n" ) ) {
765 $process = WP_Http::processResponse( $strResponse );
767 $block = $process['body'];
768 unset( $strResponse );
769 $process['body'] = '';
773 if ( isset( $r['limit_response_size'] ) && ( $bytes_written + strlen( $block ) ) > $r['limit_response_size'] )
774 $block = substr( $block, 0, ( $r['limit_response_size'] - $bytes_written ) );
776 $bytes_written += fwrite( $stream_handle, $block );
778 $keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
781 fclose( $stream_handle );
785 while ( ! feof( $handle ) && $keep_reading ) {
786 $block = fread( $handle, $block_size );
787 $strResponse .= $block;
788 if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
789 $header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
792 $keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
795 $process = WP_Http::processResponse( $strResponse );
796 unset( $strResponse );
802 if ( true === $secure_transport )
803 error_reporting($error_reporting);
805 $arrHeaders = WP_Http::processHeaders( $process['headers'] );
807 // If location is found, then assume redirect and redirect to location.
808 if ( isset($arrHeaders['headers']['location']) && 0 !== $r['_redirection'] ) {
809 if ( $r['redirection']-- > 0 ) {
810 return wp_remote_request( WP_HTTP::make_absolute_url( $arrHeaders['headers']['location'], $url ), $r);
812 return new WP_Error('http_request_failed', __('Too many redirects.'));
816 // If the body was chunk encoded, then decode it.
817 if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
818 $process['body'] = WP_Http::chunkTransferDecode($process['body']);
820 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
821 $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
823 if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
824 $process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
826 return array( 'headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies'], 'filename' => $r['filename'] );
830 * Whether this class can be used for retrieving an URL.
834 * @return boolean False means this class can not be used, true means it can.
836 public static function test( $args = array() ) {
837 if ( ! function_exists( 'fsockopen' ) )
840 if ( false !== ( $option = get_option( 'disable_fsockopen' ) ) && time() - $option < 12 * HOUR_IN_SECONDS )
843 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
845 if ( $is_ssl && ! extension_loaded( 'openssl' ) )
848 return apply_filters( 'use_fsockopen_transport', true, $args );
853 * HTTP request method uses Streams to retrieve the url.
855 * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
858 * Second preferred method for getting the URL, for PHP 5.
864 class WP_Http_Streams {
866 * Send a HTTP request to a URI using streams with fopen().
872 * @param str|array $args Optional. Override the defaults.
873 * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
875 function request($url, $args = array()) {
877 'method' => 'GET', 'timeout' => 5,
878 'redirection' => 5, 'httpversion' => '1.0',
880 'headers' => array(), 'body' => null, 'cookies' => array()
883 $r = wp_parse_args( $args, $defaults );
885 if ( isset($r['headers']['User-Agent']) ) {
886 $r['user-agent'] = $r['headers']['User-Agent'];
887 unset($r['headers']['User-Agent']);
888 } else if ( isset($r['headers']['user-agent']) ) {
889 $r['user-agent'] = $r['headers']['user-agent'];
890 unset($r['headers']['user-agent']);
893 // Construct Cookie: header if any cookies are set
894 WP_Http::buildCookieHeader( $r );
896 $arrURL = parse_url($url);
898 if ( false === $arrURL )
899 return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
901 if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
902 $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
904 // Convert Header array to string.
906 if ( is_array( $r['headers'] ) )
907 foreach ( $r['headers'] as $name => $value )
908 $strHeaders .= "{$name}: $value\r\n";
909 else if ( is_string( $r['headers'] ) )
910 $strHeaders = $r['headers'];
912 $is_local = isset($args['local']) && $args['local'];
913 $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
915 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
916 elseif ( ! $is_local )
917 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
919 $arrContext = array('http' =>
921 'method' => strtoupper($r['method']),
922 'user_agent' => $r['user-agent'],
923 'max_redirects' => 0, // Follow no redirects
924 'follow_redirects' => false,
925 'protocol_version' => (float) $r['httpversion'],
926 'header' => $strHeaders,
927 'ignore_errors' => true, // Return non-200 requests.
928 'timeout' => $r['timeout'],
930 'verify_peer' => $ssl_verify,
931 'verify_host' => $ssl_verify
936 $proxy = new WP_HTTP_Proxy();
938 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
939 $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
940 $arrContext['http']['request_fulluri'] = true;
942 // We only support Basic authentication so this will only work if that is what your proxy supports.
943 if ( $proxy->use_authentication() )
944 $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
947 if ( ! is_null( $r['body'] ) )
948 $arrContext['http']['content'] = $r['body'];
950 $context = stream_context_create($arrContext);
953 $handle = @fopen($url, 'r', false, $context);
955 $handle = fopen($url, 'r', false, $context);
958 return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
960 $timeout = (int) floor( $r['timeout'] );
961 $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
962 stream_set_timeout( $handle, $timeout, $utimeout );
964 if ( ! $r['blocking'] ) {
965 stream_set_blocking($handle, 0);
967 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
970 $max_bytes = isset( $r['limit_response_size'] ) ? intval( $r['limit_response_size'] ) : -1;
971 if ( $r['stream'] ) {
973 $stream_handle = @fopen( $r['filename'], 'w+' );
975 $stream_handle = fopen( $r['filename'], 'w+' );
977 if ( ! $stream_handle )
978 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
980 stream_copy_to_stream( $handle, $stream_handle, $max_bytes );
982 fclose( $stream_handle );
985 $strResponse = stream_get_contents( $handle, $max_bytes );
988 $meta = stream_get_meta_data( $handle );
992 $processedHeaders = array();
993 if ( isset( $meta['wrapper_data']['headers'] ) )
994 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
996 $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
998 if ( ! empty( $processedHeaders['headers']['location'] ) && 0 !== $r['_redirection'] ) { // _redirection: The requested number of redirections
999 if ( $r['redirection']-- > 0 ) {
1000 return wp_remote_request( WP_HTTP::make_absolute_url( $processedHeaders['headers']['location'], $url ), $r );
1002 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1006 if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
1007 $strResponse = WP_Http::chunkTransferDecode($strResponse);
1009 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
1010 $strResponse = WP_Http_Encoding::decompress( $strResponse );
1012 return array( 'headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies'], 'filename' => $r['filename'] );
1016 * Whether this class can be used for retrieving an URL.
1022 * @return boolean False means this class can not be used, true means it can.
1024 public static function test( $args = array() ) {
1025 if ( ! function_exists( 'fopen' ) )
1028 if ( ! function_exists( 'ini_get' ) || true != ini_get( 'allow_url_fopen' ) )
1031 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1033 if ( $is_ssl && ! extension_loaded( 'openssl' ) )
1036 return apply_filters( 'use_streams_transport', true, $args );
1041 * HTTP request method uses Curl extension to retrieve the url.
1043 * Requires the Curl extension to be installed.
1045 * @package WordPress
1049 class WP_Http_Curl {
1052 * Temporary header storage for during requests.
1058 private $headers = '';
1061 * Temporary body storage for during requests.
1070 * The maximum amount of data to recieve from the remote server
1076 private $max_body_length = false;
1079 * The file resource used for streaming to file.
1085 private $stream_handle = false;
1088 * Send a HTTP request to a URI using cURL extension.
1093 * @param string $url
1094 * @param str|array $args Optional. Override the defaults.
1095 * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
1097 function request($url, $args = array()) {
1099 'method' => 'GET', 'timeout' => 5,
1100 'redirection' => 5, 'httpversion' => '1.0',
1102 'headers' => array(), 'body' => null, 'cookies' => array()
1105 $r = wp_parse_args( $args, $defaults );
1107 if ( isset($r['headers']['User-Agent']) ) {
1108 $r['user-agent'] = $r['headers']['User-Agent'];
1109 unset($r['headers']['User-Agent']);
1110 } else if ( isset($r['headers']['user-agent']) ) {
1111 $r['user-agent'] = $r['headers']['user-agent'];
1112 unset($r['headers']['user-agent']);
1115 // Construct Cookie: header if any cookies are set.
1116 WP_Http::buildCookieHeader( $r );
1118 $handle = curl_init();
1120 // cURL offers really easy proxy support.
1121 $proxy = new WP_HTTP_Proxy();
1123 if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1125 curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1126 curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1127 curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1129 if ( $proxy->use_authentication() ) {
1130 curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1131 curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1135 $is_local = isset($r['local']) && $r['local'];
1136 $ssl_verify = isset($r['sslverify']) && $r['sslverify'];
1138 $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1139 elseif ( ! $is_local )
1140 $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1142 // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since
1143 // a value of 0 will allow an unlimited timeout.
1144 $timeout = (int) ceil( $r['timeout'] );
1145 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1146 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1148 curl_setopt( $handle, CURLOPT_URL, $url);
1149 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1150 curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
1151 curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1152 curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1153 // The option doesn't work with safe mode or when open_basedir is set, and there's a
1154 // bug #17490 with redirected POST requests, so handle redirections outside Curl.
1155 curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
1156 if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
1157 curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
1159 switch ( $r['method'] ) {
1161 curl_setopt( $handle, CURLOPT_NOBODY, true );
1164 curl_setopt( $handle, CURLOPT_POST, true );
1165 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1168 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1169 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1172 curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
1173 if ( ! is_null( $r['body'] ) )
1174 curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1178 if ( true === $r['blocking'] ) {
1179 curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
1180 curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
1183 curl_setopt( $handle, CURLOPT_HEADER, false );
1185 if ( isset( $r['limit_response_size'] ) )
1186 $this->max_body_length = intval( $r['limit_response_size'] );
1188 $this->max_body_length = false;
1190 // If streaming to a file open a file handle, and setup our curl streaming handler
1191 if ( $r['stream'] ) {
1193 $this->stream_handle = @fopen( $r['filename'], 'w+' );
1195 $this->stream_handle = fopen( $r['filename'], 'w+' );
1196 if ( ! $this->stream_handle )
1197 return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1199 $this->stream_handle = false;
1202 if ( !empty( $r['headers'] ) ) {
1203 // cURL expects full header strings in each element
1205 foreach ( $r['headers'] as $name => $value ) {
1206 $headers[] = "{$name}: $value";
1208 curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1211 if ( $r['httpversion'] == '1.0' )
1212 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1214 curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1216 // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1217 // themselves... Although, it is somewhat pointless without some reference.
1218 do_action_ref_array( 'http_api_curl', array(&$handle) );
1220 // We don't need to return the body, so don't. Just execute request and return.
1221 if ( ! $r['blocking'] ) {
1222 curl_exec( $handle );
1224 if ( $curl_error = curl_error( $handle ) ) {
1225 curl_close( $handle );
1226 return new WP_Error( 'http_request_failed', $curl_error );
1228 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1229 curl_close( $handle );
1230 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1233 curl_close( $handle );
1234 return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1237 $theResponse = curl_exec( $handle );
1238 $theHeaders = WP_Http::processHeaders( $this->headers );
1239 $theBody = $this->body;
1241 $this->headers = '';
1245 if ( 0 == strlen( $theBody ) && empty( $theHeaders['headers'] ) ) {
1246 if ( $curl_error = curl_error( $handle ) ) {
1247 curl_close( $handle );
1248 return new WP_Error( 'http_request_failed', $curl_error );
1250 if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
1251 curl_close( $handle );
1252 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1256 $response = array();
1257 $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1258 $response['message'] = get_status_header_desc($response['code']);
1260 curl_close( $handle );
1263 fclose( $this->stream_handle );
1265 // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually.
1266 if ( ! empty( $theHeaders['headers']['location'] ) && 0 !== $r['_redirection'] ) { // _redirection: The requested number of redirections
1267 if ( $r['redirection']-- > 0 ) {
1268 return wp_remote_request( WP_HTTP::make_absolute_url( $theHeaders['headers']['location'], $url ), $r );
1270 return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1274 if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1275 $theBody = WP_Http_Encoding::decompress( $theBody );
1277 return array( 'headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies'], 'filename' => $r['filename'] );
1281 * Grab the headers of the cURL request
1283 * Each header is sent individually to this callback, so we append to the $header property for temporary storage
1289 private function stream_headers( $handle, $headers ) {
1290 $this->headers .= $headers;
1291 return strlen( $headers );
1295 * Grab the body of the cURL request
1297 * The contents of the document are passed in chunks, so we append to the $body property for temporary storage.
1298 * Returning a length shorter than the length of $data passed in will cause cURL to abort the request as "completed"
1304 private function stream_body( $handle, $data ) {
1305 if ( $this->max_body_length && ( strlen( $this->body ) + strlen( $data ) ) > $this->max_body_length )
1306 $data = substr( $data, 0, ( $this->max_body_length - strlen( $this->body ) ) );
1308 if ( $this->stream_handle )
1309 fwrite( $this->stream_handle, $data );
1311 $this->body .= $data;
1313 return strlen( $data );
1317 * Whether this class can be used for retrieving an URL.
1322 * @return boolean False means this class can not be used, true means it can.
1324 public static function test( $args = array() ) {
1325 if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
1328 $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1331 $curl_version = curl_version();
1332 if ( ! (CURL_VERSION_SSL & $curl_version['features']) ) // Does this cURL version support SSL requests?
1336 return apply_filters( 'use_curl_transport', true, $args );
1341 * Adds Proxy support to the WordPress HTTP API.
1343 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1344 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1347 * Please note that only BASIC authentication is supported by most transports.
1348 * cURL MAY support more methods (such as NTLM authentication) depending on your environment.
1350 * The constants are as follows:
1352 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1353 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1354 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1355 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1356 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1357 * You do not need to have localhost and the blog host in this list, because they will not be passed
1358 * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
1361 * An example can be as seen below.
1363 * define('WP_PROXY_HOST', '192.168.84.101');
1364 * define('WP_PROXY_PORT', '8080');
1365 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
1368 * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1369 * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
1372 class WP_HTTP_Proxy {
1375 * Whether proxy connection should be used.
1378 * @use WP_PROXY_HOST
1379 * @use WP_PROXY_PORT
1383 function is_enabled() {
1384 return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1388 * Whether authentication should be used.
1391 * @use WP_PROXY_USERNAME
1392 * @use WP_PROXY_PASSWORD
1396 function use_authentication() {
1397 return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1401 * Retrieve the host for the proxy server.
1408 if ( defined('WP_PROXY_HOST') )
1409 return WP_PROXY_HOST;
1415 * Retrieve the port for the proxy server.
1422 if ( defined('WP_PROXY_PORT') )
1423 return WP_PROXY_PORT;
1429 * Retrieve the username for proxy authentication.
1435 function username() {
1436 if ( defined('WP_PROXY_USERNAME') )
1437 return WP_PROXY_USERNAME;
1443 * Retrieve the password for proxy authentication.
1449 function password() {
1450 if ( defined('WP_PROXY_PASSWORD') )
1451 return WP_PROXY_PASSWORD;
1457 * Retrieve authentication string for proxy authentication.
1463 function authentication() {
1464 return $this->username() . ':' . $this->password();
1468 * Retrieve header string for proxy authentication.
1474 function authentication_header() {
1475 return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1479 * Whether URL should be sent through the proxy server.
1481 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1482 * some proxies can not handle this. We also have the constant available for defining other
1483 * hosts that won't be sent through the proxy.
1485 * @uses WP_PROXY_BYPASS_HOSTS
1488 * @param string $uri URI to check.
1489 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1491 function send_through_proxy( $uri ) {
1492 // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1493 // This will be displayed on blogs, which is not reasonable.
1494 $check = @parse_url($uri);
1496 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
1497 if ( $check === false )
1500 $home = parse_url( get_option('siteurl') );
1502 $result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
1503 if ( ! is_null( $result ) )
1506 if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1509 if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1512 static $bypass_hosts;
1513 static $wildcard_regex = false;
1514 if ( null == $bypass_hosts ) {
1515 $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1517 if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
1518 $wildcard_regex = array();
1519 foreach ( $bypass_hosts as $host )
1520 $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
1521 $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
1525 if ( !empty($wildcard_regex) )
1526 return !preg_match($wildcard_regex, $check['host']);
1528 return !in_array( $check['host'], $bypass_hosts );
1532 * Internal representation of a single cookie.
1534 * Returned cookies are represented using this class, and when cookies are set, if they are not
1535 * already a WP_Http_Cookie() object, then they are turned into one.
1537 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1538 * names. Need to switch to use underscores instead for the methods.
1540 * @package WordPress
1544 class WP_Http_Cookie {
1563 * When the cookie expires.
1587 * Sets up this cookie object.
1589 * The parameter $data should be either an associative array containing the indices names below
1590 * or a header string detailing it.
1592 * If it's an array, it should include the following elements:
1595 * <li>Value - should NOT be urlencoded already.</li>
1596 * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1597 * <li>Path (optional)</li>
1598 * <li>Domain (optional)</li>
1604 * @param string|array $data Raw cookie data.
1606 function __construct( $data ) {
1607 if ( is_string( $data ) ) {
1608 // Assume it's a header string direct from a previous request
1609 $pairs = explode( ';', $data );
1611 // Special handling for first pair; name=value. Also be careful of "=" in value
1612 $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1613 $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1614 $this->name = $name;
1615 $this->value = urldecode( $value );
1616 array_shift( $pairs ); //Removes name=value from items.
1618 // Set everything else as a property
1619 foreach ( $pairs as $pair ) {
1620 $pair = rtrim($pair);
1621 if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1624 list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1625 $key = strtolower( trim( $key ) );
1626 if ( 'expires' == $key )
1627 $val = strtotime( $val );
1631 if ( !isset( $data['name'] ) )
1634 // Set properties based directly on parameters
1635 $this->name = $data['name'];
1636 $this->value = isset( $data['value'] ) ? $data['value'] : '';
1637 $this->path = isset( $data['path'] ) ? $data['path'] : '';
1638 $this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1640 if ( isset( $data['expires'] ) )
1641 $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1643 $this->expires = null;
1648 * Confirms that it's OK to send this cookie to the URL checked against.
1650 * Decision is based on RFC 2109/2965, so look there for details on validity.
1655 * @param string $url URL you intend to send this cookie to
1656 * @return boolean true if allowed, false otherwise.
1658 function test( $url ) {
1659 // Expires - if expired then nothing else matters
1660 if ( isset( $this->expires ) && time() > $this->expires )
1663 // Get details on the URL we're thinking about sending to
1664 $url = parse_url( $url );
1665 $url['port'] = isset( $url['port'] ) ? $url['port'] : 80;
1666 $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
1668 // Values to use for comparison against the URL
1669 $path = isset( $this->path ) ? $this->path : '/';
1670 $port = isset( $this->port ) ? $this->port : 80;
1671 $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
1672 if ( false === stripos( $domain, '.' ) )
1673 $domain .= '.local';
1675 // Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
1676 $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
1677 if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
1680 // Port - supports "port-lists" in the format: "80,8000,8080"
1681 if ( !in_array( $url['port'], explode( ',', $port) ) )
1684 // Path - request path must start with path restriction
1685 if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
1692 * Convert cookie name and value back to header string.
1697 * @return string Header encoded cookie name and value.
1699 function getHeaderValue() {
1700 if ( ! isset( $this->name ) || ! isset( $this->value ) )
1703 return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name );
1707 * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
1714 function getFullHeader() {
1715 return 'Cookie: ' . $this->getHeaderValue();
1720 * Implementation for deflate and gzip transfer encodings.
1722 * Includes RFC 1950, RFC 1951, and RFC 1952.
1725 * @package WordPress
1728 class WP_Http_Encoding {
1731 * Compress raw string using the deflate format.
1733 * Supports the RFC 1951 standard.
1737 * @param string $raw String to compress.
1738 * @param int $level Optional, default is 9. Compression level, 9 is highest.
1739 * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
1740 * @return string|bool False on failure.
1742 public static function compress( $raw, $level = 9, $supports = null ) {
1743 return gzdeflate( $raw, $level );
1747 * Decompression of deflated string.
1749 * Will attempt to decompress using the RFC 1950 standard, and if that fails
1750 * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
1751 * 1952 standard gzip decode will be attempted. If all fail, then the
1752 * original compressed string will be returned.
1756 * @param string $compressed String to decompress.
1757 * @param int $length The optional length of the compressed data.
1758 * @return string|bool False on failure.
1760 public static function decompress( $compressed, $length = null ) {
1762 if ( empty($compressed) )
1765 if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
1766 return $decompressed;
1768 if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
1769 return $decompressed;
1771 if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
1772 return $decompressed;
1774 if ( function_exists('gzdecode') ) {
1775 $decompressed = @gzdecode( $compressed );
1777 if ( false !== $decompressed )
1778 return $decompressed;
1785 * Decompression of deflated string while staying compatible with the majority of servers.
1787 * Certain Servers will return deflated data with headers which PHP's gzinflate()
1788 * function cannot handle out of the box. The following function has been created from
1789 * various snippets on the gzinflate() PHP documentation.
1791 * Warning: Magic numbers within. Due to the potential different formats that the compressed
1792 * data may be returned in, some "magic offsets" are needed to ensure proper decompression
1793 * takes place. For a simple progmatic way to determine the magic offset in use, see:
1794 * http://core.trac.wordpress.org/ticket/18273
1797 * @link http://core.trac.wordpress.org/ticket/18273
1798 * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
1799 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
1801 * @param string $gzData String to decompress.
1802 * @return string|bool False on failure.
1804 public static function compatible_gzinflate($gzData) {
1806 // Compressed data might contain a full header, if so strip it for gzinflate()
1807 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
1809 $flg = ord( substr($gzData, 3, 1) );
1812 list($xlen) = unpack('v', substr($gzData, $i, 2) );
1813 $i = $i + 2 + $xlen;
1816 $i = strpos($gzData, "\0", $i) + 1;
1818 $i = strpos($gzData, "\0", $i) + 1;
1822 $decompressed = @gzinflate( substr($gzData, $i, -8) );
1823 if ( false !== $decompressed )
1824 return $decompressed;
1827 // Compressed data from java.util.zip.Deflater amongst others.
1828 $decompressed = @gzinflate( substr($gzData, 2) );
1829 if ( false !== $decompressed )
1830 return $decompressed;
1836 * What encoding types to accept and their priority values.
1840 * @return string Types of encoding to accept.
1842 public static function accept_encoding( $url, $args ) {
1844 $compression_enabled = WP_Http_Encoding::is_available();
1846 if ( ! $args['decompress'] ) // decompression specifically disabled
1847 $compression_enabled = false;
1848 elseif ( $args['stream'] ) // disable when streaming to file
1849 $compression_enabled = false;
1850 elseif ( isset( $args['limit_response_size'] ) ) // If only partial content is being requested, we won't be able to decompress it
1851 $compression_enabled = false;
1853 if ( $compression_enabled ) {
1854 if ( function_exists( 'gzinflate' ) )
1855 $type[] = 'deflate;q=1.0';
1857 if ( function_exists( 'gzuncompress' ) )
1858 $type[] = 'compress;q=0.5';
1860 if ( function_exists( 'gzdecode' ) )
1861 $type[] = 'gzip;q=0.5';
1864 $type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
1866 return implode(', ', $type);
1870 * What encoding the content used when it was compressed to send in the headers.
1874 * @return string Content-Encoding string to send in the header.
1876 public static function content_encoding() {
1881 * Whether the content be decoded based on the headers.
1885 * @param array|string $headers All of the available headers.
1888 public static function should_decode($headers) {
1889 if ( is_array( $headers ) ) {
1890 if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
1892 } else if ( is_string( $headers ) ) {
1893 return ( stripos($headers, 'content-encoding:') !== false );
1900 * Whether decompression and compression are supported by the PHP version.
1902 * Each function is tested instead of checking for the zlib extension, to
1903 * ensure that the functions all exist in the PHP version and aren't
1910 public static function is_available() {
1911 return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );