PageRenderTime 201ms CodeModel.GetById 81ms app.highlight 78ms RepoModel.GetById 22ms app.codeStats 1ms

/wp-includes/class-http.php

https://bitbucket.org/acipriani/madeinapulia.com
PHP | 2268 lines | 975 code | 306 blank | 987 comment | 337 complexity | a92923fbd3361aef7afbad9b137d4cff 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 https://core.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 used to consistently make outgoing HTTP requests easy for developers
  19 * while still being compatible with the many PHP configurations under which
  20 * WordPress runs.
  21 *
  22 * Debugging includes several actions, which pass different variables for debugging the HTTP API.
  23 *
  24 * @package WordPress
  25 * @subpackage HTTP
  26 * @since 2.7.0
  27 */
  28class WP_Http {
  29
  30	/**
  31	 * Send an HTTP request to a URI.
  32	 *
  33	 * Please note: The only URI that are supported in the HTTP Transport implementation
  34	 * are the HTTP and HTTPS protocols.
  35	 *
  36	 * @access public
  37	 * @since 2.7.0
  38	 *
  39	 * @param string       $url  The request URL.
  40	 * @param string|array $args {
  41	 *     Optional. Array or string of HTTP request arguments.
  42	 *
  43	 *     @type string       $method              Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
  44	 *                                             Some transports technically allow others, but should not be
  45	 *                                             assumed. Default 'GET'.
  46	 *     @type int          $timeout             How long the connection should stay open in seconds. Default 5.
  47	 *     @type int          $redirection         Number of allowed redirects. Not supported by all transports
  48	 *                                             Default 5.
  49	 *     @type string       $httpversion         Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
  50	 *                                             Default '1.0'.
  51	 *     @type string       $user-agent          User-agent value sent.
  52	 *                                             Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
  53	 *     @type bool         $reject_unsafe_urls  Whether to pass URLs through {@see wp_http_validate_url()}.
  54	 *                                             Default false.
  55	 *     @type bool         $blocking            Whether the calling code requires the result of the request.
  56	 *                                             If set to false, the request will be sent to the remote server,
  57	 *                                             and processing returned to the calling code immediately, the caller
  58	 *                                             will know if the request succeeded or failed, but will not receive
  59	 *                                             any response from the remote server. Default true.
  60	 *     @type string|array $headers             Array or string of headers to send with the request.
  61	 *                                             Default empty array.
  62	 *     @type array        $cookies             List of cookies to send with the request. Default empty array.
  63	 *     @type string|array $body                Body to send with the request. Default null.
  64	 *     @type bool         $compress            Whether to compress the $body when sending the request.
  65	 *                                             Default false.
  66	 *     @type bool         $decompress          Whether to decompress a compressed response. If set to false and
  67	 *                                             compressed content is returned in the response anyway, it will
  68	 *                                             need to be separately decompressed. Default true.
  69	 *     @type bool         $sslverify           Whether to verify SSL for the request. Default true.
  70	 *     @type string       sslcertificates      Absolute path to an SSL certificate .crt file.
  71	 *                                             Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
  72	 *     @type bool         $stream              Whether to stream to a file. If set to true and no filename was
  73	 *                                             given, it will be droped it in the WP temp dir and its name will
  74	 *                                             be set using the basename of the URL. Default false.
  75	 *     @type string       $filename            Filename of the file to write to when streaming. $stream must be
  76	 *                                             set to true. Default null.
  77	 *     @type int          $limit_response_size Size in bytes to limit the response to. Default null.
  78	 *
  79	 * }
  80	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  81	 *                        A WP_Error instance upon error.
  82	 */
  83	public function request( $url, $args = array() ) {
  84		global $wp_version;
  85
  86		$defaults = array(
  87			'method' => 'GET',
  88			/**
  89			 * Filter the timeout value for an HTTP request.
  90			 *
  91			 * @since 2.7.0
  92			 *
  93			 * @param int $timeout_value Time in seconds until a request times out.
  94			 *                           Default 5.
  95			 */
  96			'timeout' => apply_filters( 'http_request_timeout', 5 ),
  97			/**
  98			 * Filter the number of redirects allowed during an HTTP request.
  99			 *
 100			 * @since 2.7.0
 101			 *
 102			 * @param int $redirect_count Number of redirects allowed. Default 5.
 103			 */
 104			'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
 105			/**
 106			 * Filter the version of the HTTP protocol used in a request.
 107			 *
 108			 * @since 2.7.0
 109			 *
 110			 * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
 111			 *                        Default '1.0'.
 112			 */
 113			'httpversion' => apply_filters( 'http_request_version', '1.0' ),
 114			/**
 115			 * Filter the user agent value sent with an HTTP request.
 116			 *
 117			 * @since 2.7.0
 118			 *
 119			 * @param string $user_agent WordPress user agent string.
 120			 */
 121			'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
 122			/**
 123			 * Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
 124			 *
 125			 * @since 3.6.0
 126			 *
 127			 * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
 128			 *                       Default false.
 129			 */
 130			'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
 131			'blocking' => true,
 132			'headers' => array(),
 133			'cookies' => array(),
 134			'body' => null,
 135			'compress' => false,
 136			'decompress' => true,
 137			'sslverify' => true,
 138			'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
 139			'stream' => false,
 140			'filename' => null,
 141			'limit_response_size' => null,
 142		);
 143
 144		// Pre-parse for the HEAD checks.
 145		$args = wp_parse_args( $args );
 146
 147		// By default, Head requests do not cause redirections.
 148		if ( isset($args['method']) && 'HEAD' == $args['method'] )
 149			$defaults['redirection'] = 0;
 150
 151		$r = wp_parse_args( $args, $defaults );
 152		/**
 153		 * Filter the arguments used in an HTTP request.
 154		 *
 155		 * @since 2.7.0
 156		 *
 157		 * @param array  $r   An array of HTTP request arguments.
 158		 * @param string $url The request URL.
 159		 */
 160		$r = apply_filters( 'http_request_args', $r, $url );
 161
 162		// The transports decrement this, store a copy of the original value for loop purposes.
 163		if ( ! isset( $r['_redirection'] ) )
 164			$r['_redirection'] = $r['redirection'];
 165
 166		/**
 167		 * Filter whether to preempt an HTTP request's return.
 168		 *
 169		 * Returning a truthy value to the filter will short-circuit
 170		 * the HTTP request and return early with that value.
 171		 *
 172		 * @since 2.9.0
 173		 *
 174		 * @param bool   $preempt Whether to preempt an HTTP request return. Default false.
 175		 * @param array  $r       HTTP request arguments.
 176		 * @param string $url     The request URL.
 177		 */
 178		$pre = apply_filters( 'pre_http_request', false, $r, $url );
 179		if ( false !== $pre )
 180			return $pre;
 181
 182		if ( function_exists( 'wp_kses_bad_protocol' ) ) {
 183			if ( $r['reject_unsafe_urls'] )
 184				$url = wp_http_validate_url( $url );
 185			$url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
 186		}
 187
 188		$arrURL = @parse_url( $url );
 189
 190		if ( empty( $url ) || empty( $arrURL['scheme'] ) )
 191			return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
 192
 193		if ( $this->block_request( $url ) )
 194			return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
 195
 196		/*
 197		 * Determine if this is a https call and pass that on to the transport functions
 198		 * so that we can blacklist the transports that do not support ssl verification
 199		 */
 200		$r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
 201
 202		// Determine if this request is to OUR install of WordPress.
 203		$homeURL = parse_url( get_bloginfo( 'url' ) );
 204		$r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
 205		unset( $homeURL );
 206
 207		/*
 208		 * If we are streaming to a file but no filename was given drop it in the WP temp dir
 209		 * and pick its name using the basename of the $url.
 210		 */
 211		if ( $r['stream']  && empty( $r['filename'] ) ) {
 212			$r['filename'] = wp_unique_filename( get_temp_dir(), basename( $url ) );
 213		}
 214
 215		/*
 216		 * Force some settings if we are streaming to a file and check for existence and perms
 217		 * of destination directory.
 218		 */
 219		if ( $r['stream'] ) {
 220			$r['blocking'] = true;
 221			if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
 222				return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
 223		}
 224
 225		if ( is_null( $r['headers'] ) )
 226			$r['headers'] = array();
 227
 228		if ( ! is_array( $r['headers'] ) ) {
 229			$processedHeaders = WP_Http::processHeaders( $r['headers'], $url );
 230			$r['headers'] = $processedHeaders['headers'];
 231		}
 232
 233		if ( isset( $r['headers']['User-Agent'] ) ) {
 234			$r['user-agent'] = $r['headers']['User-Agent'];
 235			unset( $r['headers']['User-Agent'] );
 236		}
 237
 238		if ( isset( $r['headers']['user-agent'] ) ) {
 239			$r['user-agent'] = $r['headers']['user-agent'];
 240			unset( $r['headers']['user-agent'] );
 241		}
 242
 243		if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
 244			$r['headers']['connection'] = 'close';
 245		}
 246
 247		// Construct Cookie: header if any cookies are set.
 248		WP_Http::buildCookieHeader( $r );
 249
 250		// Avoid issues where mbstring.func_overload is enabled.
 251		mbstring_binary_safe_encoding();
 252
 253		if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
 254			if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
 255				$r['headers']['Accept-Encoding'] = $encoding;
 256		}
 257
 258		if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
 259			if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
 260				$r['body'] = http_build_query( $r['body'], null, '&' );
 261
 262				if ( ! isset( $r['headers']['Content-Type'] ) )
 263					$r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
 264			}
 265
 266			if ( '' === $r['body'] )
 267				$r['body'] = null;
 268
 269			if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
 270				$r['headers']['Content-Length'] = strlen( $r['body'] );
 271		}
 272
 273		$response = $this->_dispatch_request( $url, $r );
 274
 275		reset_mbstring_encoding();
 276
 277		if ( is_wp_error( $response ) )
 278			return $response;
 279
 280		// Append cookies that were used in this request to the response
 281		if ( ! empty( $r['cookies'] ) ) {
 282			$cookies_set = wp_list_pluck( $response['cookies'], 'name' );
 283			foreach ( $r['cookies'] as $cookie ) {
 284				if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
 285					$response['cookies'][] = $cookie;
 286				}
 287			}
 288		}
 289
 290		return $response;
 291	}
 292
 293	/**
 294	 * Tests which transports are capable of supporting the request.
 295	 *
 296	 * @since 3.2.0
 297	 * @access private
 298	 *
 299	 * @param array $args Request arguments
 300	 * @param string $url URL to Request
 301	 *
 302	 * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
 303	 */
 304	public function _get_first_available_transport( $args, $url = null ) {
 305		/**
 306		 * Filter which HTTP transports are available and in what order.
 307		 *
 308		 * @since 3.7.0
 309		 *
 310		 * @param array  $value Array of HTTP transports to check. Default array contains
 311		 *                      'curl', and 'streams', in that order.
 312		 * @param array  $args  HTTP request arguments.
 313		 * @param string $url   The URL to request.
 314		 */
 315		$request_order = apply_filters( 'http_api_transports', array( 'curl', 'streams' ), $args, $url );
 316
 317		// Loop over each transport on each HTTP request looking for one which will serve this request's needs.
 318		foreach ( $request_order as $transport ) {
 319			$class = 'WP_HTTP_' . $transport;
 320
 321			// Check to see if this transport is a possibility, calls the transport statically.
 322			if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
 323				continue;
 324
 325			return $class;
 326		}
 327
 328		return false;
 329	}
 330
 331	/**
 332	 * Dispatches a HTTP request to a supporting transport.
 333	 *
 334	 * Tests each transport in order to find a transport which matches the request arguments.
 335	 * Also caches the transport instance to be used later.
 336	 *
 337	 * The order for requests is cURL, and then PHP Streams.
 338	 *
 339	 * @since 3.2.0
 340	 * @access private
 341	 *
 342	 * @param string $url URL to Request
 343	 * @param array $args Request arguments
 344	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 345	 */
 346	private function _dispatch_request( $url, $args ) {
 347		static $transports = array();
 348
 349		$class = $this->_get_first_available_transport( $args, $url );
 350		if ( !$class )
 351			return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
 352
 353		// Transport claims to support request, instantiate it and give it a whirl.
 354		if ( empty( $transports[$class] ) )
 355			$transports[$class] = new $class;
 356
 357		$response = $transports[$class]->request( $url, $args );
 358
 359		/**
 360		 * Fires after an HTTP API response is received and before the response is returned.
 361		 *
 362		 * @since 2.8.0
 363		 *
 364		 * @param array|WP_Error $response HTTP response or WP_Error object.
 365		 * @param string         $context  Context under which the hook is fired.
 366		 * @param string         $class    HTTP transport used.
 367		 * @param array          $args     HTTP request arguments.
 368		 * @param string         $url      The request URL.
 369		 */
 370		do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
 371
 372		if ( is_wp_error( $response ) )
 373			return $response;
 374
 375		/**
 376		 * Filter the HTTP API response immediately before the response is returned.
 377		 *
 378		 * @since 2.9.0
 379		 *
 380		 * @param array  $response HTTP response.
 381		 * @param array  $args     HTTP request arguments.
 382		 * @param string $url      The request URL.
 383		 */
 384		return apply_filters( 'http_response', $response, $args, $url );
 385	}
 386
 387	/**
 388	 * Uses the POST HTTP method.
 389	 *
 390	 * Used for sending data that is expected to be in the body.
 391	 *
 392	 * @access public
 393	 * @since 2.7.0
 394	 *
 395	 * @param string       $url  The request URL.
 396	 * @param string|array $args Optional. Override the defaults.
 397	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 398	 */
 399	public function post($url, $args = array()) {
 400		$defaults = array('method' => 'POST');
 401		$r = wp_parse_args( $args, $defaults );
 402		return $this->request($url, $r);
 403	}
 404
 405	/**
 406	 * Uses the GET HTTP method.
 407	 *
 408	 * Used for sending data that is expected to be in the body.
 409	 *
 410	 * @access public
 411	 * @since 2.7.0
 412	 *
 413	 * @param string $url The request URL.
 414	 * @param string|array $args Optional. Override the defaults.
 415	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 416	 */
 417	public function get($url, $args = array()) {
 418		$defaults = array('method' => 'GET');
 419		$r = wp_parse_args( $args, $defaults );
 420		return $this->request($url, $r);
 421	}
 422
 423	/**
 424	 * Uses the HEAD HTTP method.
 425	 *
 426	 * Used for sending data that is expected to be in the body.
 427	 *
 428	 * @access public
 429	 * @since 2.7.0
 430	 *
 431	 * @param string $url The request URL.
 432	 * @param string|array $args Optional. Override the defaults.
 433	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 434	 */
 435	public function head($url, $args = array()) {
 436		$defaults = array('method' => 'HEAD');
 437		$r = wp_parse_args( $args, $defaults );
 438		return $this->request($url, $r);
 439	}
 440
 441	/**
 442	 * Parses the responses and splits the parts into headers and body.
 443	 *
 444	 * @access public
 445	 * @static
 446	 * @since 2.7.0
 447	 *
 448	 * @param string $strResponse The full response string
 449	 * @return array Array with 'headers' and 'body' keys.
 450	 */
 451	public static function processResponse($strResponse) {
 452		$res = explode("\r\n\r\n", $strResponse, 2);
 453
 454		return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
 455	}
 456
 457	/**
 458	 * Transform header string into an array.
 459	 *
 460	 * If an array is given then it is assumed to be raw header data with numeric keys with the
 461	 * headers as the values. No headers must be passed that were already processed.
 462	 *
 463	 * @access public
 464	 * @static
 465	 * @since 2.7.0
 466	 *
 467	 * @param string|array $headers
 468	 * @param string $url The URL that was requested
 469	 * @return array Processed string headers. If duplicate headers are encountered,
 470	 * 					Then a numbered array is returned as the value of that header-key.
 471	 */
 472	public static function processHeaders( $headers, $url = '' ) {
 473		// Split headers, one per array element.
 474		if ( is_string($headers) ) {
 475			// Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
 476			$headers = str_replace("\r\n", "\n", $headers);
 477			/*
 478			 * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
 479			 * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
 480			 */
 481			$headers = preg_replace('/\n[ \t]/', ' ', $headers);
 482			// Create the headers array.
 483			$headers = explode("\n", $headers);
 484		}
 485
 486		$response = array('code' => 0, 'message' => '');
 487
 488		/*
 489		 * If a redirection has taken place, The headers for each page request may have been passed.
 490		 * In this case, determine the final HTTP header and parse from there.
 491		 */
 492		for ( $i = count($headers)-1; $i >= 0; $i-- ) {
 493			if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
 494				$headers = array_splice($headers, $i);
 495				break;
 496			}
 497		}
 498
 499		$cookies = array();
 500		$newheaders = array();
 501		foreach ( (array) $headers as $tempheader ) {
 502			if ( empty($tempheader) )
 503				continue;
 504
 505			if ( false === strpos($tempheader, ':') ) {
 506				$stack = explode(' ', $tempheader, 3);
 507				$stack[] = '';
 508				list( , $response['code'], $response['message']) = $stack;
 509				continue;
 510			}
 511
 512			list($key, $value) = explode(':', $tempheader, 2);
 513
 514			$key = strtolower( $key );
 515			$value = trim( $value );
 516
 517			if ( isset( $newheaders[ $key ] ) ) {
 518				if ( ! is_array( $newheaders[ $key ] ) )
 519					$newheaders[$key] = array( $newheaders[ $key ] );
 520				$newheaders[ $key ][] = $value;
 521			} else {
 522				$newheaders[ $key ] = $value;
 523			}
 524			if ( 'set-cookie' == $key )
 525				$cookies[] = new WP_Http_Cookie( $value, $url );
 526		}
 527
 528		// Cast the Response Code to an int
 529		$response['code'] = intval( $response['code'] );
 530
 531		return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
 532	}
 533
 534	/**
 535	 * Takes the arguments for a ::request() and checks for the cookie array.
 536	 *
 537	 * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
 538	 * which are each parsed into strings and added to the Cookie: header (within the arguments array).
 539	 * Edits the array by reference.
 540	 *
 541	 * @access public
 542	 * @version 2.8.0
 543	 * @static
 544	 *
 545	 * @param array $r Full array of args passed into ::request()
 546	 */
 547	public static function buildCookieHeader( &$r ) {
 548		if ( ! empty($r['cookies']) ) {
 549			// Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
 550			foreach ( $r['cookies'] as $name => $value ) {
 551				if ( ! is_object( $value ) )
 552					$r['cookies'][ $name ] = new WP_HTTP_Cookie( array( 'name' => $name, 'value' => $value ) );
 553			}
 554
 555			$cookies_header = '';
 556			foreach ( (array) $r['cookies'] as $cookie ) {
 557				$cookies_header .= $cookie->getHeaderValue() . '; ';
 558			}
 559
 560			$cookies_header = substr( $cookies_header, 0, -2 );
 561			$r['headers']['cookie'] = $cookies_header;
 562		}
 563	}
 564
 565	/**
 566	 * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
 567	 *
 568	 * Based off the HTTP http_encoding_dechunk function.
 569	 *
 570	 * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
 571	 *
 572	 * @access public
 573	 * @since 2.7.0
 574	 * @static
 575	 *
 576	 * @param string $body Body content
 577	 * @return string Chunked decoded body on success or raw body on failure.
 578	 */
 579	public static function chunkTransferDecode( $body ) {
 580		// The body is not chunked encoded or is malformed.
 581		if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
 582			return $body;
 583
 584		$parsed_body = '';
 585
 586		// We'll be altering $body, so need a backup in case of error.
 587		$body_original = $body;
 588
 589		while ( true ) {
 590			$has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
 591			if ( ! $has_chunk || empty( $match[1] ) )
 592				return $body_original;
 593
 594			$length = hexdec( $match[1] );
 595			$chunk_length = strlen( $match[0] );
 596
 597			// Parse out the chunk of data.
 598			$parsed_body .= substr( $body, $chunk_length, $length );
 599
 600			// Remove the chunk from the raw data.
 601			$body = substr( $body, $length + $chunk_length );
 602
 603			// End of the document.
 604			if ( '0' === trim( $body ) )
 605				return $parsed_body;
 606		}
 607	}
 608
 609	/**
 610	 * Block requests through the proxy.
 611	 *
 612	 * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
 613	 * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
 614	 *
 615	 * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
 616	 * file and this will only allow localhost and your blog to make requests. The constant
 617	 * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
 618	 * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
 619	 * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
 620	 *
 621	 * @since 2.8.0
 622	 * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
 623	 * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
 624	 *
 625	 * @param string $uri URI of url.
 626	 * @return bool True to block, false to allow.
 627	 */
 628	public function block_request($uri) {
 629		// We don't need to block requests, because nothing is blocked.
 630		if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
 631			return false;
 632
 633		$check = parse_url($uri);
 634		if ( ! $check )
 635			return true;
 636
 637		$home = parse_url( get_option('siteurl') );
 638
 639		// Don't block requests back to ourselves by default.
 640		if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
 641			/**
 642			 * Filter whether to block local requests through the proxy.
 643			 *
 644			 * @since 2.8.0
 645			 *
 646			 * @param bool $block Whether to block local requests through proxy.
 647			 *                    Default false.
 648			 */
 649			return apply_filters( 'block_local_requests', false );
 650		}
 651
 652		if ( !defined('WP_ACCESSIBLE_HOSTS') )
 653			return true;
 654
 655		static $accessible_hosts;
 656		static $wildcard_regex = false;
 657		if ( null == $accessible_hosts ) {
 658			$accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
 659
 660			if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
 661				$wildcard_regex = array();
 662				foreach ( $accessible_hosts as $host )
 663					$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
 664				$wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
 665			}
 666		}
 667
 668		if ( !empty($wildcard_regex) )
 669			return !preg_match($wildcard_regex, $check['host']);
 670		else
 671			return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
 672
 673	}
 674
 675	/**
 676	 * A wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7
 677	 *
 678	 * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute url's, including
 679	 * schemeless and relative url's with :// in the path, this works around those
 680	 * limitations providing a standard output on PHP 5.2~5.4+.
 681	 *
 682	 * Error suppression is used as prior to PHP 5.3.3, an E_WARNING would be generated
 683	 * when URL parsing failed.
 684	 *
 685	 * @since 4.1.0
 686	 * @access protected
 687	 *
 688	 * @param string $url The URL to parse.
 689	 * @return bool|array False on failure; Array of URL components on success;
 690	 *                    See parse_url()'s return values.
 691	 */
 692	protected static function parse_url( $url ) {
 693		$parts = @parse_url( $url );
 694		if ( ! $parts ) {
 695			// < PHP 5.4.7 compat, trouble with relative paths including a scheme break in the path
 696			if ( '/' == $url[0] && false !== strpos( $url, '://' ) ) {
 697				// Since we know it's a relative path, prefix with a scheme/host placeholder and try again
 698				if ( ! $parts = @parse_url( 'placeholder://placeholder' . $url ) ) {
 699					return $parts;
 700				}
 701				// Remove the placeholder values
 702				unset( $parts['scheme'], $parts['host'] );
 703			} else {
 704				return $parts;
 705			}
 706		}
 707
 708		// < PHP 5.4.7 compat, doesn't detect schemeless URL's host field
 709		if ( '//' == substr( $url, 0, 2 ) && ! isset( $parts['host'] ) ) {
 710			list( $parts['host'], $slashless_path ) = explode( '/', substr( $parts['path'], 2 ), 2 );
 711			$parts['path'] = "/{$slashless_path}";
 712		}
 713
 714		return $parts;
 715	}
 716
 717	/**
 718	 * Converts a relative URL to an absolute URL relative to a given URL.
 719	 *
 720	 * If an Absolute URL is provided, no processing of that URL is done.
 721	 *
 722	 * @since 3.4.0
 723	 *
 724	 * @access public
 725	 * @param string $maybe_relative_path The URL which might be relative
 726	 * @param string $url                 The URL which $maybe_relative_path is relative to
 727	 * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
 728	 */
 729	public static function make_absolute_url( $maybe_relative_path, $url ) {
 730		if ( empty( $url ) )
 731			return $maybe_relative_path;
 732
 733		if ( ! $url_parts = WP_HTTP::parse_url( $url ) ) {
 734			return $maybe_relative_path;
 735		}
 736
 737		if ( ! $relative_url_parts = WP_HTTP::parse_url( $maybe_relative_path ) ) {
 738			return $maybe_relative_path;
 739		}
 740
 741		// Check for a scheme on the 'relative' url
 742		if ( ! empty( $relative_url_parts['scheme'] ) ) {
 743			return $maybe_relative_path;
 744		}
 745
 746		$absolute_path = $url_parts['scheme'] . '://';
 747
 748		// Schemeless URL's will make it this far, so we check for a host in the relative url and convert it to a protocol-url
 749		if ( isset( $relative_url_parts['host'] ) ) {
 750			$absolute_path .= $relative_url_parts['host'];
 751			if ( isset( $relative_url_parts['port'] ) )
 752				$absolute_path .= ':' . $relative_url_parts['port'];
 753		} else {
 754			$absolute_path .= $url_parts['host'];
 755			if ( isset( $url_parts['port'] ) )
 756				$absolute_path .= ':' . $url_parts['port'];
 757		}
 758
 759		// Start off with the Absolute URL path.
 760		$path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
 761
 762		// If it's a root-relative path, then great.
 763		if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
 764			$path = $relative_url_parts['path'];
 765
 766		// Else it's a relative path.
 767		} elseif ( ! empty( $relative_url_parts['path'] ) ) {
 768			// Strip off any file components from the absolute path.
 769			$path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
 770
 771			// Build the new path.
 772			$path .= $relative_url_parts['path'];
 773
 774			// Strip all /path/../ out of the path.
 775			while ( strpos( $path, '../' ) > 1 ) {
 776				$path = preg_replace( '![^/]+/\.\./!', '', $path );
 777			}
 778
 779			// Strip any final leading ../ from the path.
 780			$path = preg_replace( '!^/(\.\./)+!', '', $path );
 781		}
 782
 783		// Add the Query string.
 784		if ( ! empty( $relative_url_parts['query'] ) )
 785			$path .= '?' . $relative_url_parts['query'];
 786
 787		return $absolute_path . '/' . ltrim( $path, '/' );
 788	}
 789
 790	/**
 791	 * Handles HTTP Redirects and follows them if appropriate.
 792	 *
 793	 * @since 3.7.0
 794	 *
 795	 * @param string $url The URL which was requested.
 796	 * @param array $args The Arguments which were used to make the request.
 797	 * @param array $response The Response of the HTTP request.
 798	 * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
 799	 */
 800	public static function handle_redirects( $url, $args, $response ) {
 801		// If no redirects are present, or, redirects were not requested, perform no action.
 802		if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
 803			return false;
 804
 805		// Only perform redirections on redirection http codes.
 806		if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
 807			return false;
 808
 809		// Don't redirect if we've run out of redirects.
 810		if ( $args['redirection']-- <= 0 )
 811			return new WP_Error( 'http_request_failed', __('Too many redirects.') );
 812
 813		$redirect_location = $response['headers']['location'];
 814
 815		// If there were multiple Location headers, use the last header specified.
 816		if ( is_array( $redirect_location ) )
 817			$redirect_location = array_pop( $redirect_location );
 818
 819		$redirect_location = WP_HTTP::make_absolute_url( $redirect_location, $url );
 820
 821		// POST requests should not POST to a redirected location.
 822		if ( 'POST' == $args['method'] ) {
 823			if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
 824				$args['method'] = 'GET';
 825		}
 826
 827		// Include valid cookies in the redirect process.
 828		if ( ! empty( $response['cookies'] ) ) {
 829			foreach ( $response['cookies'] as $cookie ) {
 830				if ( $cookie->test( $redirect_location ) )
 831					$args['cookies'][] = $cookie;
 832			}
 833		}
 834
 835		return wp_remote_request( $redirect_location, $args );
 836	}
 837
 838	/**
 839	 * Determines if a specified string represents an IP address or not.
 840	 *
 841	 * This function also detects the type of the IP address, returning either
 842	 * '4' or '6' to represent a IPv4 and IPv6 address respectively.
 843	 * This does not verify if the IP is a valid IP, only that it appears to be
 844	 * an IP address.
 845	 *
 846	 * @see http://home.deds.nl/~aeron/regex/ for IPv6 regex
 847	 *
 848	 * @since 3.7.0
 849	 * @static
 850	 *
 851	 * @param string $maybe_ip A suspected IP address
 852	 * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
 853	 */
 854	public static function is_ip_address( $maybe_ip ) {
 855		if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
 856			return 4;
 857
 858		if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) )
 859			return 6;
 860
 861		return false;
 862	}
 863
 864}
 865
 866/**
 867 * HTTP request method uses PHP Streams to retrieve the url.
 868 *
 869 * @since 2.7.0
 870 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
 871 */
 872class WP_Http_Streams {
 873	/**
 874	 * Send a HTTP request to a URI using PHP Streams.
 875	 *
 876	 * @see WP_Http::request For default options descriptions.
 877	 *
 878	 * @since 2.7.0
 879	 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
 880	 *
 881	 * @access public
 882	 * @param string $url The request URL.
 883	 * @param string|array $args Optional. Override the defaults.
 884	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
 885	 */
 886	public function request($url, $args = array()) {
 887		$defaults = array(
 888			'method' => 'GET', 'timeout' => 5,
 889			'redirection' => 5, 'httpversion' => '1.0',
 890			'blocking' => true,
 891			'headers' => array(), 'body' => null, 'cookies' => array()
 892		);
 893
 894		$r = wp_parse_args( $args, $defaults );
 895
 896		if ( isset($r['headers']['User-Agent']) ) {
 897			$r['user-agent'] = $r['headers']['User-Agent'];
 898			unset($r['headers']['User-Agent']);
 899		} else if ( isset($r['headers']['user-agent']) ) {
 900			$r['user-agent'] = $r['headers']['user-agent'];
 901			unset($r['headers']['user-agent']);
 902		}
 903
 904		// Construct Cookie: header if any cookies are set.
 905		WP_Http::buildCookieHeader( $r );
 906
 907		$arrURL = parse_url($url);
 908
 909		$connect_host = $arrURL['host'];
 910
 911		$secure_transport = ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' );
 912		if ( ! isset( $arrURL['port'] ) ) {
 913			if ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) {
 914				$arrURL['port'] = 443;
 915				$secure_transport = true;
 916			} else {
 917				$arrURL['port'] = 80;
 918			}
 919		}
 920
 921		// Always pass a Path, defaulting to the root in cases such as http://example.com
 922		if ( ! isset( $arrURL['path'] ) ) {
 923			$arrURL['path'] = '/';
 924		}
 925
 926		if ( isset( $r['headers']['Host'] ) || isset( $r['headers']['host'] ) ) {
 927			if ( isset( $r['headers']['Host'] ) )
 928				$arrURL['host'] = $r['headers']['Host'];
 929			else
 930				$arrURL['host'] = $r['headers']['host'];
 931			unset( $r['headers']['Host'], $r['headers']['host'] );
 932		}
 933
 934		/*
 935		 * Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect
 936		 * to ::1, which fails when the server is not set up for it. For compatibility, always
 937		 * connect to the IPv4 address.
 938		 */
 939		if ( 'localhost' == strtolower( $connect_host ) )
 940			$connect_host = '127.0.0.1';
 941
 942		$connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
 943
 944		$is_local = isset( $r['local'] ) && $r['local'];
 945		$ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
 946		if ( $is_local ) {
 947			/**
 948			 * Filter whether SSL should be verified for local requests.
 949			 *
 950			 * @since 2.8.0
 951			 *
 952			 * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
 953			 */
 954			$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
 955		} elseif ( ! $is_local ) {
 956			/**
 957			 * Filter whether SSL should be verified for non-local requests.
 958			 *
 959			 * @since 2.8.0
 960			 *
 961			 * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
 962			 */
 963			$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
 964		}
 965
 966		$proxy = new WP_HTTP_Proxy();
 967
 968		$context = stream_context_create( array(
 969			'ssl' => array(
 970				'verify_peer' => $ssl_verify,
 971				//'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
 972				'capture_peer_cert' => $ssl_verify,
 973				'SNI_enabled' => true,
 974				'cafile' => $r['sslcertificates'],
 975				'allow_self_signed' => ! $ssl_verify,
 976			)
 977		) );
 978
 979		$timeout = (int) floor( $r['timeout'] );
 980		$utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
 981		$connect_timeout = max( $timeout, 1 );
 982
 983		// Store error number.
 984		$connection_error = null;
 985
 986		// Store error string.
 987		$connection_error_str = null;
 988
 989		if ( !WP_DEBUG ) {
 990			// In the event that the SSL connection fails, silence the many PHP Warnings.
 991			if ( $secure_transport )
 992				$error_reporting = error_reporting(0);
 993
 994			if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 995				$handle = @stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
 996			else
 997				$handle = @stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
 998
 999			if ( $secure_transport )
1000				error_reporting( $error_reporting );
1001
1002		} else {
1003			if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
1004				$handle = stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1005			else
1006				$handle = stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
1007		}
1008
1009		if ( false === $handle ) {
1010			// SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
1011			if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str )
1012				return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1013
1014			return new WP_Error('http_request_failed', $connection_error . ': ' . $connection_error_str );
1015		}
1016
1017		// Verify that the SSL certificate is valid for this request.
1018		if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
1019			if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) )
1020				return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
1021		}
1022
1023		stream_set_timeout( $handle, $timeout, $utimeout );
1024
1025		if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
1026			$requestPath = $url;
1027		else
1028			$requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
1029
1030		$strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
1031
1032		$include_port_in_host_header = (
1033			( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) ||
1034			( 'http'  == $arrURL['scheme'] && 80  != $arrURL['port'] ) ||
1035			( 'https' == $arrURL['scheme'] && 443 != $arrURL['port'] )
1036		);
1037
1038		if ( $include_port_in_host_header ) {
1039			$strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
1040		} else {
1041			$strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
1042		}
1043
1044		if ( isset($r['user-agent']) )
1045			$strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
1046
1047		if ( is_array($r['headers']) ) {
1048			foreach ( (array) $r['headers'] as $header => $headerValue )
1049				$strHeaders .= $header . ': ' . $headerValue . "\r\n";
1050		} else {
1051			$strHeaders .= $r['headers'];
1052		}
1053
1054		if ( $proxy->use_authentication() )
1055			$strHeaders .= $proxy->authentication_header() . "\r\n";
1056
1057		$strHeaders .= "\r\n";
1058
1059		if ( ! is_null($r['body']) )
1060			$strHeaders .= $r['body'];
1061
1062		fwrite($handle, $strHeaders);
1063
1064		if ( ! $r['blocking'] ) {
1065			stream_set_blocking( $handle, 0 );
1066			fclose( $handle );
1067			return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
1068		}
1069
1070		$strResponse = '';
1071		$bodyStarted = false;
1072		$keep_reading = true;
1073		$block_size = 4096;
1074		if ( isset( $r['limit_response_size'] ) )
1075			$block_size = min( $block_size, $r['limit_response_size'] );
1076
1077		// If streaming to a file setup the file handle.
1078		if ( $r['stream'] ) {
1079			if ( ! WP_DEBUG )
1080				$stream_handle = @fopen( $r['filename'], 'w+' );
1081			else
1082				$stream_handle = fopen( $r['filename'], 'w+' );
1083			if ( ! $stream_handle )
1084				return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
1085
1086			$bytes_written = 0;
1087			while ( ! feof($handle) && $keep_reading ) {
1088				$block = fread( $handle, $block_size );
1089				if ( ! $bodyStarted ) {
1090					$strResponse .= $block;
1091					if ( strpos( $strResponse, "\r\n\r\n" ) ) {
1092						$process = WP_Http::processResponse( $strResponse );
1093						$bodyStarted = true;
1094						$block = $process['body'];
1095						unset( $strResponse );
1096						$process['body'] = '';
1097					}
1098				}
1099
1100				$this_block_size = strlen( $block );
1101
1102				if ( isset( $r['limit_response_size'] ) && ( $bytes_written + $this_block_size ) > $r['limit_response_size'] ) {
1103					$this_block_size = ( $r['limit_response_size'] - $bytes_written );
1104					$block = substr( $block, 0, $this_block_size );
1105				}
1106
1107				$bytes_written_to_file = fwrite( $stream_handle, $block );
1108
1109				if ( $bytes_written_to_file != $this_block_size ) {
1110					fclose( $handle );
1111					fclose( $stream_handle );
1112					return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
1113				}
1114
1115				$bytes_written += $bytes_written_to_file;
1116
1117				$keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
1118			}
1119
1120			fclose( $stream_handle );
1121
1122		} else {
1123			$header_length = 0;
1124			while ( ! feof( $handle ) && $keep_reading ) {
1125				$block = fread( $handle, $block_size );
1126				$strResponse .= $block;
1127				if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
1128					$header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
1129					$bodyStarted = true;
1130				}
1131				$keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
1132			}
1133
1134			$process = WP_Http::processResponse( $strResponse );
1135			unset( $strResponse );
1136
1137		}
1138
1139		fclose( $handle );
1140
1141		$arrHeaders = WP_Http::processHeaders( $process['headers'], $url );
1142
1143		$response = array(
1144			'headers' => $arrHeaders['headers'],
1145			// Not yet processed.
1146			'body' => null,
1147			'response' => $arrHeaders['response'],
1148			'cookies' => $arrHeaders['cookies'],
1149			'filename' => $r['filename']
1150		);
1151
1152		// Handle redirects.
1153		if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
1154			return $redirect_response;
1155
1156		// If the body was chunk encoded, then decode it.
1157		if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
1158			$process['body'] = WP_Http::chunkTransferDecode($process['body']);
1159
1160		if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
1161			$process['body'] = WP_Http_Encoding::decompress( $process['body'] );
1162
1163		if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
1164			$process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
1165
1166		$response['body'] = $process['body'];
1167
1168		return $response;
1169	}
1170
1171	/**
1172	 * Verifies the received SSL certificate against it's Common Names and subjectAltName fields
1173	 *
1174	 * PHP's SSL verifications only verify that it's a valid Certificate, it doesn't verify if
1175	 * the certificate is valid for the hostname which was requested.
1176	 * This function verifies the requested hostname against certificate's subjectAltName field,
1177	 * if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
1178	 *
1179	 * IP Address support is included if the request is being made to an IP address.
1180	 *
1181	 * @since 3.7.0
1182	 * @static
1183	 *
1184	 * @param stream $stream The PHP Stream which the SSL request is being made over
1185	 * @param string $host The hostname being requested
1186	 * @return bool If the cerficiate presented in $stream is valid for $host
1187	 */
1188	public static function verify_ssl_certificate( $stream, $host ) {
1189		$context_options = stream_context_get_options( $stream );
1190
1191		if ( empty( $context_options['ssl']['peer_certificate'] ) )
1192			return false;
1193
1194		$cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
1195		if ( ! $cert )
1196			return false;
1197
1198		/*
1199		 * If the request is being made to an IP address, we'll validate against IP fields
1200		 * in the cert (if they exist)
1201		 */
1202		$host_type = ( WP_HTTP::is_ip_address( $host ) ? 'ip' : 'dns' );
1203
1204		$certificate_hostnames = array();
1205		if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
1206			$match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
1207			foreach ( $match_against as $match ) {
1208				list( $match_type, $match_host ) = explode( ':', $match );
1209				if ( $host_type == strtolower( trim( $match_type ) ) ) // IP: or DNS:
1210					$certificate_hostnames[] = strtolower( trim( $match_host ) );
1211			}
1212		} elseif ( !empty( $cert['subject']['CN'] ) ) {
1213			// Only use the CN when the certificate includes no subjectAltName extension.
1214			$certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
1215		}
1216
1217		// Exact hostname/IP matches.
1218		if ( in_array( strtolower( $host ), $certificate_hostnames ) )
1219			return true;
1220
1221		// IP's can't be wildcards, Stop processing.
1222		if ( 'ip' == $host_type )
1223			return false;
1224
1225		// Test to see if the domain is at least 2 deep for wildcard support.
1226		if ( substr_count( $host, '.' ) < 2 )
1227			return false;
1228
1229		// Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
1230		$wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
1231
1232		return in_array( strtolower( $wildcard_host ), $certificate_hostnames );
1233	}
1234
1235	/**
1236	 * Whether this class can be used for retrieving a URL.
1237	 *
1238	 * @static
1239	 * @access public
1240	 * @since 2.7.0
1241	 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
1242	 *
1243	 * @return boolean False means this class can not be used, true means it can.
1244	 */
1245	public static function test( $args = array() ) {
1246		if ( ! function_exists( 'stream_socket_client' ) )
1247			return false;
1248
1249		$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
1250
1251		if ( $is_ssl ) {
1252			if ( ! extension_loaded( 'openssl' ) )
1253				return false;
1254			if ( ! function_exists( 'openssl_x509_parse' ) )
1255				return false;
1256		}
1257
1258		/**
1259		 * Filter whether streams can be used as a transport for retrieving a URL.
1260		 *
1261		 * @since 2.7.0
1262		 *
1263		 * @param bool  $use_class Whether the class can be used. Default true.
1264		 * @param array $args      Request arguments.
1265		 */
1266		return apply_filters( 'use_streams_transport', true, $args );
1267	}
1268}
1269
1270/**
1271 * Deprecated HTTP Transport method which used fsockopen.
1272 *
1273 * This class is not used, and is included for backwards compatibility only.
1274 * All code should make use of WP_HTTP directly through it's API.
1275 *
1276 * @see WP_HTTP::request
1277 *
1278 * @since 2.7.0
1279 * @deprecated 3.7.0 Please use WP_HTTP::request() directly
1280 */
1281class WP_HTTP_Fsockopen extends WP_HTTP_Streams {
1282	// For backwards compatibility for users who are using the class directly.
1283}
1284
1285/**
1286 * HTTP request method uses Curl extension to retrieve the url.
1287 *
1288 * Requires the Curl extension to be installed.
1289 *
1290 * @package WordPress
1291 * @subpackage HTTP
1292 * @since 2.7.0
1293 */
1294class WP_Http_Curl {
1295
1296	/**
1297	 * Temporary header storage for during requests.
1298	 *
1299	 * @since 3.2.0
1300	 * @access private
1301	 * @var string
1302	 */
1303	private $headers = '';
1304
1305	/**
1306	 * Temporary body storage for during requests.
1307	 *
1308	 * @since 3.6.0
1309	 * @access private
1310	 * @var string
1311	 */
1312	private $body = '';
1313
1314	/**
1315	 * The maximum amount of data to receive from the remote server.
1316	 *
1317	 * @since 3.6.0
1318	 * @access private
1319	 * @var int
1320	 */
1321	private $max_body_length = false;
1322
1323	/**
1324	 * The file resource used for streaming to file.
1325	 *
1326	 * @since 3.6.0
1327	 * @access private
1328	 * @var resource
1329	 */
1330	private $stream_handle = false;
1331
1332	/**
1333	 * The total bytes written in the current request.
1334	 *
1335	 * @since 4.1.0
1336	 * @access private
1337	 * @var int
1338	 */
1339	private $bytes_written_total = 0;
1340
1341	/**
1342	 * Send a HTTP request to a URI using cURL extension.
1343	 *
1344	 * @access public
1345	 * @since 2.7.0
1346	 *
1347	 * @param string $url The request URL.
1348	 * @param string|array $args Optional. Override the defaults.
1349	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
1350	 */
1351	public function request($url, $args = array()) {
1352		$defaults = array(
1353			'method' => 'GET', 'timeout' => 5,
1354			'redirection' => 5, 'httpversion' => '1.0',
1355			'blocking' => true,
1356			'headers' => array(), 'body' => null, 'cookies' => array()
1357		);
1358
1359		$r = wp_parse_args( $args, $defaults );
1360
1361		if ( isset($r['headers']['User-Agent']) ) {
1362			$r['user-agent'] = $r['headers']['User-Agent'];
1363			unset($r['headers']['User-Agent']);
1364		} else if ( isset($r['headers']['user-agent']) ) {
1365			$r['user-agent'] = $r['headers']['user-agent'];
1366			unset($r['headers']['user-agent']);
1367		}
1368
1369		// Construct Cookie: header if any cookies are set.
1370		WP_Http::buildCookieHeader( $r );
1371
1372		$handle = curl_init();
1373
1374		// cURL offers really easy proxy support.
1375		$proxy = new WP_HTTP_Proxy();
1376
1377		if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
1378
1379			curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
1380			curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
1381			curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
1382
1383			if ( $proxy->use_authentication() ) {
1384				curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
1385				curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
1386			}
1387		}
1388
1389		$is_local = isset($r['local']) && $r['local'];
1390		$ssl_verify = isset($r['sslverify']) && $r['sslverify'];
1391		if ( $is_local ) {
1392			/** This filter is documented in wp-includes/class-http.php */
1393			$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
1394		} elseif ( ! $is_local ) {
1395			/** This filter is documented in wp-includes/class-http.php */
1396			$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
1397		}
1398
1399		/*
1400		 * CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
1401		 * a value of 0 will allow an unlimited timeout.
1402		 */
1403		$timeout = (int) ceil( $r['timeout'] );
1404		curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
1405		curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1406
1407		curl_setopt( $handle, CURLOPT_URL, $url);
1408		curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
1409		curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
1410		curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
1411		curl_setopt( $handle, CURLOPT_CAINFO, $r['sslcertificates'] );
1412		curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
1413
1414		/*
1415		 * The option doesn't work with safe mode or when open_basedir is set, and there's
1416		 * a bug #17490 with redirected POST requests, so handle redirections outside Curl.
1417		 */
1418		curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
1419		if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
1420			curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
1421
1422		switch ( $r['method'] ) {
1423			case 'HEAD':
1424				curl_setopt( $handle, CURLOPT_NOBODY, true );
1425				break;
1426			case 'POST':
1427				curl_setopt( $handle, CURLOPT_POST, true );
1428				curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] 

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