PageRenderTime 64ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/class-http.php

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