PageRenderTime 54ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/class-http.php

https://github.com/dipakdotyadav/WordPress
PHP | 1904 lines | 903 code | 284 blank | 717 comment | 301 complexity | 4bca7ff9d3e76c9105fbb2620bc85dca MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1

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

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

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