PageRenderTime 53ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/class-http.php

https://bitbucket.org/KamranMackey/wordpress
PHP | 1791 lines | 835 code | 268 blank | 688 comment | 279 complexity | 98f01e1cc7c991e89a26c066ee8fa360 MD5 | raw file

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

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

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