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

/wp-includes/class-http.php

https://bitbucket.org/theshipswakecreative/psw
PHP | 2173 lines | 930 code | 299 blank | 944 comment | 314 complexity | 07dd46287c290341b9a1125da4577917 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0
  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 used to consistently make outgoing HTTP requests easy for developers
  18. * while still being compatible with the many PHP configurations under which
  19. * WordPress runs.
  20. *
  21. * Debugging includes several actions, which pass different variables for debugging the HTTP API.
  22. *
  23. * @package WordPress
  24. * @subpackage HTTP
  25. * @since 2.7.0
  26. */
  27. class WP_Http {
  28. /**
  29. * Send an HTTP request to a URI.
  30. *
  31. * Please note: The only URI that are supported in the HTTP Transport implementation
  32. * are the HTTP and HTTPS protocols.
  33. *
  34. * @access public
  35. * @since 2.7.0
  36. *
  37. * @param string $url The request URL.
  38. * @param string|array $args {
  39. * Optional. Array or string of HTTP request arguments.
  40. *
  41. * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
  42. * Some transports technically allow others, but should not be
  43. * assumed. Default 'GET'.
  44. * @type int $timeout How long the connection should stay open in seconds. Default 5.
  45. * @type int $redirection Number of allowed redirects. Not supported by all transports
  46. * Default 5.
  47. * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
  48. * Default '1.0'.
  49. * @type string $user-agent User-agent value sent.
  50. * Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
  51. * @type bool $reject_unsafe_urls Whether to pass URLs through {@see wp_http_validate_url()}.
  52. * Default false.
  53. * @type bool $blocking Whether the calling code requires the result of the request.
  54. * If set to false, the request will be sent to the remote server,
  55. * and processing returned to the calling code immediately, the caller
  56. * will know if the request succeeded or failed, but will not receive
  57. * any response from the remote server. Default true.
  58. * @type string|array $headers Array or string of headers to send with the request.
  59. * Default empty array.
  60. * @type array $cookies List of cookies to send with the request. Default empty array.
  61. * @type string|array $body Body to send with the request. Default null.
  62. * @type bool $compress Whether to compress the $body when sending the request.
  63. * Default false.
  64. * @type bool $decompress Whether to decompress a compressed response. If set to false and
  65. * compressed content is returned in the response anyway, it will
  66. * need to be separately decompressed. Default true.
  67. * @type bool $sslverify Whether to verify SSL for the request. Default true.
  68. * @type string sslcertificates Absolute path to an SSL certificate .crt file.
  69. * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
  70. * @type bool $stream Whether to stream to a file. If set to true and no filename was
  71. * given, it will be droped it in the WP temp dir and its name will
  72. * be set using the basename of the URL. Default false.
  73. * @type string $filename Filename of the file to write to when streaming. $stream must be
  74. * set to true. Default null.
  75. * @type int $limit_response_size Size in bytes to limit the response to. Default null.
  76. *
  77. * }
  78. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  79. * A WP_Error instance upon error.
  80. */
  81. public function request( $url, $args = array() ) {
  82. global $wp_version;
  83. $defaults = array(
  84. 'method' => 'GET',
  85. /**
  86. * Filter the timeout value for an HTTP request.
  87. *
  88. * @since 2.7.0
  89. *
  90. * @param int $timeout_value Time in seconds until a request times out.
  91. * Default 5.
  92. */
  93. 'timeout' => apply_filters( 'http_request_timeout', 5 ),
  94. /**
  95. * Filter the number of redirects allowed during an HTTP request.
  96. *
  97. * @since 2.7.0
  98. *
  99. * @param int $redirect_count Number of redirects allowed. Default 5.
  100. */
  101. 'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
  102. /**
  103. * Filter the version of the HTTP protocol used in a request.
  104. *
  105. * @since 2.7.0
  106. *
  107. * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
  108. * Default '1.0'.
  109. */
  110. 'httpversion' => apply_filters( 'http_request_version', '1.0' ),
  111. /**
  112. * Filter the user agent value sent with an HTTP request.
  113. *
  114. * @since 2.7.0
  115. *
  116. * @param string $user_agent WordPress user agent string.
  117. */
  118. 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
  119. /**
  120. * Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
  121. *
  122. * @since 3.6.0
  123. *
  124. * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
  125. * Default false.
  126. */
  127. 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
  128. 'blocking' => true,
  129. 'headers' => array(),
  130. 'cookies' => array(),
  131. 'body' => null,
  132. 'compress' => false,
  133. 'decompress' => true,
  134. 'sslverify' => true,
  135. 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
  136. 'stream' => false,
  137. 'filename' => null,
  138. 'limit_response_size' => null,
  139. );
  140. // Pre-parse for the HEAD checks.
  141. $args = wp_parse_args( $args );
  142. // By default, Head requests do not cause redirections.
  143. if ( isset($args['method']) && 'HEAD' == $args['method'] )
  144. $defaults['redirection'] = 0;
  145. $r = wp_parse_args( $args, $defaults );
  146. /**
  147. * Filter the arguments used in an HTTP request.
  148. *
  149. * @since 2.7.0
  150. *
  151. * @param array $r An array of HTTP request arguments.
  152. * @param string $url The request URL.
  153. */
  154. $r = apply_filters( 'http_request_args', $r, $url );
  155. // The transports decrement this, store a copy of the original value for loop purposes.
  156. if ( ! isset( $r['_redirection'] ) )
  157. $r['_redirection'] = $r['redirection'];
  158. /**
  159. * Filter whether to preempt an HTTP request's return.
  160. *
  161. * Returning a truthy value to the filter will short-circuit
  162. * the HTTP request and return early with that value.
  163. *
  164. * @since 2.9.0
  165. *
  166. * @param bool $preempt Whether to preempt an HTTP request return. Default false.
  167. * @param array $r HTTP request arguments.
  168. * @param string $url The request URL.
  169. */
  170. $pre = apply_filters( 'pre_http_request', false, $r, $url );
  171. if ( false !== $pre )
  172. return $pre;
  173. if ( function_exists( 'wp_kses_bad_protocol' ) ) {
  174. if ( $r['reject_unsafe_urls'] )
  175. $url = wp_http_validate_url( $url );
  176. $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
  177. }
  178. $arrURL = @parse_url( $url );
  179. if ( empty( $url ) || empty( $arrURL['scheme'] ) )
  180. return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
  181. if ( $this->block_request( $url ) )
  182. return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
  183. /*
  184. * Determine if this is a https call and pass that on to the transport functions
  185. * so that we can blacklist the transports that do not support ssl verification
  186. */
  187. $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
  188. // Determine if this request is to OUR install of WordPress.
  189. $homeURL = parse_url( get_bloginfo( 'url' ) );
  190. $r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
  191. unset( $homeURL );
  192. /*
  193. * If we are streaming to a file but no filename was given drop it in the WP temp dir
  194. * and pick its name using the basename of the $url.
  195. */
  196. if ( $r['stream'] && empty( $r['filename'] ) )
  197. $r['filename'] = get_temp_dir() . basename( $url );
  198. /*
  199. * Force some settings if we are streaming to a file and check for existence and perms
  200. * of destination directory.
  201. */
  202. if ( $r['stream'] ) {
  203. $r['blocking'] = true;
  204. if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
  205. return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
  206. }
  207. if ( is_null( $r['headers'] ) )
  208. $r['headers'] = array();
  209. if ( ! is_array( $r['headers'] ) ) {
  210. $processedHeaders = WP_Http::processHeaders( $r['headers'], $url );
  211. $r['headers'] = $processedHeaders['headers'];
  212. }
  213. if ( isset( $r['headers']['User-Agent'] ) ) {
  214. $r['user-agent'] = $r['headers']['User-Agent'];
  215. unset( $r['headers']['User-Agent'] );
  216. }
  217. if ( isset( $r['headers']['user-agent'] ) ) {
  218. $r['user-agent'] = $r['headers']['user-agent'];
  219. unset( $r['headers']['user-agent'] );
  220. }
  221. if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
  222. $r['headers']['connection'] = 'close';
  223. }
  224. // Construct Cookie: header if any cookies are set.
  225. WP_Http::buildCookieHeader( $r );
  226. // Avoid issues where mbstring.func_overload is enabled.
  227. mbstring_binary_safe_encoding();
  228. if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
  229. if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
  230. $r['headers']['Accept-Encoding'] = $encoding;
  231. }
  232. if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
  233. if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
  234. $r['body'] = http_build_query( $r['body'], null, '&' );
  235. if ( ! isset( $r['headers']['Content-Type'] ) )
  236. $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
  237. }
  238. if ( '' === $r['body'] )
  239. $r['body'] = null;
  240. if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
  241. $r['headers']['Content-Length'] = strlen( $r['body'] );
  242. }
  243. $response = $this->_dispatch_request( $url, $r );
  244. reset_mbstring_encoding();
  245. if ( is_wp_error( $response ) )
  246. return $response;
  247. // Append cookies that were used in this request to the response
  248. if ( ! empty( $r['cookies'] ) ) {
  249. $cookies_set = wp_list_pluck( $response['cookies'], 'name' );
  250. foreach ( $r['cookies'] as $cookie ) {
  251. if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
  252. $response['cookies'][] = $cookie;
  253. }
  254. }
  255. }
  256. return $response;
  257. }
  258. /**
  259. * Tests which transports are capable of supporting the request.
  260. *
  261. * @since 3.2.0
  262. * @access private
  263. *
  264. * @param array $args Request arguments
  265. * @param string $url URL to Request
  266. *
  267. * @return string|bool Class name for the first transport that claims to support the request. False if no transport claims to support the request.
  268. */
  269. public function _get_first_available_transport( $args, $url = null ) {
  270. /**
  271. * Filter which HTTP transports are available and in what order.
  272. *
  273. * @since 3.7.0
  274. *
  275. * @param array $value Array of HTTP transports to check. Default array contains
  276. * 'curl', and 'streams', in that order.
  277. * @param array $args HTTP request arguments.
  278. * @param string $url The URL to request.
  279. */
  280. $request_order = apply_filters( 'http_api_transports', array( 'curl', 'streams' ), $args, $url );
  281. // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
  282. foreach ( $request_order as $transport ) {
  283. $class = 'WP_HTTP_' . $transport;
  284. // Check to see if this transport is a possibility, calls the transport statically.
  285. if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
  286. continue;
  287. return $class;
  288. }
  289. return false;
  290. }
  291. /**
  292. * Dispatches a HTTP request to a supporting transport.
  293. *
  294. * Tests each transport in order to find a transport which matches the request arguments.
  295. * Also caches the transport instance to be used later.
  296. *
  297. * The order for requests is cURL, and then PHP Streams.
  298. *
  299. * @since 3.2.0
  300. * @access private
  301. *
  302. * @param string $url URL to Request
  303. * @param array $args Request arguments
  304. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  305. */
  306. private function _dispatch_request( $url, $args ) {
  307. static $transports = array();
  308. $class = $this->_get_first_available_transport( $args, $url );
  309. if ( !$class )
  310. return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
  311. // Transport claims to support request, instantiate it and give it a whirl.
  312. if ( empty( $transports[$class] ) )
  313. $transports[$class] = new $class;
  314. $response = $transports[$class]->request( $url, $args );
  315. /**
  316. * Fires after an HTTP API response is received and before the response is returned.
  317. *
  318. * @since 2.8.0
  319. *
  320. * @param array|WP_Error $response HTTP response or WP_Error object.
  321. * @param string $context Context under which the hook is fired.
  322. * @param string $class HTTP transport used.
  323. * @param array $args HTTP request arguments.
  324. * @param string $url The request URL.
  325. */
  326. do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
  327. if ( is_wp_error( $response ) )
  328. return $response;
  329. /**
  330. * Filter the HTTP API response immediately before the response is returned.
  331. *
  332. * @since 2.9.0
  333. *
  334. * @param array $response HTTP response.
  335. * @param array $args HTTP request arguments.
  336. * @param string $url The request URL.
  337. */
  338. return apply_filters( 'http_response', $response, $args, $url );
  339. }
  340. /**
  341. * Uses the POST HTTP method.
  342. *
  343. * Used for sending data that is expected to be in the body.
  344. *
  345. * @access public
  346. * @since 2.7.0
  347. *
  348. * @param string $url The request URL.
  349. * @param string|array $args Optional. Override the defaults.
  350. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  351. */
  352. public function post($url, $args = array()) {
  353. $defaults = array('method' => 'POST');
  354. $r = wp_parse_args( $args, $defaults );
  355. return $this->request($url, $r);
  356. }
  357. /**
  358. * Uses the GET HTTP method.
  359. *
  360. * Used for sending data that is expected to be in the body.
  361. *
  362. * @access public
  363. * @since 2.7.0
  364. *
  365. * @param string $url The request URL.
  366. * @param string|array $args Optional. Override the defaults.
  367. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  368. */
  369. public function get($url, $args = array()) {
  370. $defaults = array('method' => 'GET');
  371. $r = wp_parse_args( $args, $defaults );
  372. return $this->request($url, $r);
  373. }
  374. /**
  375. * Uses the HEAD HTTP method.
  376. *
  377. * Used for sending data that is expected to be in the body.
  378. *
  379. * @access public
  380. * @since 2.7.0
  381. *
  382. * @param string $url The request URL.
  383. * @param string|array $args Optional. Override the defaults.
  384. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  385. */
  386. public function head($url, $args = array()) {
  387. $defaults = array('method' => 'HEAD');
  388. $r = wp_parse_args( $args, $defaults );
  389. return $this->request($url, $r);
  390. }
  391. /**
  392. * Parses the responses and splits the parts into headers and body.
  393. *
  394. * @access public
  395. * @static
  396. * @since 2.7.0
  397. *
  398. * @param string $strResponse The full response string
  399. * @return array Array with 'headers' and 'body' keys.
  400. */
  401. public static function processResponse($strResponse) {
  402. $res = explode("\r\n\r\n", $strResponse, 2);
  403. return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
  404. }
  405. /**
  406. * Transform header string into an array.
  407. *
  408. * If an array is given then it is assumed to be raw header data with numeric keys with the
  409. * headers as the values. No headers must be passed that were already processed.
  410. *
  411. * @access public
  412. * @static
  413. * @since 2.7.0
  414. *
  415. * @param string|array $headers
  416. * @param string $url The URL that was requested
  417. * @return array Processed string headers. If duplicate headers are encountered,
  418. * Then a numbered array is returned as the value of that header-key.
  419. */
  420. public static function processHeaders( $headers, $url = '' ) {
  421. // Split headers, one per array element.
  422. if ( is_string($headers) ) {
  423. // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
  424. $headers = str_replace("\r\n", "\n", $headers);
  425. /*
  426. * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
  427. * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
  428. */
  429. $headers = preg_replace('/\n[ \t]/', ' ', $headers);
  430. // Create the headers array.
  431. $headers = explode("\n", $headers);
  432. }
  433. $response = array('code' => 0, 'message' => '');
  434. /*
  435. * If a redirection has taken place, The headers for each page request may have been passed.
  436. * In this case, determine the final HTTP header and parse from there.
  437. */
  438. for ( $i = count($headers)-1; $i >= 0; $i-- ) {
  439. if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
  440. $headers = array_splice($headers, $i);
  441. break;
  442. }
  443. }
  444. $cookies = array();
  445. $newheaders = array();
  446. foreach ( (array) $headers as $tempheader ) {
  447. if ( empty($tempheader) )
  448. continue;
  449. if ( false === strpos($tempheader, ':') ) {
  450. $stack = explode(' ', $tempheader, 3);
  451. $stack[] = '';
  452. list( , $response['code'], $response['message']) = $stack;
  453. continue;
  454. }
  455. list($key, $value) = explode(':', $tempheader, 2);
  456. $key = strtolower( $key );
  457. $value = trim( $value );
  458. if ( isset( $newheaders[ $key ] ) ) {
  459. if ( ! is_array( $newheaders[ $key ] ) )
  460. $newheaders[$key] = array( $newheaders[ $key ] );
  461. $newheaders[ $key ][] = $value;
  462. } else {
  463. $newheaders[ $key ] = $value;
  464. }
  465. if ( 'set-cookie' == $key )
  466. $cookies[] = new WP_Http_Cookie( $value, $url );
  467. }
  468. return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
  469. }
  470. /**
  471. * Takes the arguments for a ::request() and checks for the cookie array.
  472. *
  473. * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
  474. * which are each parsed into strings and added to the Cookie: header (within the arguments array).
  475. * Edits the array by reference.
  476. *
  477. * @access public
  478. * @version 2.8.0
  479. * @static
  480. *
  481. * @param array $r Full array of args passed into ::request()
  482. */
  483. public static function buildCookieHeader( &$r ) {
  484. if ( ! empty($r['cookies']) ) {
  485. // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
  486. foreach ( $r['cookies'] as $name => $value ) {
  487. if ( ! is_object( $value ) )
  488. $r['cookies'][ $name ] = new WP_HTTP_Cookie( array( 'name' => $name, 'value' => $value ) );
  489. }
  490. $cookies_header = '';
  491. foreach ( (array) $r['cookies'] as $cookie ) {
  492. $cookies_header .= $cookie->getHeaderValue() . '; ';
  493. }
  494. $cookies_header = substr( $cookies_header, 0, -2 );
  495. $r['headers']['cookie'] = $cookies_header;
  496. }
  497. }
  498. /**
  499. * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
  500. *
  501. * Based off the HTTP http_encoding_dechunk function.
  502. *
  503. * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
  504. *
  505. * @access public
  506. * @since 2.7.0
  507. * @static
  508. *
  509. * @param string $body Body content
  510. * @return string Chunked decoded body on success or raw body on failure.
  511. */
  512. public static function chunkTransferDecode( $body ) {
  513. // The body is not chunked encoded or is malformed.
  514. if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
  515. return $body;
  516. $parsed_body = '';
  517. // We'll be altering $body, so need a backup in case of error.
  518. $body_original = $body;
  519. while ( true ) {
  520. $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
  521. if ( ! $has_chunk || empty( $match[1] ) )
  522. return $body_original;
  523. $length = hexdec( $match[1] );
  524. $chunk_length = strlen( $match[0] );
  525. // Parse out the chunk of data.
  526. $parsed_body .= substr( $body, $chunk_length, $length );
  527. // Remove the chunk from the raw data.
  528. $body = substr( $body, $length + $chunk_length );
  529. // End of the document.
  530. if ( '0' === trim( $body ) )
  531. return $parsed_body;
  532. }
  533. }
  534. /**
  535. * Block requests through the proxy.
  536. *
  537. * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
  538. * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
  539. *
  540. * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
  541. * file and this will only allow localhost and your blog to make requests. The constant
  542. * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
  543. * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
  544. * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
  545. *
  546. * @since 2.8.0
  547. * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
  548. * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
  549. *
  550. * @param string $uri URI of url.
  551. * @return bool True to block, false to allow.
  552. */
  553. public function block_request($uri) {
  554. // We don't need to block requests, because nothing is blocked.
  555. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
  556. return false;
  557. $check = parse_url($uri);
  558. if ( ! $check )
  559. return true;
  560. $home = parse_url( get_option('siteurl') );
  561. // Don't block requests back to ourselves by default.
  562. if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
  563. /**
  564. * Filter whether to block local requests through the proxy.
  565. *
  566. * @since 2.8.0
  567. *
  568. * @param bool $block Whether to block local requests through proxy.
  569. * Default false.
  570. */
  571. return apply_filters( 'block_local_requests', false );
  572. }
  573. if ( !defined('WP_ACCESSIBLE_HOSTS') )
  574. return true;
  575. static $accessible_hosts;
  576. static $wildcard_regex = false;
  577. if ( null == $accessible_hosts ) {
  578. $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
  579. if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
  580. $wildcard_regex = array();
  581. foreach ( $accessible_hosts as $host )
  582. $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
  583. $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
  584. }
  585. }
  586. if ( !empty($wildcard_regex) )
  587. return !preg_match($wildcard_regex, $check['host']);
  588. else
  589. return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
  590. }
  591. public static function make_absolute_url( $maybe_relative_path, $url ) {
  592. if ( empty( $url ) )
  593. return $maybe_relative_path;
  594. // Check for a scheme.
  595. if ( false !== strpos( $maybe_relative_path, '://' ) )
  596. return $maybe_relative_path;
  597. if ( ! $url_parts = @parse_url( $url ) )
  598. return $maybe_relative_path;
  599. if ( ! $relative_url_parts = @parse_url( $maybe_relative_path ) )
  600. return $maybe_relative_path;
  601. $absolute_path = $url_parts['scheme'] . '://' . $url_parts['host'];
  602. if ( isset( $url_parts['port'] ) )
  603. $absolute_path .= ':' . $url_parts['port'];
  604. // Start off with the Absolute URL path.
  605. $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
  606. // If it's a root-relative path, then great.
  607. if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
  608. $path = $relative_url_parts['path'];
  609. // Else it's a relative path.
  610. } elseif ( ! empty( $relative_url_parts['path'] ) ) {
  611. // Strip off any file components from the absolute path.
  612. $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
  613. // Build the new path.
  614. $path .= $relative_url_parts['path'];
  615. // Strip all /path/../ out of the path.
  616. while ( strpos( $path, '../' ) > 1 ) {
  617. $path = preg_replace( '![^/]+/\.\./!', '', $path );
  618. }
  619. // Strip any final leading ../ from the path.
  620. $path = preg_replace( '!^/(\.\./)+!', '', $path );
  621. }
  622. // Add the Query string.
  623. if ( ! empty( $relative_url_parts['query'] ) )
  624. $path .= '?' . $relative_url_parts['query'];
  625. return $absolute_path . '/' . ltrim( $path, '/' );
  626. }
  627. /**
  628. * Handles HTTP Redirects and follows them if appropriate.
  629. *
  630. * @since 3.7.0
  631. *
  632. * @param string $url The URL which was requested.
  633. * @param array $args The Arguments which were used to make the request.
  634. * @param array $response The Response of the HTTP request.
  635. * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
  636. */
  637. public static function handle_redirects( $url, $args, $response ) {
  638. // If no redirects are present, or, redirects were not requested, perform no action.
  639. if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
  640. return false;
  641. // Only perform redirections on redirection http codes.
  642. if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
  643. return false;
  644. // Don't redirect if we've run out of redirects.
  645. if ( $args['redirection']-- <= 0 )
  646. return new WP_Error( 'http_request_failed', __('Too many redirects.') );
  647. $redirect_location = $response['headers']['location'];
  648. // If there were multiple Location headers, use the last header specified.
  649. if ( is_array( $redirect_location ) )
  650. $redirect_location = array_pop( $redirect_location );
  651. $redirect_location = WP_HTTP::make_absolute_url( $redirect_location, $url );
  652. // POST requests should not POST to a redirected location.
  653. if ( 'POST' == $args['method'] ) {
  654. if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
  655. $args['method'] = 'GET';
  656. }
  657. // Include valid cookies in the redirect process.
  658. if ( ! empty( $response['cookies'] ) ) {
  659. foreach ( $response['cookies'] as $cookie ) {
  660. if ( $cookie->test( $redirect_location ) )
  661. $args['cookies'][] = $cookie;
  662. }
  663. }
  664. return wp_remote_request( $redirect_location, $args );
  665. }
  666. /**
  667. * Determines if a specified string represents an IP address or not.
  668. *
  669. * This function also detects the type of the IP address, returning either
  670. * '4' or '6' to represent a IPv4 and IPv6 address respectively.
  671. * This does not verify if the IP is a valid IP, only that it appears to be
  672. * an IP address.
  673. *
  674. * @see http://home.deds.nl/~aeron/regex/ for IPv6 regex
  675. *
  676. * @since 3.7.0
  677. * @static
  678. *
  679. * @param string $maybe_ip A suspected IP address
  680. * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
  681. */
  682. public static function is_ip_address( $maybe_ip ) {
  683. if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
  684. return 4;
  685. if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) )
  686. return 6;
  687. return false;
  688. }
  689. }
  690. /**
  691. * HTTP request method uses PHP Streams to retrieve the url.
  692. *
  693. * @since 2.7.0
  694. * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
  695. */
  696. class WP_Http_Streams {
  697. /**
  698. * Send a HTTP request to a URI using PHP Streams.
  699. *
  700. * @see WP_Http::request For default options descriptions.
  701. *
  702. * @since 2.7.0
  703. * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
  704. *
  705. * @access public
  706. * @param string $url The request URL.
  707. * @param string|array $args Optional. Override the defaults.
  708. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  709. */
  710. public function request($url, $args = array()) {
  711. $defaults = array(
  712. 'method' => 'GET', 'timeout' => 5,
  713. 'redirection' => 5, 'httpversion' => '1.0',
  714. 'blocking' => true,
  715. 'headers' => array(), 'body' => null, 'cookies' => array()
  716. );
  717. $r = wp_parse_args( $args, $defaults );
  718. if ( isset($r['headers']['User-Agent']) ) {
  719. $r['user-agent'] = $r['headers']['User-Agent'];
  720. unset($r['headers']['User-Agent']);
  721. } else if ( isset($r['headers']['user-agent']) ) {
  722. $r['user-agent'] = $r['headers']['user-agent'];
  723. unset($r['headers']['user-agent']);
  724. }
  725. // Construct Cookie: header if any cookies are set.
  726. WP_Http::buildCookieHeader( $r );
  727. $arrURL = parse_url($url);
  728. $connect_host = $arrURL['host'];
  729. $secure_transport = ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' );
  730. if ( ! isset( $arrURL['port'] ) ) {
  731. if ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) {
  732. $arrURL['port'] = 443;
  733. $secure_transport = true;
  734. } else {
  735. $arrURL['port'] = 80;
  736. }
  737. }
  738. if ( isset( $r['headers']['Host'] ) || isset( $r['headers']['host'] ) ) {
  739. if ( isset( $r['headers']['Host'] ) )
  740. $arrURL['host'] = $r['headers']['Host'];
  741. else
  742. $arrURL['host'] = $r['headers']['host'];
  743. unset( $r['headers']['Host'], $r['headers']['host'] );
  744. }
  745. /*
  746. * Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect
  747. * to ::1, which fails when the server is not set up for it. For compatibility, always
  748. * connect to the IPv4 address.
  749. */
  750. if ( 'localhost' == strtolower( $connect_host ) )
  751. $connect_host = '127.0.0.1';
  752. $connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
  753. $is_local = isset( $r['local'] ) && $r['local'];
  754. $ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
  755. if ( $is_local ) {
  756. /**
  757. * Filter whether SSL should be verified for local requests.
  758. *
  759. * @since 2.8.0
  760. *
  761. * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
  762. */
  763. $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
  764. } elseif ( ! $is_local ) {
  765. /**
  766. * Filter whether SSL should be verified for non-local requests.
  767. *
  768. * @since 2.8.0
  769. *
  770. * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
  771. */
  772. $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
  773. }
  774. $proxy = new WP_HTTP_Proxy();
  775. $context = stream_context_create( array(
  776. 'ssl' => array(
  777. 'verify_peer' => $ssl_verify,
  778. //'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
  779. 'capture_peer_cert' => $ssl_verify,
  780. 'SNI_enabled' => true,
  781. 'cafile' => $r['sslcertificates'],
  782. 'allow_self_signed' => ! $ssl_verify,
  783. )
  784. ) );
  785. $timeout = (int) floor( $r['timeout'] );
  786. $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
  787. $connect_timeout = max( $timeout, 1 );
  788. // Store error number.
  789. $connection_error = null;
  790. // Store error string.
  791. $connection_error_str = null;
  792. if ( !WP_DEBUG ) {
  793. // In the event that the SSL connection fails, silence the many PHP Warnings.
  794. if ( $secure_transport )
  795. $error_reporting = error_reporting(0);
  796. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
  797. $handle = @stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
  798. else
  799. $handle = @stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
  800. if ( $secure_transport )
  801. error_reporting( $error_reporting );
  802. } else {
  803. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
  804. $handle = stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
  805. else
  806. $handle = stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
  807. }
  808. if ( false === $handle ) {
  809. // SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
  810. if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str )
  811. return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
  812. return new WP_Error('http_request_failed', $connection_error . ': ' . $connection_error_str );
  813. }
  814. // Verify that the SSL certificate is valid for this request.
  815. if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
  816. if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) )
  817. return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
  818. }
  819. stream_set_timeout( $handle, $timeout, $utimeout );
  820. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
  821. $requestPath = $url;
  822. else
  823. $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
  824. if ( empty($requestPath) )
  825. $requestPath .= '/';
  826. $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
  827. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
  828. $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
  829. else
  830. $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
  831. if ( isset($r['user-agent']) )
  832. $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
  833. if ( is_array($r['headers']) ) {
  834. foreach ( (array) $r['headers'] as $header => $headerValue )
  835. $strHeaders .= $header . ': ' . $headerValue . "\r\n";
  836. } else {
  837. $strHeaders .= $r['headers'];
  838. }
  839. if ( $proxy->use_authentication() )
  840. $strHeaders .= $proxy->authentication_header() . "\r\n";
  841. $strHeaders .= "\r\n";
  842. if ( ! is_null($r['body']) )
  843. $strHeaders .= $r['body'];
  844. fwrite($handle, $strHeaders);
  845. if ( ! $r['blocking'] ) {
  846. stream_set_blocking( $handle, 0 );
  847. fclose( $handle );
  848. return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
  849. }
  850. $strResponse = '';
  851. $bodyStarted = false;
  852. $keep_reading = true;
  853. $block_size = 4096;
  854. if ( isset( $r['limit_response_size'] ) )
  855. $block_size = min( $block_size, $r['limit_response_size'] );
  856. // If streaming to a file setup the file handle.
  857. if ( $r['stream'] ) {
  858. if ( ! WP_DEBUG )
  859. $stream_handle = @fopen( $r['filename'], 'w+' );
  860. else
  861. $stream_handle = fopen( $r['filename'], 'w+' );
  862. if ( ! $stream_handle )
  863. return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
  864. $bytes_written = 0;
  865. while ( ! feof($handle) && $keep_reading ) {
  866. $block = fread( $handle, $block_size );
  867. if ( ! $bodyStarted ) {
  868. $strResponse .= $block;
  869. if ( strpos( $strResponse, "\r\n\r\n" ) ) {
  870. $process = WP_Http::processResponse( $strResponse );
  871. $bodyStarted = true;
  872. $block = $process['body'];
  873. unset( $strResponse );
  874. $process['body'] = '';
  875. }
  876. }
  877. $this_block_size = strlen( $block );
  878. if ( isset( $r['limit_response_size'] ) && ( $bytes_written + $this_block_size ) > $r['limit_response_size'] )
  879. $block = substr( $block, 0, ( $r['limit_response_size'] - $bytes_written ) );
  880. $bytes_written_to_file = fwrite( $stream_handle, $block );
  881. if ( $bytes_written_to_file != $this_block_size ) {
  882. fclose( $handle );
  883. fclose( $stream_handle );
  884. return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
  885. }
  886. $bytes_written += $bytes_written_to_file;
  887. $keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
  888. }
  889. fclose( $stream_handle );
  890. } else {
  891. $header_length = 0;
  892. while ( ! feof( $handle ) && $keep_reading ) {
  893. $block = fread( $handle, $block_size );
  894. $strResponse .= $block;
  895. if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
  896. $header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
  897. $bodyStarted = true;
  898. }
  899. $keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
  900. }
  901. $process = WP_Http::processResponse( $strResponse );
  902. unset( $strResponse );
  903. }
  904. fclose( $handle );
  905. $arrHeaders = WP_Http::processHeaders( $process['headers'], $url );
  906. $response = array(
  907. 'headers' => $arrHeaders['headers'],
  908. // Not yet processed.
  909. 'body' => null,
  910. 'response' => $arrHeaders['response'],
  911. 'cookies' => $arrHeaders['cookies'],
  912. 'filename' => $r['filename']
  913. );
  914. // Handle redirects.
  915. if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
  916. return $redirect_response;
  917. // If the body was chunk encoded, then decode it.
  918. if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
  919. $process['body'] = WP_Http::chunkTransferDecode($process['body']);
  920. if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
  921. $process['body'] = WP_Http_Encoding::decompress( $process['body'] );
  922. if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
  923. $process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
  924. $response['body'] = $process['body'];
  925. return $response;
  926. }
  927. /**
  928. * Verifies the received SSL certificate against it's Common Names and subjectAltName fields
  929. *
  930. * PHP's SSL verifications only verify that it's a valid Certificate, it doesn't verify if
  931. * the certificate is valid for the hostname which was requested.
  932. * This function verifies the requested hostname against certificate's subjectAltName field,
  933. * if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
  934. *
  935. * IP Address support is included if the request is being made to an IP address.
  936. *
  937. * @since 3.7.0
  938. * @static
  939. *
  940. * @param stream $stream The PHP Stream which the SSL request is being made over
  941. * @param string $host The hostname being requested
  942. * @return bool If the cerficiate presented in $stream is valid for $host
  943. */
  944. public static function verify_ssl_certificate( $stream, $host ) {
  945. $context_options = stream_context_get_options( $stream );
  946. if ( empty( $context_options['ssl']['peer_certificate'] ) )
  947. return false;
  948. $cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
  949. if ( ! $cert )
  950. return false;
  951. /*
  952. * If the request is being made to an IP address, we'll validate against IP fields
  953. * in the cert (if they exist)
  954. */
  955. $host_type = ( WP_HTTP::is_ip_address( $host ) ? 'ip' : 'dns' );
  956. $certificate_hostnames = array();
  957. if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
  958. $match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
  959. foreach ( $match_against as $match ) {
  960. list( $match_type, $match_host ) = explode( ':', $match );
  961. if ( $host_type == strtolower( trim( $match_type ) ) ) // IP: or DNS:
  962. $certificate_hostnames[] = strtolower( trim( $match_host ) );
  963. }
  964. } elseif ( !empty( $cert['subject']['CN'] ) ) {
  965. // Only use the CN when the certificate includes no subjectAltName extension.
  966. $certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
  967. }
  968. // Exact hostname/IP matches.
  969. if ( in_array( strtolower( $host ), $certificate_hostnames ) )
  970. return true;
  971. // IP's can't be wildcards, Stop processing.
  972. if ( 'ip' == $host_type )
  973. return false;
  974. // Test to see if the domain is at least 2 deep for wildcard support.
  975. if ( substr_count( $host, '.' ) < 2 )
  976. return false;
  977. // Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
  978. $wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
  979. return in_array( strtolower( $wildcard_host ), $certificate_hostnames );
  980. }
  981. /**
  982. * Whether this class can be used for retrieving a URL.
  983. *
  984. * @static
  985. * @access public
  986. * @since 2.7.0
  987. * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
  988. *
  989. * @return boolean False means this class can not be used, true means it can.
  990. */
  991. public static function test( $args = array() ) {
  992. if ( ! function_exists( 'stream_socket_client' ) )
  993. return false;
  994. $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
  995. if ( $is_ssl ) {
  996. if ( ! extension_loaded( 'openssl' ) )
  997. return false;
  998. if ( ! function_exists( 'openssl_x509_parse' ) )
  999. return false;
  1000. }
  1001. /**
  1002. * Filter whether streams can be used as a transport for retrieving a URL.
  1003. *
  1004. * @since 2.7.0
  1005. *
  1006. * @param bool $use_class Whether the class can be used. Default true.
  1007. * @param array $args Request arguments.
  1008. */
  1009. return apply_filters( 'use_streams_transport', true, $args );
  1010. }
  1011. }
  1012. /**
  1013. * Deprecated HTTP Transport method which used fsockopen.
  1014. *
  1015. * This class is not used, and is included for backwards compatibility only.
  1016. * All code should make use of WP_HTTP directly through it's API.
  1017. *
  1018. * @see WP_HTTP::request
  1019. *
  1020. * @since 2.7.0
  1021. * @deprecated 3.7.0 Please use WP_HTTP::request() directly
  1022. */
  1023. class WP_HTTP_Fsockopen extends WP_HTTP_Streams {
  1024. // For backwards compatibility for users who are using the class directly.
  1025. }
  1026. /**
  1027. * HTTP request method uses Curl extension to retrieve the url.
  1028. *
  1029. * Requires the Curl extension to be installed.
  1030. *
  1031. * @package WordPress
  1032. * @subpackage HTTP
  1033. * @since 2.7.0
  1034. */
  1035. class WP_Http_Curl {
  1036. /**
  1037. * Temporary header storage for during requests.
  1038. *
  1039. * @since 3.2.0
  1040. * @access private
  1041. * @var string
  1042. */
  1043. private $headers = '';
  1044. /**
  1045. * Temporary body storage for during requests.
  1046. *
  1047. * @since 3.6.0
  1048. * @access private
  1049. * @var string
  1050. */
  1051. private $body = '';
  1052. /**
  1053. * The maximum amount of data to receive from the remote server.
  1054. *
  1055. * @since 3.6.0
  1056. * @access private
  1057. * @var int
  1058. */
  1059. private $max_body_length = false;
  1060. /**
  1061. * The file resource used for streaming to file.
  1062. *
  1063. * @since 3.6.0
  1064. * @access private
  1065. * @var resource
  1066. */
  1067. private $stream_handle = false;
  1068. /**
  1069. * Send a HTTP request to a URI using cURL extension.
  1070. *
  1071. * @access public
  1072. * @since 2.7.0
  1073. *
  1074. * @param string $url The request URL.
  1075. * @param string|array $args Optional. Override the defaults.
  1076. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  1077. */
  1078. public function request($url, $args = array()) {
  1079. $defaults = array(
  1080. 'method' => 'GET', 'timeout' => 5,
  1081. 'redirection' => 5, 'httpversion' => '1.0',
  1082. 'blocking' => true,
  1083. 'headers' => array(), 'body' => null, 'cookies' => array()
  1084. );
  1085. $r = wp_parse_args( $args, $defaults );
  1086. if ( isset($r['headers']['User-Agent']) ) {
  1087. $r['user-agent'] = $r['headers']['User-Agent'];
  1088. unset($r['headers']['User-Agent']);
  1089. } else if ( isset($r['headers']['user-agent']) ) {
  1090. $r['user-agent'] = $r['headers']['user-agent'];
  1091. unset($r['headers']['user-agent']);
  1092. }
  1093. // Construct Cookie: header if any cookies are set.
  1094. WP_Http::buildCookieHeader( $r );
  1095. $handle = curl_init();
  1096. // cURL offers really easy proxy support.
  1097. $proxy = new WP_HTTP_Proxy();
  1098. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
  1099. curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
  1100. curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
  1101. curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
  1102. if ( $proxy->use_authentication() ) {
  1103. curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
  1104. curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
  1105. }
  1106. }
  1107. $is_local = isset($r['local']) && $r['local'];
  1108. $ssl_verify = isset($r['sslverify']) && $r['sslverify'];
  1109. if ( $is_local ) {
  1110. /** This filter is documented in wp-includes/class-http.php */
  1111. $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
  1112. } elseif ( ! $is_local ) {
  1113. /** This filter is documented in wp-includes/class-http.php */
  1114. $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
  1115. }
  1116. /*
  1117. * CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
  1118. * a value of 0 will allow an unlimited timeout.
  1119. */
  1120. $timeout = (int) ceil( $r['timeout'] );
  1121. curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
  1122. curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
  1123. curl_setopt( $handle, CURLOPT_URL, $url);
  1124. curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
  1125. curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
  1126. curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
  1127. curl_setopt( $handle, CURLOPT_CAINFO, $r['sslcertificates'] );
  1128. curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
  1129. /*
  1130. * The option doesn't work with safe mode or when open_basedir is set, and there's
  1131. * a bug #17490 with redirected POST requests, so handle redirections outside Curl.
  1132. */
  1133. curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
  1134. if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
  1135. curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
  1136. switch ( $r['method'] ) {
  1137. case 'HEAD':
  1138. curl_setopt( $handle, CURLOPT_NOBODY, true );
  1139. break;
  1140. case 'POST':
  1141. curl_setopt( $handle, CURLOPT_POST, true );
  1142. curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
  1143. break;
  1144. case 'PUT':
  1145. curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
  1146. curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
  1147. break;
  1148. default:
  1149. curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
  1150. if ( ! is_null( $r['body'] ) )
  1151. curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
  1152. break;
  1153. }
  1154. if ( true === $r['blocking'] ) {
  1155. curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
  1156. curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
  1157. }
  1158. curl_setopt( $handle, CURLOPT_HEADER, false );
  1159. if ( isset( $r['limit_response_size'] ) )
  1160. $this->max_body_length = intval( $r['limit_response_size'] );
  1161. else
  1162. $this->max_body_length = false;
  1163. // If streaming to a file open a file handle, and setup our curl streaming handler.
  1164. if ( $r['stream'] ) {
  1165. if ( ! WP_DEBUG )
  1166. $this->stream_handle = @fopen( $r['filename'], 'w+' );
  1167. else
  1168. $this->stream_handle = fopen( $r['filename'], 'w+' );
  1169. if ( ! $this->stream_handle )
  1170. return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
  1171. } else {
  1172. $this->stream_handle = false;
  1173. }
  1174. if ( !empty( $r['headers'] ) ) {
  1175. // cURL expects full header strings in each element.
  1176. $headers = array();
  1177. foreach ( $r['headers'] as $name => $value ) {
  1178. $headers[] = "{$name}: $value";
  1179. }
  1180. curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
  1181. }
  1182. if ( $r['httpversion'] == '1.0' )
  1183. curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
  1184. else
  1185. curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
  1186. /**
  1187. * Fires before the cURL request is executed.
  1188. *
  1189. * Cookies are not currently handled by the HTTP API. This action allows
  1190. * plugins to handle cookies themselves.
  1191. *
  1192. * @since 2.8.0
  1193. *
  1194. * @param resource &$handle The cURL handle returned by curl_init().
  1195. * @param array $r The HTTP request arguments.
  1196. * @param string $url The request URL.
  1197. */
  1198. do_action_ref_array( 'http_api_curl', array( &$handle, $r, $url ) );
  1199. // We don't need to return the body, so don't. Just execute request and return.
  1200. if ( ! $r['blocking'] ) {
  1201. curl_exec( $handle );
  1202. if ( $curl_error = curl_error( $handle ) ) {
  1203. curl_close( $handle );
  1204. return new WP_Error( 'http_request_failed', $curl_error );
  1205. }
  1206. if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
  1207. curl_close( $handle );
  1208. return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
  1209. }
  1210. curl_close( $handle );
  1211. return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
  1212. }
  1213. curl_exec( $handle );
  1214. $theHeaders = WP_Http::processHeaders( $this->headers, $url );
  1215. $theBody = $this->body;
  1216. $this->headers = '';
  1217. $this->body = '';
  1218. $curl_error = curl_errno( $handle );
  1219. // If an error occurred, or, no response.
  1220. if ( $curl_error || ( 0 == strlen( $theBody ) && empty( $theHeaders['headers'] ) ) ) {
  1221. if ( CURLE_WRITE_ERROR /* 23 */ == $curl_error && $r['stream'] ) {
  1222. fclose( $this->stream_handle );
  1223. return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
  1224. }
  1225. if ( $curl_error = curl_error( $handle ) ) {
  1226. curl_close( $handle );
  1227. return new WP_Error( 'http_request_failed', $curl_error );
  1228. }
  1229. if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
  1230. curl_close( $handle );
  1231. return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
  1232. }
  1233. }
  1234. $response = array();
  1235. $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
  1236. $response['message'] = get_status_header_desc($response['code']);
  1237. curl_close( $handle );
  1238. if ( $r['stream'] )
  1239. fclose( $this->stream_handle );
  1240. $response = array(
  1241. 'headers' => $theHeaders['headers'],
  1242. 'body' => null,
  1243. 'response' => $response,
  1244. 'cookies' => $theHeaders['cookies'],
  1245. 'filename' => $r['filename']
  1246. );
  1247. // Handle redirects.
  1248. if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
  1249. return $redirect_response;
  1250. if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
  1251. $theBody = WP_Http_Encoding::decompress( $theBody );
  1252. $response['body'] = $theBody;
  1253. return $response;
  1254. }
  1255. /**
  1256. * Grab the headers of the cURL request
  1257. *
  1258. * Each header is sent individually to this callback, so we append to the $header property for temporary storage
  1259. *
  1260. * @since 3.2.0
  1261. * @access private
  1262. * @return int
  1263. */
  1264. private function stream_headers( $handle, $headers ) {
  1265. $this->headers .= $headers;
  1266. return strlen( $headers );
  1267. }
  1268. /**
  1269. * Grab the body of the cURL request
  1270. *
  1271. * The contents of the document are passed in chunks, so we append to the $body property for temporary storage.
  1272. * Returning a length shorter than the length of $data passed in will cause cURL to abort the request as "completed"
  1273. *
  1274. * @since 3.6.0
  1275. * @access private
  1276. * @return int
  1277. */
  1278. private function stream_body( $handle, $data ) {
  1279. $data_length = strlen( $data );
  1280. if ( $this->max_body_length && ( strlen( $this->body ) + $data_length ) > $this->max_body_length )
  1281. $data = substr( $data, 0, ( $this->max_body_length - $data_length ) );
  1282. if ( $this->stream_handle ) {
  1283. $bytes_written = fwrite( $this->stream_handle, $data );
  1284. } else {
  1285. $this->body .= $data;
  1286. $bytes_written = $data_length;
  1287. }
  1288. // Upon event of this function returning less than strlen( $data ) curl will error with CURLE_WRITE_ERROR.
  1289. return $bytes_written;
  1290. }
  1291. /**
  1292. * Whether this class can be used for retrieving an URL.
  1293. *
  1294. * @static
  1295. * @since 2.7.0
  1296. *
  1297. * @return boolean False means this class can not be used, true means it can.
  1298. */
  1299. public static function test( $args = array() ) {
  1300. if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
  1301. return false;
  1302. $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
  1303. if ( $is_ssl ) {
  1304. $curl_version = curl_version();
  1305. // Check whether this cURL version support SSL requests.
  1306. if ( ! (CURL_VERSION_SSL & $curl_version['features']) )
  1307. return false;
  1308. }
  1309. /**
  1310. * Filter whether cURL can be used as a transport for retrieving a URL.
  1311. *
  1312. * @since 2.7.0
  1313. *
  1314. * @param bool $use_class Whether the class can be used. Default true.
  1315. * @param array $args An array of request arguments.
  1316. */
  1317. return apply_filters( 'use_curl_transport', true, $args );
  1318. }
  1319. }
  1320. /**
  1321. * Adds Proxy support to the WordPress HTTP API.
  1322. *
  1323. * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
  1324. * enable proxy support. There are also a few filters that plugins can hook into for some of the
  1325. * constants.
  1326. *
  1327. * Please note that only BASIC authentication is supported by most transports.
  1328. * cURL MAY support more methods (such as NTLM authentication) depending on your environment.
  1329. *
  1330. * The constants are as follows:
  1331. * <ol>
  1332. * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
  1333. * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
  1334. * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
  1335. * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
  1336. * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
  1337. * You do not need to have localhost and the blog host in this list, because they will not be passed
  1338. * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
  1339. * </ol>
  1340. *
  1341. * An example can be as seen below.
  1342. * <code>
  1343. * define('WP_PROXY_HOST', '192.168.84.101');
  1344. * define('WP_PROXY_PORT', '8080');
  1345. * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
  1346. * </code>
  1347. *
  1348. * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
  1349. * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
  1350. * @since 2.8.0
  1351. */
  1352. class WP_HTTP_Proxy {
  1353. /**
  1354. * Whether proxy connection should be used.
  1355. *
  1356. * @since 2.8.0
  1357. *
  1358. * @use WP_PROXY_HOST
  1359. * @use WP_PROXY_PORT
  1360. *
  1361. * @return bool
  1362. */
  1363. public function is_enabled() {
  1364. return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
  1365. }
  1366. /**
  1367. * Whether authentication should be used.
  1368. *
  1369. * @since 2.8.0
  1370. *
  1371. * @use WP_PROXY_USERNAME
  1372. * @use WP_PROXY_PASSWORD
  1373. *
  1374. * @return bool
  1375. */
  1376. public function use_authentication() {
  1377. return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
  1378. }
  1379. /**
  1380. * Retrieve the host for the proxy server.
  1381. *
  1382. * @since 2.8.0
  1383. *
  1384. * @return string
  1385. */
  1386. public function host() {
  1387. if ( defined('WP_PROXY_HOST') )
  1388. return WP_PROXY_HOST;
  1389. return '';
  1390. }
  1391. /**
  1392. * Retrieve the port for the proxy server.
  1393. *
  1394. * @since 2.8.0
  1395. *
  1396. * @return string
  1397. */
  1398. public function port() {
  1399. if ( defined('WP_PROXY_PORT') )
  1400. return WP_PROXY_PORT;
  1401. return '';
  1402. }
  1403. /**
  1404. * Retrieve the username for proxy authentication.
  1405. *
  1406. * @since 2.8.0
  1407. *
  1408. * @return string
  1409. */
  1410. public function username() {
  1411. if ( defined('WP_PROXY_USERNAME') )
  1412. return WP_PROXY_USERNAME;
  1413. return '';
  1414. }
  1415. /**
  1416. * Retrieve the password for proxy authentication.
  1417. *
  1418. * @since 2.8.0
  1419. *
  1420. * @return string
  1421. */
  1422. public function password() {
  1423. if ( defined('WP_PROXY_PASSWORD') )
  1424. return WP_PROXY_PASSWORD;
  1425. return '';
  1426. }
  1427. /**
  1428. * Retrieve authentication string for proxy authentication.
  1429. *
  1430. * @since 2.8.0
  1431. *
  1432. * @return string
  1433. */
  1434. public function authentication() {
  1435. return $this->username() . ':' . $this->password();
  1436. }
  1437. /**
  1438. * Retrieve header string for proxy authentication.
  1439. *
  1440. * @since 2.8.0
  1441. *
  1442. * @return string
  1443. */
  1444. public function authentication_header() {
  1445. return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
  1446. }
  1447. /**
  1448. * Whether URL should be sent through the proxy server.
  1449. *
  1450. * We want to keep localhost and the blog URL from being sent through the proxy server, because
  1451. * some proxies can not handle this. We also have the constant available for defining other
  1452. * hosts that won't be sent through the proxy.
  1453. *
  1454. * @uses WP_PROXY_BYPASS_HOSTS
  1455. * @since 2.8.0
  1456. *
  1457. * @param string $uri URI to check.
  1458. * @return bool True, to send through the proxy and false if, the proxy should not be used.
  1459. */
  1460. public function send_through_proxy( $uri ) {
  1461. /*
  1462. * parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
  1463. * This will be displayed on blogs, which is not reasonable.
  1464. */
  1465. $check = @parse_url($uri);
  1466. // Malformed URL, can not process, but this could mean ssl, so let through anyway.
  1467. if ( $check === false )
  1468. return true;
  1469. $home = parse_url( get_option('siteurl') );
  1470. /**
  1471. * Filter whether to preempt sending the request through the proxy server.
  1472. *
  1473. * Returning false will bypass the proxy; returning true will send
  1474. * the request through the proxy. Returning null bypasses the filter.
  1475. *
  1476. * @since 3.5.0
  1477. *
  1478. * @param null $override Whether to override the request result. Default null.
  1479. * @param string $uri URL to check.
  1480. * @param array $check Associative array result of parsing the URI.
  1481. * @param array $home Associative array result of parsing the site URL.
  1482. */
  1483. $result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
  1484. if ( ! is_null( $result ) )
  1485. return $result;
  1486. if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) )
  1487. return false;
  1488. if ( !defined('WP_PROXY_BYPASS_HOSTS') )
  1489. return true;
  1490. static $bypass_hosts;
  1491. static $wildcard_regex = false;
  1492. if ( null == $bypass_hosts ) {
  1493. $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
  1494. if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
  1495. $wildcard_regex = array();
  1496. foreach ( $bypass_hosts as $host )
  1497. $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
  1498. $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
  1499. }
  1500. }
  1501. if ( !empty($wildcard_regex) )
  1502. return !preg_match($wildcard_regex, $check['host']);
  1503. else
  1504. return !in_array( $check['host'], $bypass_hosts );
  1505. }
  1506. }
  1507. /**
  1508. * Internal representation of a single cookie.
  1509. *
  1510. * Returned cookies are represented using this class, and when cookies are set, if they are not
  1511. * already a WP_Http_Cookie() object, then they are turned into one.
  1512. *
  1513. * @todo The WordPress convention is to use underscores instead of camelCase for function and method
  1514. * names. Need to switch to use underscores instead for the methods.
  1515. *
  1516. * @package WordPress
  1517. * @subpackage HTTP
  1518. * @since 2.8.0
  1519. */
  1520. class WP_Http_Cookie {
  1521. /**
  1522. * Cookie name.
  1523. *
  1524. * @since 2.8.0
  1525. * @var string
  1526. */
  1527. public $name;
  1528. /**
  1529. * Cookie value.
  1530. *
  1531. * @since 2.8.0
  1532. * @var string
  1533. */
  1534. public $value;
  1535. /**
  1536. * When the cookie expires.
  1537. *
  1538. * @since 2.8.0
  1539. * @var string
  1540. */
  1541. public $expires;
  1542. /**
  1543. * Cookie URL path.
  1544. *
  1545. * @since 2.8.0
  1546. * @var string
  1547. */
  1548. public $path;
  1549. /**
  1550. * Cookie Domain.
  1551. *
  1552. * @since 2.8.0
  1553. * @var string
  1554. */
  1555. public $domain;
  1556. /**
  1557. * Sets up this cookie object.
  1558. *
  1559. * The parameter $data should be either an associative array containing the indices names below
  1560. * or a header string detailing it.
  1561. *
  1562. * @since 2.8.0
  1563. * @access public
  1564. *
  1565. * @param string|array $data {
  1566. * Raw cookie data as header string or data array.
  1567. *
  1568. * @type string $name Cookie name.
  1569. * @type mixed $value Value. Should NOT already be urlencoded.
  1570. * @type string|int $expires Optional. Unix timestamp or formatted date. Default null.
  1571. * @type string $path Optional. Path. Default '/'.
  1572. * @type string $domain Optional. Domain. Default host of parsed $requested_url.
  1573. * @type int $port Optional. Port. Default null.
  1574. * }
  1575. * @param string $requested_url The URL which the cookie was set on, used for default $domain
  1576. * and $port values.
  1577. */
  1578. public function __construct( $data, $requested_url = '' ) {
  1579. if ( $requested_url )
  1580. $arrURL = @parse_url( $requested_url );
  1581. if ( isset( $arrURL['host'] ) )
  1582. $this->domain = $arrURL['host'];
  1583. $this->path = isset( $arrURL['path'] ) ? $arrURL['path'] : '/';
  1584. if ( '/' != substr( $this->path, -1 ) )
  1585. $this->path = dirname( $this->path ) . '/';
  1586. if ( is_string( $data ) ) {
  1587. // Assume it's a header string direct from a previous request.
  1588. $pairs = explode( ';', $data );
  1589. // Special handling for first pair; name=value. Also be careful of "=" in value.
  1590. $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
  1591. $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
  1592. $this->name = $name;
  1593. $this->value = urldecode( $value );
  1594. // Removes name=value from items.
  1595. array_shift( $pairs );
  1596. // Set everything else as a property.
  1597. foreach ( $pairs as $pair ) {
  1598. $pair = rtrim($pair);
  1599. // Handle the cookie ending in ; which results in a empty final pair.
  1600. if ( empty($pair) )
  1601. continue;
  1602. list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
  1603. $key = strtolower( trim( $key ) );
  1604. if ( 'expires' == $key )
  1605. $val = strtotime( $val );
  1606. $this->$key = $val;
  1607. }
  1608. } else {
  1609. if ( !isset( $data['name'] ) )
  1610. return false;
  1611. // Set properties based directly on parameters.
  1612. foreach ( array( 'name', 'value', 'path', 'domain', 'port' ) as $field ) {
  1613. if ( isset( $data[ $field ] ) )
  1614. $this->$field = $data[ $field ];
  1615. }
  1616. if ( isset( $data['expires'] ) )
  1617. $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
  1618. else
  1619. $this->expires = null;
  1620. }
  1621. }
  1622. /**
  1623. * Confirms that it's OK to send this cookie to the URL checked against.
  1624. *
  1625. * Decision is based on RFC 2109/2965, so look there for details on validity.
  1626. *
  1627. * @access public
  1628. * @since 2.8.0
  1629. *
  1630. * @param string $url URL you intend to send this cookie to
  1631. * @return boolean true if allowed, false otherwise.
  1632. */
  1633. public function test( $url ) {
  1634. if ( is_null( $this->name ) )
  1635. return false;
  1636. // Expires - if expired then nothing else matters.
  1637. if ( isset( $this->expires ) && time() > $this->expires )
  1638. return false;
  1639. // Get details on the URL we're thinking about sending to.
  1640. $url = parse_url( $url );
  1641. $url['port'] = isset( $url['port'] ) ? $url['port'] : ( 'https' == $url['scheme'] ? 443 : 80 );
  1642. $url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
  1643. // Values to use for comparison against the URL.
  1644. $path = isset( $this->path ) ? $this->path : '/';
  1645. $port = isset( $this->port ) ? $this->port : null;
  1646. $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
  1647. if ( false === stripos( $domain, '.' ) )
  1648. $domain .= '.local';
  1649. // Host - very basic check that the request URL ends with the domain restriction (minus leading dot).
  1650. $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
  1651. if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
  1652. return false;
  1653. // Port - supports "port-lists" in the format: "80,8000,8080".
  1654. if ( !empty( $port ) && !in_array( $url['port'], explode( ',', $port) ) )
  1655. return false;
  1656. // Path - request path must start with path restriction.
  1657. if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
  1658. return false;
  1659. return true;
  1660. }
  1661. /**
  1662. * Convert cookie name and value back to header string.
  1663. *
  1664. * @access public
  1665. * @since 2.8.0
  1666. *
  1667. * @return string Header encoded cookie name and value.
  1668. */
  1669. public function getHeaderValue() {
  1670. if ( ! isset( $this->name ) || ! isset( $this->value ) )
  1671. return '';
  1672. /**
  1673. * Filter the header-encoded cookie value.
  1674. *
  1675. * @since 3.4.0
  1676. *
  1677. * @param string $value The cookie value.
  1678. * @param string $name The cookie name.
  1679. */
  1680. return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name );
  1681. }
  1682. /**
  1683. * Retrieve cookie header for usage in the rest of the WordPress HTTP API.
  1684. *
  1685. * @access public
  1686. * @since 2.8.0
  1687. *
  1688. * @return string
  1689. */
  1690. public function getFullHeader() {
  1691. return 'Cookie: ' . $this->getHeaderValue();
  1692. }
  1693. }
  1694. /**
  1695. * Implementation for deflate and gzip transfer encodings.
  1696. *
  1697. * Includes RFC 1950, RFC 1951, and RFC 1952.
  1698. *
  1699. * @since 2.8.0
  1700. * @package WordPress
  1701. * @subpackage HTTP
  1702. */
  1703. class WP_Http_Encoding {
  1704. /**
  1705. * Compress raw string using the deflate format.
  1706. *
  1707. * Supports the RFC 1951 standard.
  1708. *
  1709. * @since 2.8.0
  1710. *
  1711. * @param string $raw String to compress.
  1712. * @param int $level Optional, default is 9. Compression level, 9 is highest.
  1713. * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
  1714. * @return string|bool False on failure.
  1715. */
  1716. public static function compress( $raw, $level = 9, $supports = null ) {
  1717. return gzdeflate( $raw, $level );
  1718. }
  1719. /**
  1720. * Decompression of deflated string.
  1721. *
  1722. * Will attempt to decompress using the RFC 1950 standard, and if that fails
  1723. * then the RFC 1951 standard deflate will be attempted. Finally, the RFC
  1724. * 1952 standard gzip decode will be attempted. If all fail, then the
  1725. * original compressed string will be returned.
  1726. *
  1727. * @since 2.8.0
  1728. *
  1729. * @param string $compressed String to decompress.
  1730. * @param int $length The optional length of the compressed data.
  1731. * @return string|bool False on failure.
  1732. */
  1733. public static function decompress( $compressed, $length = null ) {
  1734. if ( empty($compressed) )
  1735. return $compressed;
  1736. if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
  1737. return $decompressed;
  1738. if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
  1739. return $decompressed;
  1740. if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
  1741. return $decompressed;
  1742. if ( function_exists('gzdecode') ) {
  1743. $decompressed = @gzdecode( $compressed );
  1744. if ( false !== $decompressed )
  1745. return $decompressed;
  1746. }
  1747. return $compressed;
  1748. }
  1749. /**
  1750. * Decompression of deflated string while staying compatible with the majority of servers.
  1751. *
  1752. * Certain Servers will return deflated data with headers which PHP's gzinflate()
  1753. * function cannot handle out of the box. The following function has been created from
  1754. * various snippets on the gzinflate() PHP documentation.
  1755. *
  1756. * Warning: Magic numbers within. Due to the potential different formats that the compressed
  1757. * data may be returned in, some "magic offsets" are needed to ensure proper decompression
  1758. * takes place. For a simple progmatic way to determine the magic offset in use, see:
  1759. * http://core.trac.wordpress.org/ticket/18273
  1760. *
  1761. * @since 2.8.1
  1762. * @link http://core.trac.wordpress.org/ticket/18273
  1763. * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
  1764. * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
  1765. *
  1766. * @param string $gzData String to decompress.
  1767. * @return string|bool False on failure.
  1768. */
  1769. public static function compatible_gzinflate($gzData) {
  1770. // Compressed data might contain a full header, if so strip it for gzinflate().
  1771. if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
  1772. $i = 10;
  1773. $flg = ord( substr($gzData, 3, 1) );
  1774. if ( $flg > 0 ) {
  1775. if ( $flg & 4 ) {
  1776. list($xlen) = unpack('v', substr($gzData, $i, 2) );
  1777. $i = $i + 2 + $xlen;
  1778. }
  1779. if ( $flg & 8 )
  1780. $i = strpos($gzData, "\0", $i) + 1;
  1781. if ( $flg & 16 )
  1782. $i = strpos($gzData, "\0", $i) + 1;
  1783. if ( $flg & 2 )
  1784. $i = $i + 2;
  1785. }
  1786. $decompressed = @gzinflate( substr($gzData, $i, -8) );
  1787. if ( false !== $decompressed )
  1788. return $decompressed;
  1789. }
  1790. // Compressed data from java.util.zip.Deflater amongst others.
  1791. $decompressed = @gzinflate( substr($gzData, 2) );
  1792. if ( false !== $decompressed )
  1793. return $decompressed;
  1794. return false;
  1795. }
  1796. /**
  1797. * What encoding types to accept and their priority values.
  1798. *
  1799. * @since 2.8.0
  1800. *
  1801. * @return string Types of encoding to accept.
  1802. */
  1803. public static function accept_encoding( $url, $args ) {
  1804. $type = array();
  1805. $compression_enabled = WP_Http_Encoding::is_available();
  1806. if ( ! $args['decompress'] ) // Decompression specifically disabled.
  1807. $compression_enabled = false;
  1808. elseif ( $args['stream'] ) // Disable when streaming to file.
  1809. $compression_enabled = false;
  1810. elseif ( isset( $args['limit_response_size'] ) ) // If only partial content is being requested, we won't be able to decompress it.
  1811. $compression_enabled = false;
  1812. if ( $compression_enabled ) {
  1813. if ( function_exists( 'gzinflate' ) )
  1814. $type[] = 'deflate;q=1.0';
  1815. if ( function_exists( 'gzuncompress' ) )
  1816. $type[] = 'compress;q=0.5';
  1817. if ( function_exists( 'gzdecode' ) )
  1818. $type[] = 'gzip;q=0.5';
  1819. }
  1820. /**
  1821. * Filter the allowed encoding types.
  1822. *
  1823. * @since 3.6.0
  1824. *
  1825. * @param array $type Encoding types allowed. Accepts 'gzinflate',
  1826. * 'gzuncompress', 'gzdecode'.
  1827. * @param string $url URL of the HTTP request.
  1828. * @param array $args HTTP request arguments.
  1829. */
  1830. $type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
  1831. return implode(', ', $type);
  1832. }
  1833. /**
  1834. * What encoding the content used when it was compressed to send in the headers.
  1835. *
  1836. * @since 2.8.0
  1837. *
  1838. * @return string Content-Encoding string to send in the header.
  1839. */
  1840. public static function content_encoding() {
  1841. return 'deflate';
  1842. }
  1843. /**
  1844. * Whether the content be decoded based on the headers.
  1845. *
  1846. * @since 2.8.0
  1847. *
  1848. * @param array|string $headers All of the available headers.
  1849. * @return bool
  1850. */
  1851. public static function should_decode($headers) {
  1852. if ( is_array( $headers ) ) {
  1853. if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
  1854. return true;
  1855. } else if ( is_string( $headers ) ) {
  1856. return ( stripos($headers, 'content-encoding:') !== false );
  1857. }
  1858. return false;
  1859. }
  1860. /**
  1861. * Whether decompression and compression are supported by the PHP version.
  1862. *
  1863. * Each function is tested instead of checking for the zlib extension, to
  1864. * ensure that the functions all exist in the PHP version and aren't
  1865. * disabled.
  1866. *
  1867. * @since 2.8.0
  1868. *
  1869. * @return bool
  1870. */
  1871. public static function is_available() {
  1872. return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
  1873. }
  1874. }