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

/htdocs/wp-includes/class-http.php

https://bitbucket.org/dkrzos/phc
PHP | 1804 lines | 849 code | 269 blank | 686 comment | 285 complexity | f68a769acf54ccf9ae3139860d964b8b MD5 | raw file
Possible License(s): GPL-2.0

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

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

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