PageRenderTime 422ms CodeModel.GetById 141ms app.highlight 143ms RepoModel.GetById 78ms app.codeStats 1ms

/wp-includes/class-http.php

https://bitbucket.org/aqge/deptandashboard
PHP | 1741 lines | 806 code | 256 blank | 679 comment | 273 complexity | dd802c36d49f66acbe87ae314081731b MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * Simple and uniform HTTP request API.
   4 *
   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.
   7 *
   8 * @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal
   9 *
  10 * @package WordPress
  11 * @subpackage HTTP
  12 * @since 2.7.0
  13 */
  14
  15/**
  16 * WordPress HTTP Class for managing HTTP Transports and making HTTP requests.
  17 *
  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.
  21 *
  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
  26 * way.
  27 *
  28 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
  29 *
  30 * @package WordPress
  31 * @subpackage HTTP
  32 * @since 2.7.0
  33 */
  34class WP_Http {
  35
  36	/**
  37	 * Send a HTTP request to a URI.
  38	 *
  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().
  43	 *
  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.
  47	 *
  48	 * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
  49	 * 'user-agent'.
  50	 *
  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.
  56	 *
  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.
  61	 *
  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
  67	 * the request.
  68	 *
  69	 * @access public
  70	 * @since 2.7.0
  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.
  76	 *
  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
  80	 */
  81	function request( $url, $args = array() ) {
  82		global $wp_version;
  83
  84		$defaults = array(
  85			'method' => 'GET',
  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			'blocking' => true,
  91			'headers' => array(),
  92			'cookies' => array(),
  93			'body' => null,
  94			'compress' => false,
  95			'decompress' => true,
  96			'sslverify' => true,
  97			'stream' => false,
  98			'filename' => null
  99		);
 100
 101
 102		// Pre-parse for the HEAD checks.
 103		$args = wp_parse_args( $args );
 104
 105		// By default, Head requests do not cause redirections.
 106		if ( isset($args['method']) && 'HEAD' == $args['method'] )
 107			$defaults['redirection'] = 0;
 108
 109		$r = wp_parse_args( $args, $defaults );
 110		$r = apply_filters( 'http_request_args', $r, $url );
 111
 112		// Certain classes decrement this, store a copy of the original value for loop purposes.
 113		$r['_redirection'] = $r['redirection'];
 114
 115		// Allow plugins to short-circuit the request
 116		$pre = apply_filters( 'pre_http_request', false, $r, $url );
 117		if ( false !== $pre )
 118			return $pre;
 119
 120		$arrURL = parse_url( $url );
 121
 122		if ( empty( $url ) || empty( $arrURL['scheme'] ) )
 123			return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
 124
 125		if ( $this->block_request( $url ) )
 126			return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
 127
 128		// Determine if this is a https call and pass that on to the transport functions
 129		// so that we can blacklist the transports that do not support ssl verification
 130		$r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
 131
 132		// Determine if this request is to OUR install of WordPress
 133		$homeURL = parse_url( get_bloginfo( 'url' ) );
 134		$r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
 135		unset( $homeURL );
 136
 137		// If we are streaming to a file but no filename was given drop it in the WP temp dir
 138		// and pick it's name using the basename of the $url
 139		if ( $r['stream']  && empty( $r['filename'] ) )
 140			$r['filename'] = get_temp_dir() . basename( $url );
 141
 142		// Force some settings if we are streaming to a file and check for existence and perms of destination directory
 143		if ( $r['stream'] ) {
 144			$r['blocking'] = true;
 145			if ( ! is_writable( dirname( $r['filename'] ) ) )
 146				return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
 147		}
 148
 149		if ( is_null( $r['headers'] ) )
 150			$r['headers'] = array();
 151
 152		if ( ! is_array( $r['headers'] ) ) {
 153			$processedHeaders = WP_Http::processHeaders( $r['headers'] );
 154			$r['headers'] = $processedHeaders['headers'];
 155		}
 156
 157		if ( isset( $r['headers']['User-Agent'] ) ) {
 158			$r['user-agent'] = $r['headers']['User-Agent'];
 159			unset( $r['headers']['User-Agent'] );
 160		}
 161
 162		if ( isset( $r['headers']['user-agent'] ) ) {
 163			$r['user-agent'] = $r['headers']['user-agent'];
 164			unset( $r['headers']['user-agent'] );
 165		}
 166
 167		// Construct Cookie: header if any cookies are set
 168		WP_Http::buildCookieHeader( $r );
 169
 170		if ( WP_Http_Encoding::is_available() )
 171			$r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding();
 172
 173		if ( empty($r['body']) ) {
 174			$r['body'] = null;
 175			// Some servers fail when sending content without the content-length header being set.
 176			// Also, to fix another bug, we only send when doing POST and PUT and the content-length
 177			// header isn't already set.
 178			if ( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset( $r['headers']['Content-Length'] ) )
 179				$r['headers']['Content-Length'] = 0;
 180		} else {
 181			if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
 182				$r['body'] = http_build_query( $r['body'], null, '&' );
 183				if ( ! isset( $r['headers']['Content-Type'] ) )
 184					$r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
 185				$r['headers']['Content-Length'] = strlen( $r['body'] );
 186			}
 187
 188			if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
 189				$r['headers']['Content-Length'] = strlen( $r['body'] );
 190		}
 191
 192		return $this->_dispatch_request($url, $r);
 193	}
 194
 195	/**
 196	 * Tests which transports are capable of supporting the request.
 197	 *
 198	 * @since 3.2.0
 199	 * @access private
 200	 *
 201	 * @param array $args Request arguments
 202	 * @param string $url URL to Request
 203	 *
 204	 * @return string|false Class name for the first transport that claims to support the request.  False if no transport claims to support the request.
 205	 */
 206	public function _get_first_available_transport( $args, $url = null ) {
 207		$request_order = array( 'curl', 'streams', 'fsockopen' );
 208
 209		// Loop over each transport on each HTTP request looking for one which will serve this request's needs
 210		foreach ( $request_order as $transport ) {
 211			$class = 'WP_HTTP_' . $transport;
 212
 213			// Check to see if this transport is a possibility, calls the transport statically
 214			if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
 215				continue;
 216
 217			return $class;
 218		}
 219
 220		return false;
 221	}
 222
 223	/**
 224	 * Dispatches a HTTP request to a supporting transport.
 225	 *
 226	 * Tests each transport in order to find a transport which matches the request arguments.
 227	 * Also caches the transport instance to be used later.
 228	 *
 229	 * The order for blocking requests is cURL, Streams, and finally Fsockopen.
 230	 * The order for non-blocking requests is cURL, Streams and Fsockopen().
 231	 *
 232	 * There are currently issues with "localhost" not resolving correctly with DNS. This may cause
 233	 * an error "failed to open stream: A connection attempt failed because the connected party did
 234	 * not properly respond after a period of time, or established connection failed because [the]
 235	 * connected host has failed to respond."
 236	 *
 237	 * @since 3.2.0
 238	 * @access private
 239	 *
 240	 * @param string $url URL to Request
 241	 * @param array $args Request arguments
 242	 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 243	 */
 244	private function _dispatch_request( $url, $args ) {
 245		static $transports = array();
 246
 247		$class = $this->_get_first_available_transport( $args, $url );
 248		if ( !$class )
 249			return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
 250
 251		// Transport claims to support request, instantiate it and give it a whirl.
 252		if ( empty( $transports[$class] ) )
 253			$transports[$class] = new $class;
 254
 255		$response = $transports[$class]->request( $url, $args );
 256
 257		do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
 258
 259		if ( is_wp_error( $response ) )
 260			return $response;
 261
 262		return apply_filters( 'http_response', $response, $args, $url );
 263	}
 264
 265	/**
 266	 * Uses the POST HTTP method.
 267	 *
 268	 * Used for sending data that is expected to be in the body.
 269	 *
 270	 * @access public
 271	 * @since 2.7.0
 272	 *
 273	 * @param string $url URI resource.
 274	 * @param str|array $args Optional. Override the defaults.
 275	 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 276	 */
 277	function post($url, $args = array()) {
 278		$defaults = array('method' => 'POST');
 279		$r = wp_parse_args( $args, $defaults );
 280		return $this->request($url, $r);
 281	}
 282
 283	/**
 284	 * Uses the GET HTTP method.
 285	 *
 286	 * Used for sending data that is expected to be in the body.
 287	 *
 288	 * @access public
 289	 * @since 2.7.0
 290	 *
 291	 * @param string $url URI resource.
 292	 * @param str|array $args Optional. Override the defaults.
 293	 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 294	 */
 295	function get($url, $args = array()) {
 296		$defaults = array('method' => 'GET');
 297		$r = wp_parse_args( $args, $defaults );
 298		return $this->request($url, $r);
 299	}
 300
 301	/**
 302	 * Uses the HEAD HTTP method.
 303	 *
 304	 * Used for sending data that is expected to be in the body.
 305	 *
 306	 * @access public
 307	 * @since 2.7.0
 308	 *
 309	 * @param string $url URI resource.
 310	 * @param str|array $args Optional. Override the defaults.
 311	 * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 312	 */
 313	function head($url, $args = array()) {
 314		$defaults = array('method' => 'HEAD');
 315		$r = wp_parse_args( $args, $defaults );
 316		return $this->request($url, $r);
 317	}
 318
 319	/**
 320	 * Parses the responses and splits the parts into headers and body.
 321	 *
 322	 * @access public
 323	 * @static
 324	 * @since 2.7.0
 325	 *
 326	 * @param string $strResponse The full response string
 327	 * @return array Array with 'headers' and 'body' keys.
 328	 */
 329	function processResponse($strResponse) {
 330		$res = explode("\r\n\r\n", $strResponse, 2);
 331
 332		return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
 333	}
 334
 335	/**
 336	 * Transform header string into an array.
 337	 *
 338	 * If an array is given then it is assumed to be raw header data with numeric keys with the
 339	 * headers as the values. No headers must be passed that were already processed.
 340	 *
 341	 * @access public
 342	 * @static
 343	 * @since 2.7.0
 344	 *
 345	 * @param string|array $headers
 346	 * @return array Processed string headers. If duplicate headers are encountered,
 347	 * 					Then a numbered array is returned as the value of that header-key.
 348	 */
 349	public static function processHeaders($headers) {
 350		// split headers, one per array element
 351		if ( is_string($headers) ) {
 352			// tolerate line terminator: CRLF = LF (RFC 2616 19.3)
 353			$headers = str_replace("\r\n", "\n", $headers);
 354			// unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
 355			$headers = preg_replace('/\n[ \t]/', ' ', $headers);
 356			// create the headers array
 357			$headers = explode("\n", $headers);
 358		}
 359
 360		$response = array('code' => 0, 'message' => '');
 361
 362		// If a redirection has taken place, The headers for each page request may have been passed.
 363		// In this case, determine the final HTTP header and parse from there.
 364		for ( $i = count($headers)-1; $i >= 0; $i-- ) {
 365			if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
 366				$headers = array_splice($headers, $i);
 367				break;
 368			}
 369		}
 370
 371		$cookies = array();
 372		$newheaders = array();
 373		foreach ( (array) $headers as $tempheader ) {
 374			if ( empty($tempheader) )
 375				continue;
 376
 377			if ( false === strpos($tempheader, ':') ) {
 378				$stack = explode(' ', $tempheader, 3);
 379				$stack[] = '';
 380				list( , $response['code'], $response['message']) = $stack;
 381				continue;
 382			}
 383
 384			list($key, $value) = explode(':', $tempheader, 2);
 385
 386			if ( !empty( $value ) ) {
 387				$key = strtolower( $key );
 388				if ( isset( $newheaders[$key] ) ) {
 389					if ( !is_array($newheaders[$key]) )
 390						$newheaders[$key] = array($newheaders[$key]);
 391					$newheaders[$key][] = trim( $value );
 392				} else {
 393					$newheaders[$key] = trim( $value );
 394				}
 395				if ( 'set-cookie' == $key )
 396					$cookies[] = new WP_Http_Cookie( $value );
 397			}
 398		}
 399
 400		return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
 401	}
 402
 403	/**
 404	 * Takes the arguments for a ::request() and checks for the cookie array.
 405	 *
 406	 * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
 407	 * into strings and added to the Cookie: header (within the arguments array). Edits the array by
 408	 * reference.
 409	 *
 410	 * @access public
 411	 * @version 2.8.0
 412	 * @static
 413	 *
 414	 * @param array $r Full array of args passed into ::request()
 415	 */
 416	public static function buildCookieHeader( &$r ) {
 417		if ( ! empty($r['cookies']) ) {
 418			$cookies_header = '';
 419			foreach ( (array) $r['cookies'] as $cookie ) {
 420				$cookies_header .= $cookie->getHeaderValue() . '; ';
 421			}
 422			$cookies_header = substr( $cookies_header, 0, -2 );
 423			$r['headers']['cookie'] = $cookies_header;
 424		}
 425	}
 426
 427	/**
 428	 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
 429	 *
 430	 * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
 431	 * returning footer headers. Shouldn't be too difficult to support it though.
 432	 *
 433	 * @todo Add support for footer chunked headers.
 434	 * @access public
 435	 * @since 2.7.0
 436	 * @static
 437	 *
 438	 * @param string $body Body content
 439	 * @return string Chunked decoded body on success or raw body on failure.
 440	 */
 441	function chunkTransferDecode($body) {
 442		$body = str_replace(array("\r\n", "\r"), "\n", $body);
 443		// The body is not chunked encoding or is malformed.
 444		if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
 445			return $body;
 446
 447		$parsedBody = '';
 448		//$parsedHeaders = array(); Unsupported
 449
 450		while ( true ) {
 451			$hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
 452
 453			if ( $hasChunk ) {
 454				if ( empty( $match[1] ) )
 455					return $body;
 456
 457				$length = hexdec( $match[1] );
 458				$chunkLength = strlen( $match[0] );
 459
 460				$strBody = substr($body, $chunkLength, $length);
 461				$parsedBody .= $strBody;
 462
 463				$body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
 464
 465				if ( "0" == trim($body) )
 466					return $parsedBody; // Ignore footer headers.
 467			} else {
 468				return $body;
 469			}
 470		}
 471	}
 472
 473	/**
 474	 * Block requests through the proxy.
 475	 *
 476	 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
 477	 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
 478	 *
 479	 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
 480	 * file and this will only allow localhost and your blog to make requests. The constant
 481	 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
 482	 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
 483	 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
 484	 *
 485	 * @since 2.8.0
 486	 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
 487	 * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
 488	 *
 489	 * @param string $uri URI of url.
 490	 * @return bool True to block, false to allow.
 491	 */
 492	function block_request($uri) {
 493		// We don't need to block requests, because nothing is blocked.
 494		if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
 495			return false;
 496
 497		// parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
 498		// This will be displayed on blogs, which is not reasonable.
 499		$check = @parse_url($uri);
 500
 501		/* Malformed URL, can not process, but this could mean ssl, so let through anyway.
 502		 *
 503		 * This isn't very security sound. There are instances where a hacker might attempt
 504		 * to bypass the proxy and this check. However, the reason for this behavior is that
 505		 * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
 506		 * the default unsecure nature of the HTTP request.
 507		 */
 508		if ( $check === false )
 509			return false;
 510
 511		$home = parse_url( get_option('siteurl') );
 512
 513		// Don't block requests back to ourselves by default
 514		if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
 515			return apply_filters('block_local_requests', false);
 516
 517		if ( !defined('WP_ACCESSIBLE_HOSTS') )
 518			return true;
 519
 520		static $accessible_hosts;
 521		static $wildcard_regex = false;
 522		if ( null == $accessible_hosts ) {
 523			$accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
 524
 525			if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
 526				$wildcard_regex = array();
 527				foreach ( $accessible_hosts as $host )
 528					$wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
 529				$wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
 530			}
 531		}
 532
 533		if ( !empty($wildcard_regex) )
 534			return !preg_match($wildcard_regex, $check['host']);
 535		else
 536			return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
 537
 538
 539
 540	}
 541}
 542
 543/**
 544 * HTTP request method uses fsockopen function to retrieve the url.
 545 *
 546 * This would be the preferred method, but the fsockopen implementation has the most overhead of all
 547 * the HTTP transport implementations.
 548 *
 549 * @package WordPress
 550 * @subpackage HTTP
 551 * @since 2.7.0
 552 */
 553class WP_Http_Fsockopen {
 554	/**
 555	 * Send a HTTP request to a URI using fsockopen().
 556	 *
 557	 * Does not support non-blocking mode.
 558	 *
 559	 * @see WP_Http::request For default options descriptions.
 560	 *
 561	 * @since 2.7
 562	 * @access public
 563	 * @param string $url URI resource.
 564	 * @param str|array $args Optional. Override the defaults.
 565	 * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
 566	 */
 567	function request($url, $args = array()) {
 568		$defaults = array(
 569			'method' => 'GET', 'timeout' => 5,
 570			'redirection' => 5, 'httpversion' => '1.0',
 571			'blocking' => true,
 572			'headers' => array(), 'body' => null, 'cookies' => array()
 573		);
 574
 575		$r = wp_parse_args( $args, $defaults );
 576
 577		if ( isset($r['headers']['User-Agent']) ) {
 578			$r['user-agent'] = $r['headers']['User-Agent'];
 579			unset($r['headers']['User-Agent']);
 580		} else if ( isset($r['headers']['user-agent']) ) {
 581			$r['user-agent'] = $r['headers']['user-agent'];
 582			unset($r['headers']['user-agent']);
 583		}
 584
 585		// Construct Cookie: header if any cookies are set
 586		WP_Http::buildCookieHeader( $r );
 587
 588		$iError = null; // Store error number
 589		$strError = null; // Store error string
 590
 591		$arrURL = parse_url($url);
 592
 593		$fsockopen_host = $arrURL['host'];
 594
 595		$secure_transport = false;
 596
 597		if ( ! isset( $arrURL['port'] ) ) {
 598			if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
 599				$fsockopen_host = "ssl://$fsockopen_host";
 600				$arrURL['port'] = 443;
 601				$secure_transport = true;
 602			} else {
 603				$arrURL['port'] = 80;
 604			}
 605		}
 606
 607		//fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
 608		// which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
 609		if ( 'localhost' == strtolower($fsockopen_host) )
 610			$fsockopen_host = '127.0.0.1';
 611
 612		// There are issues with the HTTPS and SSL protocols that cause errors that can be safely
 613		// ignored and should be ignored.
 614		if ( true === $secure_transport )
 615			$error_reporting = error_reporting(0);
 616
 617		$startDelay = time();
 618
 619		$proxy = new WP_HTTP_Proxy();
 620
 621		if ( !WP_DEBUG ) {
 622			if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 623				$handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
 624			else
 625				$handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
 626		} else {
 627			if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 628				$handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
 629			else
 630				$handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
 631		}
 632
 633		$endDelay = time();
 634
 635		// If the delay is greater than the timeout then fsockopen shouldn't be used, because it will
 636		// cause a long delay.
 637		$elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
 638		if ( true === $elapseDelay )
 639			add_option( 'disable_fsockopen', $endDelay, null, true );
 640
 641		if ( false === $handle )
 642			return new WP_Error('http_request_failed', $iError . ': ' . $strError);
 643
 644		$timeout = (int) floor( $r['timeout'] );
 645		$utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
 646		stream_set_timeout( $handle, $timeout, $utimeout );
 647
 648		if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
 649			$requestPath = $url;
 650		else
 651			$requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
 652
 653		if ( empty($requestPath) )
 654			$requestPath .= '/';
 655
 656		$strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
 657
 658		if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 659			$strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
 660		else
 661			$strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
 662
 663		if ( isset($r['user-agent']) )
 664			$strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
 665
 666		if ( is_array($r['headers']) ) {
 667			foreach ( (array) $r['headers'] as $header => $headerValue )
 668				$strHeaders .= $header . ': ' . $headerValue . "\r\n";
 669		} else {
 670			$strHeaders .= $r['headers'];
 671		}
 672
 673		if ( $proxy->use_authentication() )
 674			$strHeaders .= $proxy->authentication_header() . "\r\n";
 675
 676		$strHeaders .= "\r\n";
 677
 678		if ( ! is_null($r['body']) )
 679			$strHeaders .= $r['body'];
 680
 681		fwrite($handle, $strHeaders);
 682
 683		if ( ! $r['blocking'] ) {
 684			fclose($handle);
 685			return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
 686		}
 687
 688		$strResponse = '';
 689		$bodyStarted = false;
 690
 691		// If streaming to a file setup the file handle
 692		if ( $r['stream'] ) {
 693			if ( ! WP_DEBUG )
 694				$stream_handle = @fopen( $r['filename'], 'w+' );
 695			else
 696				$stream_handle = fopen( $r['filename'], 'w+' );
 697			if ( ! $stream_handle )
 698				return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
 699
 700			while ( ! feof($handle) ) {
 701				$block = fread( $handle, 4096 );
 702				if ( $bodyStarted ) {
 703					fwrite( $stream_handle, $block );
 704				} else {
 705					$strResponse .= $block;
 706					if ( strpos( $strResponse, "\r\n\r\n" ) ) {
 707						$process = WP_Http::processResponse( $strResponse );
 708						$bodyStarted = true;
 709						fwrite( $stream_handle, $process['body'] );
 710						unset( $strResponse );
 711						$process['body'] = '';
 712					}
 713				}
 714			}
 715
 716			fclose( $stream_handle );
 717
 718		} else {
 719			while ( ! feof($handle) )
 720				$strResponse .= fread( $handle, 4096 );
 721
 722			$process = WP_Http::processResponse( $strResponse );
 723			unset( $strResponse );
 724		}
 725
 726		fclose( $handle );
 727
 728		if ( true === $secure_transport )
 729			error_reporting($error_reporting);
 730
 731		$arrHeaders = WP_Http::processHeaders( $process['headers'] );
 732
 733		// If location is found, then assume redirect and redirect to location.
 734		if ( isset($arrHeaders['headers']['location']) && 0 !== $r['_redirection'] ) {
 735			if ( $r['redirection']-- > 0 ) {
 736				return $this->request($arrHeaders['headers']['location'], $r);
 737			} else {
 738				return new WP_Error('http_request_failed', __('Too many redirects.'));
 739			}
 740		}
 741
 742		// If the body was chunk encoded, then decode it.
 743		if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
 744			$process['body'] = WP_Http::chunkTransferDecode($process['body']);
 745
 746		if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
 747			$process['body'] = WP_Http_Encoding::decompress( $process['body'] );
 748
 749		return array( 'headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies'], 'filename' => $r['filename'] );
 750	}
 751
 752	/**
 753	 * Whether this class can be used for retrieving an URL.
 754	 *
 755	 * @since 2.7.0
 756	 * @static
 757	 * @return boolean False means this class can not be used, true means it can.
 758	 */
 759	public static function test( $args = array() ) {
 760		if ( ! function_exists( 'fsockopen' ) )
 761			return false;
 762
 763		if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
 764			return false;
 765
 766		$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
 767
 768		if ( $is_ssl && ! extension_loaded( 'openssl' ) )
 769			return false;
 770
 771		return apply_filters( 'use_fsockopen_transport', true, $args );
 772	}
 773}
 774
 775/**
 776 * HTTP request method uses Streams to retrieve the url.
 777 *
 778 * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
 779 * to be enabled.
 780 *
 781 * Second preferred method for getting the URL, for PHP 5.
 782 *
 783 * @package WordPress
 784 * @subpackage HTTP
 785 * @since 2.7.0
 786 */
 787class WP_Http_Streams {
 788	/**
 789	 * Send a HTTP request to a URI using streams with fopen().
 790	 *
 791	 * @access public
 792	 * @since 2.7.0
 793	 *
 794	 * @param string $url
 795	 * @param str|array $args Optional. Override the defaults.
 796	 * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
 797	 */
 798	function request($url, $args = array()) {
 799		$defaults = array(
 800			'method' => 'GET', 'timeout' => 5,
 801			'redirection' => 5, 'httpversion' => '1.0',
 802			'blocking' => true,
 803			'headers' => array(), 'body' => null, 'cookies' => array()
 804		);
 805
 806		$r = wp_parse_args( $args, $defaults );
 807
 808		if ( isset($r['headers']['User-Agent']) ) {
 809			$r['user-agent'] = $r['headers']['User-Agent'];
 810			unset($r['headers']['User-Agent']);
 811		} else if ( isset($r['headers']['user-agent']) ) {
 812			$r['user-agent'] = $r['headers']['user-agent'];
 813			unset($r['headers']['user-agent']);
 814		}
 815
 816		// Construct Cookie: header if any cookies are set
 817		WP_Http::buildCookieHeader( $r );
 818
 819		$arrURL = parse_url($url);
 820
 821		if ( false === $arrURL )
 822			return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
 823
 824		if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
 825			$url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
 826
 827		// Convert Header array to string.
 828		$strHeaders = '';
 829		if ( is_array( $r['headers'] ) )
 830			foreach ( $r['headers'] as $name => $value )
 831				$strHeaders .= "{$name}: $value\r\n";
 832		else if ( is_string( $r['headers'] ) )
 833			$strHeaders = $r['headers'];
 834
 835		$is_local = isset($args['local']) && $args['local'];
 836		$ssl_verify = isset($args['sslverify']) && $args['sslverify'];
 837		if ( $is_local )
 838			$ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
 839		elseif ( ! $is_local )
 840			$ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
 841
 842		$arrContext = array('http' =>
 843			array(
 844				'method' => strtoupper($r['method']),
 845				'user_agent' => $r['user-agent'],
 846				'max_redirects' => $r['redirection'] + 1, // See #11557
 847				'protocol_version' => (float) $r['httpversion'],
 848				'header' => $strHeaders,
 849				'ignore_errors' => true, // Return non-200 requests.
 850				'timeout' => $r['timeout'],
 851				'ssl' => array(
 852						'verify_peer' => $ssl_verify,
 853						'verify_host' => $ssl_verify
 854				)
 855			)
 856		);
 857
 858		$proxy = new WP_HTTP_Proxy();
 859
 860		if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
 861			$arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
 862			$arrContext['http']['request_fulluri'] = true;
 863
 864			// We only support Basic authentication so this will only work if that is what your proxy supports.
 865			if ( $proxy->use_authentication() )
 866				$arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
 867		}
 868
 869		if ( ! empty($r['body'] ) )
 870			$arrContext['http']['content'] = $r['body'];
 871
 872		$context = stream_context_create($arrContext);
 873
 874		if ( !WP_DEBUG )
 875			$handle = @fopen($url, 'r', false, $context);
 876		else
 877			$handle = fopen($url, 'r', false, $context);
 878
 879		if ( ! $handle )
 880			return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
 881
 882		$timeout = (int) floor( $r['timeout'] );
 883		$utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
 884		stream_set_timeout( $handle, $timeout, $utimeout );
 885
 886		if ( ! $r['blocking'] ) {
 887			stream_set_blocking($handle, 0);
 888			fclose($handle);
 889			return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
 890		}
 891
 892		if ( $r['stream'] ) {
 893			if ( ! WP_DEBUG )
 894				$stream_handle = @fopen( $r['filename'], 'w+' );
 895			else
 896				$stream_handle = fopen( $r['filename'], 'w+' );
 897
 898			if ( ! $stream_handle )
 899				return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
 900
 901			stream_copy_to_stream( $handle, $stream_handle );
 902
 903			fclose( $stream_handle );
 904			$strResponse = '';
 905		} else {
 906			$strResponse = stream_get_contents( $handle );
 907		}
 908
 909		$meta = stream_get_meta_data( $handle );
 910
 911		fclose( $handle );
 912
 913		$processedHeaders = array();
 914		if ( isset( $meta['wrapper_data']['headers'] ) )
 915			$processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
 916		else
 917			$processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
 918
 919		// Streams does not provide an error code which we can use to see why the request stream stopped.
 920		// We can however test to see if a location header is present and return based on that.
 921		if ( isset($processedHeaders['headers']['location']) && 0 !== $args['_redirection'] )
 922			return new WP_Error('http_request_failed', __('Too many redirects.'));
 923
 924		if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
 925			$strResponse = WP_Http::chunkTransferDecode($strResponse);
 926
 927		if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
 928			$strResponse = WP_Http_Encoding::decompress( $strResponse );
 929
 930		return array( 'headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies'], 'filename' => $r['filename'] );
 931	}
 932
 933	/**
 934	 * Whether this class can be used for retrieving an URL.
 935	 *
 936	 * @static
 937	 * @access public
 938	 * @since 2.7.0
 939	 *
 940	 * @return boolean False means this class can not be used, true means it can.
 941	 */
 942	public static function test( $args = array() ) {
 943		if ( ! function_exists( 'fopen' ) )
 944			return false;
 945
 946		if ( ! function_exists( 'ini_get' ) || true != ini_get( 'allow_url_fopen' ) )
 947			return false;
 948
 949		$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
 950
 951		if ( $is_ssl && ! extension_loaded( 'openssl' ) )
 952			return false;
 953
 954		return apply_filters( 'use_streams_transport', true, $args );
 955	}
 956}
 957
 958/**
 959 * HTTP request method uses Curl extension to retrieve the url.
 960 *
 961 * Requires the Curl extension to be installed.
 962 *
 963 * @package WordPress
 964 * @subpackage HTTP
 965 * @since 2.7
 966 */
 967class WP_Http_Curl {
 968
 969	/**
 970	 * Temporary header storage for use with streaming to a file.
 971	 *
 972	 * @since 3.2.0
 973	 * @access private
 974	 * @var string
 975	 */
 976	private $headers = '';
 977
 978	/**
 979	 * Send a HTTP request to a URI using cURL extension.
 980	 *
 981	 * @access public
 982	 * @since 2.7.0
 983	 *
 984	 * @param string $url
 985	 * @param str|array $args Optional. Override the defaults.
 986	 * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
 987	 */
 988	function request($url, $args = array()) {
 989		$defaults = array(
 990			'method' => 'GET', 'timeout' => 5,
 991			'redirection' => 5, 'httpversion' => '1.0',
 992			'blocking' => true,
 993			'headers' => array(), 'body' => null, 'cookies' => array()
 994		);
 995
 996		$r = wp_parse_args( $args, $defaults );
 997
 998		if ( isset($r['headers']['User-Agent']) ) {
 999			$r['user-agent'] = $r['headers']['User-Agent'];
1000			unset($r['headers']['User-Agent']);
1001		} else if ( isset($r['headers']['user-agent']) ) {
1002			$r['user-agent'] = $r['headers']['user-agent'];
1003			unset($r['headers']['user-agent']);
1004		}
1005
1006		// Construct Cookie: header if any cookies are set.
1007		WP_Http::buildCookieHeader( $r );
1008
1009		$handle = curl_init();
1010
1011		// cURL offers really easy proxy support.
1012		$proxy = new WP_HTTP_Proxy();
1013
1014		if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1015
1016			curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1017			curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1018			curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1019
1020			if ( $proxy->use_authentication() ) {
1021				curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1022				curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1023			}
1024		}
1025
1026		$is_local = isset($args['local']) && $args['local'];
1027		$ssl_verify = isset($args['sslverify']) && $args['sslverify'];
1028		if ( $is_local )
1029			$ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
1030		elseif ( ! $is_local )
1031			$ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
1032
1033
1034		// CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers.  Have to use ceil since
1035		// a value of 0 will allow an unlimited timeout.
1036		$timeout = (int) ceil( $r['timeout'] );
1037		curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1038		curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1039
1040		curl_setopt( $handle, CURLOPT_URL, $url);
1041		curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1042		curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
1043		curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1044		curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1045		curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] );
1046
1047		switch ( $r['method'] ) {
1048			case 'HEAD':
1049				curl_setopt( $handle, CURLOPT_NOBODY, true );
1050				break;
1051			case 'POST':
1052				curl_setopt( $handle, CURLOPT_POST, true );
1053				curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1054				break;
1055			case 'PUT':
1056				curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
1057				curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
1058				break;
1059		}
1060
1061		if ( true === $r['blocking'] )
1062			curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( &$this, 'stream_headers' ) );
1063
1064		curl_setopt( $handle, CURLOPT_HEADER, false );
1065
1066		// If streaming to a file open a file handle, and setup our curl streaming handler
1067		if ( $r['stream'] ) {
1068			if ( ! WP_DEBUG )
1069				$stream_handle = @fopen( $r['filename'], 'w+' );
1070			else
1071				$stream_handle = fopen( $r['filename'], 'w+' );
1072			if ( ! $stream_handle )
1073				return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1074			curl_setopt( $handle, CURLOPT_FILE, $stream_handle );
1075		}
1076
1077		// The option doesn't work with safe mode or when open_basedir is set.
1078		if ( !ini_get('safe_mode') && !ini_get('open_basedir') && 0 !== $r['_redirection'] )
1079			curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true );
1080
1081		if ( !empty( $r['headers'] ) ) {
1082			// cURL expects full header strings in each element
1083			$headers = array();
1084			foreach ( $r['headers'] as $name => $value ) {
1085				$headers[] = "{$name}: $value";
1086			}
1087			curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
1088		}
1089
1090		if ( $r['httpversion'] == '1.0' )
1091			curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
1092		else
1093			curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
1094
1095		// Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
1096		// themselves... Although, it is somewhat pointless without some reference.
1097		do_action_ref_array( 'http_api_curl', array(&$handle) );
1098
1099		// We don't need to return the body, so don't. Just execute request and return.
1100		if ( ! $r['blocking'] ) {
1101			curl_exec( $handle );
1102			curl_close( $handle );
1103			return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1104		}
1105
1106		$theResponse = curl_exec( $handle );
1107		$theBody = '';
1108		$theHeaders = WP_Http::processHeaders( $this->headers );
1109
1110		if ( strlen($theResponse) > 0 && ! is_bool( $theResponse ) ) // is_bool: when using $args['stream'], curl_exec will return (bool)true
1111			$theBody = $theResponse;
1112
1113		// If no response, and It's not a HEAD request with valid headers returned
1114		if ( 0 == strlen($theResponse) && ('HEAD' != $args['method'] || empty($this->headers)) ) {
1115			if ( $curl_error = curl_error($handle) )
1116				return new WP_Error('http_request_failed', $curl_error);
1117			if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) )
1118				return new WP_Error('http_request_failed', __('Too many redirects.'));
1119		}
1120
1121		$this->headers = '';
1122
1123		$response = array();
1124		$response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
1125		$response['message'] = get_status_header_desc($response['code']);
1126
1127		curl_close( $handle );
1128
1129		if ( $r['stream'] )
1130			fclose( $stream_handle );
1131
1132		// See #11305 - When running under safe mode, redirection is disabled above. Handle it manually.
1133		if ( ! empty( $theHeaders['headers']['location'] ) && ( ini_get( 'safe_mode' ) || ini_get( 'open_basedir' ) ) && 0 !== $r['_redirection'] ) {
1134			if ( $r['redirection']-- > 0 ) {
1135				return $this->request( $theHeaders['headers']['location'], $r );
1136			} else {
1137				return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
1138			}
1139		}
1140
1141		if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
1142			$theBody = WP_Http_Encoding::decompress( $theBody );
1143
1144		return array( 'headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies'], 'filename' => $r['filename'] );
1145	}
1146
1147	/**
1148	 * Grab the headers of the cURL request
1149	 *
1150	 * Each header is sent individually to this callback, so we append to the $header property for temporary storage
1151	 *
1152	 * @since 3.2.0
1153	 * @access private
1154	 * @return int
1155	 */
1156	private function stream_headers( $handle, $headers ) {
1157		$this->headers .= $headers;
1158		return strlen( $headers );
1159	}
1160
1161	/**
1162	 * Whether this class can be used for retrieving an URL.
1163	 *
1164	 * @static
1165	 * @since 2.7.0
1166	 *
1167	 * @return boolean False means this class can not be used, true means it can.
1168	 */
1169	public static function test( $args = array() ) {
1170		if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
1171			return false;
1172
1173		$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1174
1175		if ( $is_ssl ) {
1176			$curl_version = curl_version();
1177			if ( ! (CURL_VERSION_SSL & $curl_version['features']) ) // Does this cURL version support SSL requests?
1178				return false;
1179		}
1180
1181		return apply_filters( 'use_curl_transport', true, $args );
1182	}
1183}
1184
1185/**
1186 * Adds Proxy support to the WordPress HTTP API.
1187 *
1188 * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
1189 * enable proxy support. There are also a few filters that plugins can hook into for some of the
1190 * constants.
1191 *
1192 * Please note that only BASIC authentication is supported by most transports.
1193 * cURL MAY support more methods (such as NTLM authentication) depending on your environment.
1194 *
1195 * The constants are as follows:
1196 * <ol>
1197 * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
1198 * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
1199 * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
1200 * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
1201 * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
1202 * You do not need to have localhost and the blog host in this list, because they will not be passed
1203 * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
1204 * </ol>
1205 *
1206 * An example can be as seen below.
1207 * <code>
1208 * define('WP_PROXY_HOST', '192.168.84.101');
1209 * define('WP_PROXY_PORT', '8080');
1210 * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
1211 * </code>
1212 *
1213 * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
1214 * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
1215 * @since 2.8
1216 */
1217class WP_HTTP_Proxy {
1218
1219	/**
1220	 * Whether proxy connection should be used.
1221	 *
1222	 * @since 2.8
1223	 * @use WP_PROXY_HOST
1224	 * @use WP_PROXY_PORT
1225	 *
1226	 * @return bool
1227	 */
1228	function is_enabled() {
1229		return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
1230	}
1231
1232	/**
1233	 * Whether authentication should be used.
1234	 *
1235	 * @since 2.8
1236	 * @use WP_PROXY_USERNAME
1237	 * @use WP_PROXY_PASSWORD
1238	 *
1239	 * @return bool
1240	 */
1241	function use_authentication() {
1242		return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
1243	}
1244
1245	/**
1246	 * Retrieve the host for the proxy server.
1247	 *
1248	 * @since 2.8
1249	 *
1250	 * @return string
1251	 */
1252	function host() {
1253		if ( defined('WP_PROXY_HOST') )
1254			return WP_PROXY_HOST;
1255
1256		return '';
1257	}
1258
1259	/**
1260	 * Retrieve the port for the proxy server.
1261	 *
1262	 * @since 2.8
1263	 *
1264	 * @return string
1265	 */
1266	function port() {
1267		if ( defined('WP_PROXY_PORT') )
1268			return WP_PROXY_PORT;
1269
1270		return '';
1271	}
1272
1273	/**
1274	 * Retrieve the username for proxy authentication.
1275	 *
1276	 * @since 2.8
1277	 *
1278	 * @return string
1279	 */
1280	function username() {
1281		if ( defined('WP_PROXY_USERNAME') )
1282			return WP_PROXY_USERNAME;
1283
1284		return '';
1285	}
1286
1287	/**
1288	 * Retrieve the password for proxy authentication.
1289	 *
1290	 * @since 2.8
1291	 *
1292	 * @return string
1293	 */
1294	function password() {
1295		if ( defined('WP_PROXY_PASSWORD') )
1296			return WP_PROXY_PASSWORD;
1297
1298		return '';
1299	}
1300
1301	/**
1302	 * Retrieve authentication string for proxy authentication.
1303	 *
1304	 * @since 2.8
1305	 *
1306	 * @return string
1307	 */
1308	function authentication() {
1309		return $this->username() . ':' . $this->password();
1310	}
1311
1312	/**
1313	 * Retrieve header string for proxy authentication.
1314	 *
1315	 * @since 2.8
1316	 *
1317	 * @return string
1318	 */
1319	function authentication_header() {
1320		return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
1321	}
1322
1323	/**
1324	 * Whether URL should be sent through the proxy server.
1325	 *
1326	 * We want to keep localhost and the blog URL from being sent through the proxy server, because
1327	 * some proxies can not handle this. We also have the constant available for defining other
1328	 * hosts that won't be sent through the proxy.
1329	 *
1330	 * @uses WP_PROXY_BYPASS_HOSTS
1331	 * @since 2.8.0
1332	 *
1333	 * @param string $uri URI to check.
1334	 * @return bool True, to send through the proxy and false if, the proxy should not be used.
1335	 */
1336	function send_through_proxy( $uri ) {
1337		// parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
1338		// This will be displayed on blogs, which is not reasonable.
1339		$check = @parse_url($uri);
1340
1341		// Malformed URL, can not process, but this could mean ssl, so let through anyway.
1342		if ( $check === false )
1343			return true;
1344
1345		$home = parse_url( get_option('siteurl') );
1346
1347		if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
1348			return false;
1349
1350		if ( !defined('WP_PROXY_BYPASS_HOSTS') )
1351			return true;
1352
1353		static $bypass_hosts;
1354		static $wildcard_regex = false;
1355		if ( null == $bypass_hosts ) {
1356			$bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
1357
1358			if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
1359				$wildcard_regex = array();
1360				foreach ( $bypass_hosts as $host )
1361					$wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
1362				$wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
1363			}
1364		}
1365
1366		if ( !empty($wildcard_regex) )
1367			return !preg_match($wildcard_regex, $check['host']);
1368		else
1369			return !in_array( $check['host'], $bypass_hosts );
1370	}
1371}
1372/**
1373 * Internal representation of a single cookie.
1374 *
1375 * Returned cookies are represented using this class, and when cookies are set, if they are not
1376 * already a WP_Http_Cookie() object, then they are turned into one.
1377 *
1378 * @todo The WordPress convention is to use underscores instead of camelCase for function and method
1379 * names. Need to switch to use underscores instead for the methods.
1380 *
1381 * @package WordPress
1382 * @subpackage HTTP
1383 * @since 2.8.0
1384 */
1385class WP_Http_Cookie {
1386
1387	/**
1388	 * Cookie name.
1389	 *
1390	 * @since 2.8.0
1391	 * @var string
1392	 */
1393	var $name;
1394
1395	/**
1396	 * Cookie value.
1397	 *
1398	 * @since 2.8.0
1399	 * @var string
1400	 */
1401	var $value;
1402
1403	/**
1404	 * When the cookie expires.
1405	 *
1406	 * @since 2.8.0
1407	 * @var string
1408	 */
1409	var $expires;
1410
1411	/**
1412	 * Cookie URL path.
1413	 *
1414	 * @since 2.8.0
1415	 * @var string
1416	 */
1417	var $path;
1418
1419	/**
1420	 * Cookie Domain.
1421	 *
1422	 * @since 2.8.0
1423	 * @var string
1424	 */
1425	var $domain;
1426
1427	/**
1428	 * Sets up this cookie object.
1429	 *
1430	 * The parameter $data should be either an associative array containing the indices names below
1431	 * or a header string detailing it.
1432	 *
1433	 * If it's an array, it should include the following elements:
1434	 * <ol>
1435	 * <li>Name</li>
1436	 * <li>Value - should NOT be urlencoded already.</li>
1437	 * <li>Expires - (optional) String or int (UNIX timestamp).</li>
1438	 * <li>Path (optional)</li>
1439	 * <li>Domain (optional)</li>
1440	 * </ol>
1441	 *
1442	 * @access public
1443	 * @since 2.8.0
1444	 *
1445	 * @param string|array $data Raw cookie data.
1446	 */
1447	function __construct( $data ) {
1448		if ( is_string( $data ) ) {
1449			// Assume it's a header string direct from a previous request
1450			$pairs = explode( ';', $data );
1451
1452			// Special handling for first pair; name=value. Also be careful of "=" in value
1453			$name  = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
1454			$value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
1455			$this->name  = $name;
1456			$this->value = urldecode( $value );
1457			array_shift( $pairs ); //Removes name=value from items.
1458
1459			// Set everything else as a property
1460			foreach ( $pairs as $pair ) {
1461				$pair = rtrim($pair);
1462				if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
1463					continue;
1464
1465				list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
1466				$key = strtolower( trim( $key ) );
1467				if ( 'expires' == $key )
1468					$val = strtotime( $val );
1469				$this->$key = $val;
1470			}
1471		} else {
1472			if ( !isset( $data['name'] ) )
1473				return false;
1474
1475			// Set properties based directly on parameters
1476			$this->name   = $data['name'];
1477			$this->value  = isset( $data['value'] ) ? $data['value'] : '';
1478			$this->path   = isset( $data['path'] ) ? $data['path'] : '';
1479			$this->domain = isset( $data['domain'] ) ? $data['domain'] : '';
1480
1481			if ( isset( $data['expires'] ) )
1482				$this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
1483			else
1484				$this->expires = null;
1485		}
1486	}
1487
1488	/**
1489	 * Confirms that it's OK to send this cookie to the URL checked against.
1490	 *
1491	 * Decision is based on RFC 2109/2965, so look there for details on validity.
1492	 *
1493	 * @access public
1494	 * @since 2.8.0
1495	 *
1496	 * @param string $url URL you intend to send this cookie to
1497	 * @return boolean TRUE if allowed, FALSE otherwise.
1498	 */
1499	function test( $url ) {
1500		// Expires - if expired then nothing else …

Large files files are truncated, but you can click here to view the full file