PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/class-http.php

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