PageRenderTime 65ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/temp/wordpress/wp-includes/class-http.php

https://bitbucket.org/broderboy/shannonbroder-wordpress
PHP | 1789 lines | 836 code | 264 blank | 689 comment | 277 complexity | 9551ca7742b32eaeaf61c5f9c3b913f3 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, AGPL-1.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. '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 ( ! 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 ( empty($r['body']) ) {
  151. $r['body'] = null;
  152. // Some servers fail when sending content without the content-length header being set.
  153. // Also, to fix another bug, we only send when doing POST and PUT and the content-length
  154. // header isn't already set.
  155. if ( ($r['method'] == 'POST' || $r['method'] == 'PUT') && ! isset( $r['headers']['Content-Length'] ) )
  156. $r['headers']['Content-Length'] = 0;
  157. } else {
  158. if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
  159. $r['body'] = http_build_query( $r['body'], null, '&' );
  160. if ( ! isset( $r['headers']['Content-Type'] ) )
  161. $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
  162. $r['headers']['Content-Length'] = strlen( $r['body'] );
  163. }
  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|false 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. if ( !empty( $value ) ) {
  338. $key = strtolower( $key );
  339. if ( isset( $newheaders[$key] ) ) {
  340. if ( !is_array($newheaders[$key]) )
  341. $newheaders[$key] = array($newheaders[$key]);
  342. $newheaders[$key][] = trim( $value );
  343. } else {
  344. $newheaders[$key] = trim( $value );
  345. }
  346. if ( 'set-cookie' == $key )
  347. $cookies[] = new WP_Http_Cookie( $value );
  348. }
  349. }
  350. return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
  351. }
  352. /**
  353. * Takes the arguments for a ::request() and checks for the cookie array.
  354. *
  355. * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed
  356. * into strings and added to the Cookie: header (within the arguments array). Edits the array by
  357. * reference.
  358. *
  359. * @access public
  360. * @version 2.8.0
  361. * @static
  362. *
  363. * @param array $r Full array of args passed into ::request()
  364. */
  365. public static function buildCookieHeader( &$r ) {
  366. if ( ! empty($r['cookies']) ) {
  367. $cookies_header = '';
  368. foreach ( (array) $r['cookies'] as $cookie ) {
  369. $cookies_header .= $cookie->getHeaderValue() . '; ';
  370. }
  371. $cookies_header = substr( $cookies_header, 0, -2 );
  372. $r['headers']['cookie'] = $cookies_header;
  373. }
  374. }
  375. /**
  376. * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
  377. *
  378. * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support
  379. * returning footer headers. Shouldn't be too difficult to support it though.
  380. *
  381. * @todo Add support for footer chunked headers.
  382. * @access public
  383. * @since 2.7.0
  384. * @static
  385. *
  386. * @param string $body Body content
  387. * @return string Chunked decoded body on success or raw body on failure.
  388. */
  389. function chunkTransferDecode($body) {
  390. $body = str_replace(array("\r\n", "\r"), "\n", $body);
  391. // The body is not chunked encoding or is malformed.
  392. if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) )
  393. return $body;
  394. $parsedBody = '';
  395. //$parsedHeaders = array(); Unsupported
  396. while ( true ) {
  397. $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match );
  398. if ( $hasChunk ) {
  399. if ( empty( $match[1] ) )
  400. return $body;
  401. $length = hexdec( $match[1] );
  402. $chunkLength = strlen( $match[0] );
  403. $strBody = substr($body, $chunkLength, $length);
  404. $parsedBody .= $strBody;
  405. $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n");
  406. if ( "0" == trim($body) )
  407. return $parsedBody; // Ignore footer headers.
  408. } else {
  409. return $body;
  410. }
  411. }
  412. }
  413. /**
  414. * Block requests through the proxy.
  415. *
  416. * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
  417. * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
  418. *
  419. * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
  420. * file and this will only allow localhost and your blog to make requests. The constant
  421. * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
  422. * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
  423. * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
  424. *
  425. * @since 2.8.0
  426. * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
  427. * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
  428. *
  429. * @param string $uri URI of url.
  430. * @return bool True to block, false to allow.
  431. */
  432. function block_request($uri) {
  433. // We don't need to block requests, because nothing is blocked.
  434. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
  435. return false;
  436. // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
  437. // This will be displayed on blogs, which is not reasonable.
  438. $check = @parse_url($uri);
  439. /* Malformed URL, can not process, but this could mean ssl, so let through anyway.
  440. *
  441. * This isn't very security sound. There are instances where a hacker might attempt
  442. * to bypass the proxy and this check. However, the reason for this behavior is that
  443. * WordPress does not do any checking currently for non-proxy requests, so it is keeps with
  444. * the default unsecure nature of the HTTP request.
  445. */
  446. if ( $check === false )
  447. return false;
  448. $home = parse_url( get_option('siteurl') );
  449. // Don't block requests back to ourselves by default
  450. if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
  451. return apply_filters('block_local_requests', false);
  452. if ( !defined('WP_ACCESSIBLE_HOSTS') )
  453. return true;
  454. static $accessible_hosts;
  455. static $wildcard_regex = false;
  456. if ( null == $accessible_hosts ) {
  457. $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
  458. if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
  459. $wildcard_regex = array();
  460. foreach ( $accessible_hosts as $host )
  461. $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
  462. $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
  463. }
  464. }
  465. if ( !empty($wildcard_regex) )
  466. return !preg_match($wildcard_regex, $check['host']);
  467. else
  468. return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it.
  469. }
  470. static function make_absolute_url( $maybe_relative_path, $url ) {
  471. if ( empty( $url ) )
  472. return $maybe_relative_path;
  473. // Check for a scheme
  474. if ( false !== strpos( $maybe_relative_path, '://' ) )
  475. return $maybe_relative_path;
  476. if ( ! $url_parts = @parse_url( $url ) )
  477. return $maybe_relative_path;
  478. if ( ! $relative_url_parts = @parse_url( $maybe_relative_path ) )
  479. return $maybe_relative_path;
  480. $absolute_path = $url_parts['scheme'] . '://' . $url_parts['host'];
  481. if ( isset( $url_parts['port'] ) )
  482. $absolute_path .= ':' . $url_parts['port'];
  483. // Start off with the Absolute URL path
  484. $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
  485. // If the it's a root-relative path, then great
  486. if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
  487. $path = $relative_url_parts['path'];
  488. // Else it's a relative path
  489. } elseif ( ! empty( $relative_url_parts['path'] ) ) {
  490. // Strip off any file components from the absolute path
  491. $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
  492. // Build the new path
  493. $path .= $relative_url_parts['path'];
  494. // Strip all /path/../ out of the path
  495. while ( strpos( $path, '../' ) > 1 ) {
  496. $path = preg_replace( '![^/]+/\.\./!', '', $path );
  497. }
  498. // Strip any final leading ../ from the path
  499. $path = preg_replace( '!^/(\.\./)+!', '', $path );
  500. }
  501. // Add the Query string
  502. if ( ! empty( $relative_url_parts['query'] ) )
  503. $path .= '?' . $relative_url_parts['query'];
  504. return $absolute_path . '/' . ltrim( $path, '/' );
  505. }
  506. }
  507. /**
  508. * HTTP request method uses fsockopen function to retrieve the url.
  509. *
  510. * This would be the preferred method, but the fsockopen implementation has the most overhead of all
  511. * the HTTP transport implementations.
  512. *
  513. * @package WordPress
  514. * @subpackage HTTP
  515. * @since 2.7.0
  516. */
  517. class WP_Http_Fsockopen {
  518. /**
  519. * Send a HTTP request to a URI using fsockopen().
  520. *
  521. * Does not support non-blocking mode.
  522. *
  523. * @see WP_Http::request For default options descriptions.
  524. *
  525. * @since 2.7
  526. * @access public
  527. * @param string $url URI resource.
  528. * @param str|array $args Optional. Override the defaults.
  529. * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
  530. */
  531. function request($url, $args = array()) {
  532. $defaults = array(
  533. 'method' => 'GET', 'timeout' => 5,
  534. 'redirection' => 5, 'httpversion' => '1.0',
  535. 'blocking' => true,
  536. 'headers' => array(), 'body' => null, 'cookies' => array()
  537. );
  538. $r = wp_parse_args( $args, $defaults );
  539. if ( isset($r['headers']['User-Agent']) ) {
  540. $r['user-agent'] = $r['headers']['User-Agent'];
  541. unset($r['headers']['User-Agent']);
  542. } else if ( isset($r['headers']['user-agent']) ) {
  543. $r['user-agent'] = $r['headers']['user-agent'];
  544. unset($r['headers']['user-agent']);
  545. }
  546. // Construct Cookie: header if any cookies are set
  547. WP_Http::buildCookieHeader( $r );
  548. $iError = null; // Store error number
  549. $strError = null; // Store error string
  550. $arrURL = parse_url($url);
  551. $fsockopen_host = $arrURL['host'];
  552. $secure_transport = false;
  553. if ( ! isset( $arrURL['port'] ) ) {
  554. if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) {
  555. $fsockopen_host = "ssl://$fsockopen_host";
  556. $arrURL['port'] = 443;
  557. $secure_transport = true;
  558. } else {
  559. $arrURL['port'] = 80;
  560. }
  561. }
  562. //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1,
  563. // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
  564. if ( 'localhost' == strtolower($fsockopen_host) )
  565. $fsockopen_host = '127.0.0.1';
  566. // There are issues with the HTTPS and SSL protocols that cause errors that can be safely
  567. // ignored and should be ignored.
  568. if ( true === $secure_transport )
  569. $error_reporting = error_reporting(0);
  570. $startDelay = time();
  571. $proxy = new WP_HTTP_Proxy();
  572. if ( !WP_DEBUG ) {
  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. } else {
  578. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
  579. $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] );
  580. else
  581. $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] );
  582. }
  583. $endDelay = time();
  584. // If the delay is greater than the timeout then fsockopen shouldn't be used, because it will
  585. // cause a long delay.
  586. $elapseDelay = ($endDelay-$startDelay) > $r['timeout'];
  587. if ( true === $elapseDelay )
  588. add_option( 'disable_fsockopen', $endDelay, null, true );
  589. if ( false === $handle )
  590. return new WP_Error('http_request_failed', $iError . ': ' . $strError);
  591. $timeout = (int) floor( $r['timeout'] );
  592. $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
  593. stream_set_timeout( $handle, $timeout, $utimeout );
  594. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
  595. $requestPath = $url;
  596. else
  597. $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
  598. if ( empty($requestPath) )
  599. $requestPath .= '/';
  600. $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
  601. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
  602. $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
  603. else
  604. $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
  605. if ( isset($r['user-agent']) )
  606. $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
  607. if ( is_array($r['headers']) ) {
  608. foreach ( (array) $r['headers'] as $header => $headerValue )
  609. $strHeaders .= $header . ': ' . $headerValue . "\r\n";
  610. } else {
  611. $strHeaders .= $r['headers'];
  612. }
  613. if ( $proxy->use_authentication() )
  614. $strHeaders .= $proxy->authentication_header() . "\r\n";
  615. $strHeaders .= "\r\n";
  616. if ( ! is_null($r['body']) )
  617. $strHeaders .= $r['body'];
  618. fwrite($handle, $strHeaders);
  619. if ( ! $r['blocking'] ) {
  620. fclose($handle);
  621. return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
  622. }
  623. $strResponse = '';
  624. $bodyStarted = false;
  625. // If streaming to a file setup the file handle
  626. if ( $r['stream'] ) {
  627. if ( ! WP_DEBUG )
  628. $stream_handle = @fopen( $r['filename'], 'w+' );
  629. else
  630. $stream_handle = fopen( $r['filename'], 'w+' );
  631. if ( ! $stream_handle )
  632. return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
  633. while ( ! feof($handle) ) {
  634. $block = fread( $handle, 4096 );
  635. if ( $bodyStarted ) {
  636. fwrite( $stream_handle, $block );
  637. } else {
  638. $strResponse .= $block;
  639. if ( strpos( $strResponse, "\r\n\r\n" ) ) {
  640. $process = WP_Http::processResponse( $strResponse );
  641. $bodyStarted = true;
  642. fwrite( $stream_handle, $process['body'] );
  643. unset( $strResponse );
  644. $process['body'] = '';
  645. }
  646. }
  647. }
  648. fclose( $stream_handle );
  649. } else {
  650. while ( ! feof($handle) )
  651. $strResponse .= fread( $handle, 4096 );
  652. $process = WP_Http::processResponse( $strResponse );
  653. unset( $strResponse );
  654. }
  655. fclose( $handle );
  656. if ( true === $secure_transport )
  657. error_reporting($error_reporting);
  658. $arrHeaders = WP_Http::processHeaders( $process['headers'] );
  659. // If location is found, then assume redirect and redirect to location.
  660. if ( isset($arrHeaders['headers']['location']) && 0 !== $r['_redirection'] ) {
  661. if ( $r['redirection']-- > 0 ) {
  662. return $this->request( WP_HTTP::make_absolute_url( $arrHeaders['headers']['location'], $url ), $r);
  663. } else {
  664. return new WP_Error('http_request_failed', __('Too many redirects.'));
  665. }
  666. }
  667. // If the body was chunk encoded, then decode it.
  668. if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
  669. $process['body'] = WP_Http::chunkTransferDecode($process['body']);
  670. if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
  671. $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
  672. return array( 'headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies'], 'filename' => $r['filename'] );
  673. }
  674. /**
  675. * Whether this class can be used for retrieving an URL.
  676. *
  677. * @since 2.7.0
  678. * @static
  679. * @return boolean False means this class can not be used, true means it can.
  680. */
  681. public static function test( $args = array() ) {
  682. if ( ! function_exists( 'fsockopen' ) )
  683. return false;
  684. if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours
  685. return false;
  686. $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
  687. if ( $is_ssl && ! extension_loaded( 'openssl' ) )
  688. return false;
  689. return apply_filters( 'use_fsockopen_transport', true, $args );
  690. }
  691. }
  692. /**
  693. * HTTP request method uses Streams to retrieve the url.
  694. *
  695. * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting
  696. * to be enabled.
  697. *
  698. * Second preferred method for getting the URL, for PHP 5.
  699. *
  700. * @package WordPress
  701. * @subpackage HTTP
  702. * @since 2.7.0
  703. */
  704. class WP_Http_Streams {
  705. /**
  706. * Send a HTTP request to a URI using streams with fopen().
  707. *
  708. * @access public
  709. * @since 2.7.0
  710. *
  711. * @param string $url
  712. * @param str|array $args Optional. Override the defaults.
  713. * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
  714. */
  715. function request($url, $args = array()) {
  716. $defaults = array(
  717. 'method' => 'GET', 'timeout' => 5,
  718. 'redirection' => 5, 'httpversion' => '1.0',
  719. 'blocking' => true,
  720. 'headers' => array(), 'body' => null, 'cookies' => array()
  721. );
  722. $r = wp_parse_args( $args, $defaults );
  723. if ( isset($r['headers']['User-Agent']) ) {
  724. $r['user-agent'] = $r['headers']['User-Agent'];
  725. unset($r['headers']['User-Agent']);
  726. } else if ( isset($r['headers']['user-agent']) ) {
  727. $r['user-agent'] = $r['headers']['user-agent'];
  728. unset($r['headers']['user-agent']);
  729. }
  730. // Construct Cookie: header if any cookies are set
  731. WP_Http::buildCookieHeader( $r );
  732. $arrURL = parse_url($url);
  733. if ( false === $arrURL )
  734. return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url));
  735. if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] )
  736. $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
  737. // Convert Header array to string.
  738. $strHeaders = '';
  739. if ( is_array( $r['headers'] ) )
  740. foreach ( $r['headers'] as $name => $value )
  741. $strHeaders .= "{$name}: $value\r\n";
  742. else if ( is_string( $r['headers'] ) )
  743. $strHeaders = $r['headers'];
  744. $is_local = isset($args['local']) && $args['local'];
  745. $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
  746. if ( $is_local )
  747. $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
  748. elseif ( ! $is_local )
  749. $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
  750. $arrContext = array('http' =>
  751. array(
  752. 'method' => strtoupper($r['method']),
  753. 'user_agent' => $r['user-agent'],
  754. 'max_redirects' => $r['redirection'] + 1, // See #11557
  755. 'protocol_version' => (float) $r['httpversion'],
  756. 'header' => $strHeaders,
  757. 'ignore_errors' => true, // Return non-200 requests.
  758. 'timeout' => $r['timeout'],
  759. 'ssl' => array(
  760. 'verify_peer' => $ssl_verify,
  761. 'verify_host' => $ssl_verify
  762. )
  763. )
  764. );
  765. $proxy = new WP_HTTP_Proxy();
  766. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
  767. $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port();
  768. $arrContext['http']['request_fulluri'] = true;
  769. // We only support Basic authentication so this will only work if that is what your proxy supports.
  770. if ( $proxy->use_authentication() )
  771. $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n";
  772. }
  773. if ( ! empty($r['body'] ) )
  774. $arrContext['http']['content'] = $r['body'];
  775. $context = stream_context_create($arrContext);
  776. if ( !WP_DEBUG )
  777. $handle = @fopen($url, 'r', false, $context);
  778. else
  779. $handle = fopen($url, 'r', false, $context);
  780. if ( ! $handle )
  781. return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url));
  782. $timeout = (int) floor( $r['timeout'] );
  783. $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
  784. stream_set_timeout( $handle, $timeout, $utimeout );
  785. if ( ! $r['blocking'] ) {
  786. stream_set_blocking($handle, 0);
  787. fclose($handle);
  788. return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
  789. }
  790. if ( $r['stream'] ) {
  791. if ( ! WP_DEBUG )
  792. $stream_handle = @fopen( $r['filename'], 'w+' );
  793. else
  794. $stream_handle = fopen( $r['filename'], 'w+' );
  795. if ( ! $stream_handle )
  796. return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
  797. stream_copy_to_stream( $handle, $stream_handle );
  798. fclose( $stream_handle );
  799. $strResponse = '';
  800. } else {
  801. $strResponse = stream_get_contents( $handle );
  802. }
  803. $meta = stream_get_meta_data( $handle );
  804. fclose( $handle );
  805. $processedHeaders = array();
  806. if ( isset( $meta['wrapper_data']['headers'] ) )
  807. $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']);
  808. else
  809. $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']);
  810. // Streams does not provide an error code which we can use to see why the request stream stopped.
  811. // We can however test to see if a location header is present and return based on that.
  812. if ( isset($processedHeaders['headers']['location']) && 0 !== $args['_redirection'] )
  813. return new WP_Error('http_request_failed', __('Too many redirects.'));
  814. if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] )
  815. $strResponse = WP_Http::chunkTransferDecode($strResponse);
  816. if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) )
  817. $strResponse = WP_Http_Encoding::decompress( $strResponse );
  818. return array( 'headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies'], 'filename' => $r['filename'] );
  819. }
  820. /**
  821. * Whether this class can be used for retrieving an URL.
  822. *
  823. * @static
  824. * @access public
  825. * @since 2.7.0
  826. *
  827. * @return boolean False means this class can not be used, true means it can.
  828. */
  829. public static function test( $args = array() ) {
  830. if ( ! function_exists( 'fopen' ) )
  831. return false;
  832. if ( ! function_exists( 'ini_get' ) || true != ini_get( 'allow_url_fopen' ) )
  833. return false;
  834. $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
  835. if ( $is_ssl && ! extension_loaded( 'openssl' ) )
  836. return false;
  837. return apply_filters( 'use_streams_transport', true, $args );
  838. }
  839. }
  840. /**
  841. * HTTP request method uses Curl extension to retrieve the url.
  842. *
  843. * Requires the Curl extension to be installed.
  844. *
  845. * @package WordPress
  846. * @subpackage HTTP
  847. * @since 2.7
  848. */
  849. class WP_Http_Curl {
  850. /**
  851. * Temporary header storage for use with streaming to a file.
  852. *
  853. * @since 3.2.0
  854. * @access private
  855. * @var string
  856. */
  857. private $headers = '';
  858. /**
  859. * Send a HTTP request to a URI using cURL extension.
  860. *
  861. * @access public
  862. * @since 2.7.0
  863. *
  864. * @param string $url
  865. * @param str|array $args Optional. Override the defaults.
  866. * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
  867. */
  868. function request($url, $args = array()) {
  869. $defaults = array(
  870. 'method' => 'GET', 'timeout' => 5,
  871. 'redirection' => 5, 'httpversion' => '1.0',
  872. 'blocking' => true,
  873. 'headers' => array(), 'body' => null, 'cookies' => array()
  874. );
  875. $r = wp_parse_args( $args, $defaults );
  876. if ( isset($r['headers']['User-Agent']) ) {
  877. $r['user-agent'] = $r['headers']['User-Agent'];
  878. unset($r['headers']['User-Agent']);
  879. } else if ( isset($r['headers']['user-agent']) ) {
  880. $r['user-agent'] = $r['headers']['user-agent'];
  881. unset($r['headers']['user-agent']);
  882. }
  883. // Construct Cookie: header if any cookies are set.
  884. WP_Http::buildCookieHeader( $r );
  885. $handle = curl_init();
  886. // cURL offers really easy proxy support.
  887. $proxy = new WP_HTTP_Proxy();
  888. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
  889. curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
  890. curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
  891. curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
  892. if ( $proxy->use_authentication() ) {
  893. curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
  894. curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
  895. }
  896. }
  897. $is_local = isset($r['local']) && $r['local'];
  898. $ssl_verify = isset($r['sslverify']) && $r['sslverify'];
  899. if ( $is_local )
  900. $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
  901. elseif ( ! $is_local )
  902. $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
  903. // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since
  904. // a value of 0 will allow an unlimited timeout.
  905. $timeout = (int) ceil( $r['timeout'] );
  906. curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
  907. curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
  908. curl_setopt( $handle, CURLOPT_URL, $url);
  909. curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
  910. curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
  911. curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
  912. curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
  913. // The option doesn't work with safe mode or when open_basedir is set, and there's a
  914. // bug #17490 with redirected POST requests, so handle redirections outside Curl.
  915. curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
  916. switch ( $r['method'] ) {
  917. case 'HEAD':
  918. curl_setopt( $handle, CURLOPT_NOBODY, true );
  919. break;
  920. case 'POST':
  921. curl_setopt( $handle, CURLOPT_POST, true );
  922. curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
  923. break;
  924. case 'PUT':
  925. curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
  926. curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
  927. break;
  928. default:
  929. curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
  930. if ( ! empty( $r['body'] ) )
  931. curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
  932. break;
  933. }
  934. if ( true === $r['blocking'] )
  935. curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( &$this, 'stream_headers' ) );
  936. curl_setopt( $handle, CURLOPT_HEADER, false );
  937. // If streaming to a file open a file handle, and setup our curl streaming handler
  938. if ( $r['stream'] ) {
  939. if ( ! WP_DEBUG )
  940. $stream_handle = @fopen( $r['filename'], 'w+' );
  941. else
  942. $stream_handle = fopen( $r['filename'], 'w+' );
  943. if ( ! $stream_handle )
  944. return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
  945. curl_setopt( $handle, CURLOPT_FILE, $stream_handle );
  946. }
  947. if ( !empty( $r['headers'] ) ) {
  948. // cURL expects full header strings in each element
  949. $headers = array();
  950. foreach ( $r['headers'] as $name => $value ) {
  951. $headers[] = "{$name}: $value";
  952. }
  953. curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
  954. }
  955. if ( $r['httpversion'] == '1.0' )
  956. curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
  957. else
  958. curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
  959. // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it
  960. // themselves... Although, it is somewhat pointless without some reference.
  961. do_action_ref_array( 'http_api_curl', array(&$handle) );
  962. // We don't need to return the body, so don't. Just execute request and return.
  963. if ( ! $r['blocking'] ) {
  964. curl_exec( $handle );
  965. curl_close( $handle );
  966. return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
  967. }
  968. $theResponse = curl_exec( $handle );
  969. $theBody = '';
  970. $theHeaders = WP_Http::processHeaders( $this->headers );
  971. if ( strlen($theResponse) > 0 && ! is_bool( $theResponse ) ) // is_bool: when using $args['stream'], curl_exec will return (bool)true
  972. $theBody = $theResponse;
  973. // If no response
  974. if ( 0 == strlen( $theResponse ) && empty( $theHeaders['headers'] ) ) {
  975. if ( $curl_error = curl_error( $handle ) )
  976. return new WP_Error( 'http_request_failed', $curl_error );
  977. if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) )
  978. return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
  979. }
  980. $this->headers = '';
  981. $response = array();
  982. $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
  983. $response['message'] = get_status_header_desc($response['code']);
  984. curl_close( $handle );
  985. if ( $r['stream'] )
  986. fclose( $stream_handle );
  987. // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually.
  988. if ( ! empty( $theHeaders['headers']['location'] ) && 0 !== $r['_redirection'] ) { // _redirection: The requested number of redirections
  989. if ( $r['redirection']-- > 0 ) {
  990. return $this->request( WP_HTTP::make_absolute_url( $theHeaders['headers']['location'], $url ), $r );
  991. } else {
  992. return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
  993. }
  994. }
  995. if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
  996. $theBody = WP_Http_Encoding::decompress( $theBody );
  997. return array( 'headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies'], 'filename' => $r['filename'] );
  998. }
  999. /**
  1000. * Grab the headers of the cURL request
  1001. *
  1002. * Each header is sent individually to this callback, so we append to the $header property for temporary storage
  1003. *
  1004. * @since 3.2.0
  1005. * @access private
  1006. * @return int
  1007. */
  1008. private function stream_headers( $handle, $headers ) {
  1009. $this->headers .= $headers;
  1010. return strlen( $headers );
  1011. }
  1012. /**
  1013. * Whether this class can be used for retrieving an URL.
  1014. *
  1015. * @static
  1016. * @since 2.7.0
  1017. *
  1018. * @return boolean False means this class can not be used, true means it can.
  1019. */
  1020. public static function test( $args = array() ) {
  1021. if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
  1022. return false;
  1023. $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
  1024. if ( $is_ssl ) {
  1025. $curl_version = curl_version();
  1026. if ( ! (CURL_VERSION_SSL & $curl_version['features']) ) // Does this cURL version support SSL requests?
  1027. return false;
  1028. }
  1029. return apply_filters( 'use_curl_transport', true, $args );
  1030. }
  1031. }
  1032. /**
  1033. * Adds Proxy support to the WordPress HTTP API.
  1034. *
  1035. * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
  1036. * enable proxy support. There are also a few filters that plugins can hook into for some of the
  1037. * constants.
  1038. *
  1039. * Please note that only BASIC authentication is supported by most transports.
  1040. * cURL MAY support more methods (such as NTLM authentication) depending on your environment.
  1041. *
  1042. * The constants are as follows:
  1043. * <ol>
  1044. * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
  1045. * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
  1046. * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
  1047. * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
  1048. * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
  1049. * You do not need to have localhost and the blog host in this list, because they will not be passed
  1050. * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
  1051. * </ol>
  1052. *
  1053. * An example can be as seen below.
  1054. * <code>
  1055. * define('WP_PROXY_HOST', '192.168.84.101');
  1056. * define('WP_PROXY_PORT', '8080');
  1057. * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
  1058. * </code>
  1059. *
  1060. * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
  1061. * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
  1062. * @since 2.8
  1063. */
  1064. class WP_HTTP_Proxy {
  1065. /**
  1066. * Whether proxy connection should be used.
  1067. *
  1068. * @since 2.8
  1069. * @use WP_PROXY_HOST
  1070. * @use WP_PROXY_PORT
  1071. *
  1072. * @return bool
  1073. */
  1074. function is_enabled() {
  1075. return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
  1076. }
  1077. /**
  1078. * Whether authentication should be used.
  1079. *
  1080. * @since 2.8
  1081. * @use WP_PROXY_USERNAME
  1082. * @use WP_PROXY_PASSWORD
  1083. *
  1084. * @return bool
  1085. */
  1086. function use_authentication() {
  1087. return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
  1088. }
  1089. /**
  1090. * Retrieve the host for the proxy server.
  1091. *
  1092. * @since 2.8
  1093. *
  1094. * @return string
  1095. */
  1096. function host() {
  1097. if ( defined('WP_PROXY_HOST') )
  1098. return WP_PROXY_HOST;
  1099. return '';
  1100. }
  1101. /**
  1102. * Retrieve the port for the proxy server.
  1103. *
  1104. * @since 2.8
  1105. *
  1106. * @return string
  1107. */
  1108. function port() {
  1109. if ( defined('WP_PROXY_PORT') )
  1110. return WP_PROXY_PORT;
  1111. return '';
  1112. }
  1113. /**
  1114. * Retrieve the username for proxy authentication.
  1115. *
  1116. * @since 2.8
  1117. *
  1118. * @return string
  1119. */
  1120. function username() {
  1121. if ( defined('WP_PROXY_USERNAME') )
  1122. return WP_PROXY_USERNAME;
  1123. return '';
  1124. }
  1125. /**
  1126. * Retrieve the password for proxy authentication.
  1127. *
  1128. * @since 2.8
  1129. *
  1130. * @return string
  1131. */
  1132. function password() {
  1133. if ( defined('WP_PROXY_PASSWORD') )
  1134. return WP_PROXY_PASSWORD;
  1135. return '';
  1136. }
  1137. /**
  1138. * Retrieve authentication string for proxy authentication.
  1139. *
  1140. * @since 2.8
  1141. *
  1142. * @return string
  1143. */
  1144. function authentication() {
  1145. return $this->username() . ':' . $this->password();
  1146. }
  1147. /**
  1148. * Retrieve header string for proxy authentication.
  1149. *
  1150. * @since 2.8
  1151. *
  1152. * @return string
  1153. */
  1154. function authentication_header() {
  1155. return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
  1156. }
  1157. /**
  1158. * Whether URL should be sent through the proxy server.
  1159. *
  1160. * We want to keep localhost and the blog URL from being sent through the proxy server, because
  1161. * some proxies can not handle this. We also have the constant available for defining other
  1162. * hosts that won't be sent through the proxy.
  1163. *
  1164. * @uses WP_PROXY_BYPASS_HOSTS
  1165. * @since 2.8.0
  1166. *
  1167. * @param string $uri URI to check.
  1168. * @return bool True, to send through the proxy and false if, the proxy should not be used.
  1169. */
  1170. function send_through_proxy( $uri ) {
  1171. // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
  1172. // This will be displayed on blogs, which is not reasonable.
  1173. $check = @parse_url($uri);
  1174. // Malformed URL, can not process, but this could mean ssl, so let through anyway.
  1175. if ( $check === false )
  1176. return true;
  1177. $home = parse_url( get_option('siteurl') );
  1178. if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
  1179. return false;
  1180. if ( !defined('WP_PROXY_BYPASS_HOSTS') )
  1181. return true;
  1182. static $bypass_hosts;
  1183. static $wildcard_regex = false;
  1184. if ( null == $bypass_hosts ) {
  1185. $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
  1186. if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
  1187. $wildcard_regex = array();
  1188. foreach ( $bypass_hosts as $host )
  1189. $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/'));
  1190. $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
  1191. }
  1192. }
  1193. if ( !empty($wildcard_regex) )
  1194. return !preg_match($wildcard_regex, $check['host']);
  1195. else
  1196. return !in_array( $check['host'], $bypass_hosts );
  1197. }
  1198. }
  1199. /**
  1200. * Internal representation of a single cookie.
  1201. *
  1202. * Returned cookies are represented using this class, and when cookies are set, if they are not
  1203. * already a WP_Http_Cookie() object, then they are turned into one.
  1204. *
  1205. * @todo The WordPress convention is to use underscores instead of camelCase for function and method
  1206. * names. Need to switch to use underscores instead for the methods.
  1207. *
  1208. * @package WordPress
  1209. * @subpackage HTTP
  1210. * @since 2.8.0
  1211. */
  1212. class WP_Http_Cookie {
  1213. /**
  1214. * Cookie name.
  1215. *
  1216. * @since 2.8.0
  1217. * @var string
  1218. */
  1219. var $name;
  1220. /**
  1221. * Cookie value.
  1222. *
  1223. * @since 2.8.0
  1224. * @var string
  1225. */
  1226. var $value;
  1227. /**
  1228. * When the cookie expires.
  1229. *
  1230. * @since 2.8.0
  1231. * @var string
  1232. */
  1233. var $expires;
  1234. /**
  1235. * Cookie URL path.
  1236. *
  1237. * @since 2.8.0
  1238. * @var string
  1239. */
  1240. var $path;
  1241. /**
  1242. * Cookie Domain.
  1243. *
  1244. * @since 2.8.0
  1245. * @var string
  1246. */
  1247. var $domain;
  1248. /**
  1249. * Sets up this cookie object.
  1250. *
  1251. * The parameter $data should be either an associative array containing the indices names below
  1252. * or a header string detailing it.
  1253. *
  1254. * If it's an array, it should include the following elements:
  1255. * <ol>
  1256. * <li>Name</li>
  1257. * <li>Value - should NOT be urlencoded already.</li>
  1258. * <li>Expires - (optional) String or int (UNIX timestamp).</li>
  1259. * <li>Path (optional)</li>
  1260. * <li>Domain (optional)</li>
  1261. * </ol>
  1262. *
  1263. * @access public
  1264. * @since 2.8.0
  1265. *
  1266. * @param string|array $data Raw cookie data.
  1267. */
  1268. function __construct( $data ) {
  1269. if ( is_string( $data ) ) {
  1270. // Assume it's a header string direct from a previous request
  1271. $pairs = explode( ';', $data );
  1272. // Speā€¦

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