PageRenderTime 68ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/class-http.php

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

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