PageRenderTime 59ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/class-http.php

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

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