PageRenderTime 61ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/class-http.php

https://github.com/locdinh/mywebsite
PHP | 2121 lines | 930 code | 294 blank | 897 comment | 311 complexity | f2fb56ce236adefb5b58380523c9e3aa MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1

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

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