PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/class-http.php

https://bitbucket.org/theshipswakecreative/psw
PHP | 2173 lines | 930 code | 299 blank | 944 comment | 314 complexity | 07dd46287c290341b9a1125da4577917 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0

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

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