PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/class-http.php

https://gitlab.com/webkod3r/tripolis
PHP | 921 lines | 381 code | 115 blank | 425 comment | 110 complexity | 4e595dfa07645e995a12e69334257171 MD5 | raw file
  1. <?php
  2. /**
  3. * HTTP API: WP_Http class
  4. *
  5. * @package WordPress
  6. * @subpackage HTTP
  7. * @since 2.7.0
  8. */
  9. /**
  10. * Core class used for managing HTTP transports and making HTTP requests.
  11. *
  12. * This class is used to consistently make outgoing HTTP requests easy for developers
  13. * while still being compatible with the many PHP configurations under which
  14. * WordPress runs.
  15. *
  16. * Debugging includes several actions, which pass different variables for debugging the HTTP API.
  17. *
  18. * @since 2.7.0
  19. */
  20. class WP_Http {
  21. // Aliases for HTTP response codes.
  22. const HTTP_CONTINUE = 100;
  23. const SWITCHING_PROTOCOLS = 101;
  24. const PROCESSING = 102;
  25. const OK = 200;
  26. const CREATED = 201;
  27. const ACCEPTED = 202;
  28. const NON_AUTHORITATIVE_INFORMATION = 203;
  29. const NO_CONTENT = 204;
  30. const RESET_CONTENT = 205;
  31. const PARTIAL_CONTENT = 206;
  32. const MULTI_STATUS = 207;
  33. const IM_USED = 226;
  34. const MULTIPLE_CHOICES = 300;
  35. const MOVED_PERMANENTLY = 301;
  36. const FOUND = 302;
  37. const SEE_OTHER = 303;
  38. const NOT_MODIFIED = 304;
  39. const USE_PROXY = 305;
  40. const RESERVED = 306;
  41. const TEMPORARY_REDIRECT = 307;
  42. const PERMANENT_REDIRECT = 308;
  43. const BAD_REQUEST = 400;
  44. const UNAUTHORIZED = 401;
  45. const PAYMENT_REQUIRED = 402;
  46. const FORBIDDEN = 403;
  47. const NOT_FOUND = 404;
  48. const METHOD_NOT_ALLOWED = 405;
  49. const NOT_ACCEPTABLE = 406;
  50. const PROXY_AUTHENTICATION_REQUIRED = 407;
  51. const REQUEST_TIMEOUT = 408;
  52. const CONFLICT = 409;
  53. const GONE = 410;
  54. const LENGTH_REQUIRED = 411;
  55. const PRECONDITION_FAILED = 412;
  56. const REQUEST_ENTITY_TOO_LARGE = 413;
  57. const REQUEST_URI_TOO_LONG = 414;
  58. const UNSUPPORTED_MEDIA_TYPE = 415;
  59. const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
  60. const EXPECTATION_FAILED = 417;
  61. const IM_A_TEAPOT = 418;
  62. const MISDIRECTED_REQUEST = 421;
  63. const UNPROCESSABLE_ENTITY = 422;
  64. const LOCKED = 423;
  65. const FAILED_DEPENDENCY = 424;
  66. const UPGRADE_REQUIRED = 426;
  67. const PRECONDITION_REQUIRED = 428;
  68. const TOO_MANY_REQUESTS = 429;
  69. const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
  70. const UNAVAILABLE_FOR_LEGAL_REASONS = 451;
  71. const INTERNAL_SERVER_ERROR = 500;
  72. const NOT_IMPLEMENTED = 501;
  73. const BAD_GATEWAY = 502;
  74. const SERVICE_UNAVAILABLE = 503;
  75. const GATEWAY_TIMEOUT = 504;
  76. const HTTP_VERSION_NOT_SUPPORTED = 505;
  77. const VARIANT_ALSO_NEGOTIATES = 506;
  78. const INSUFFICIENT_STORAGE = 507;
  79. const NOT_EXTENDED = 510;
  80. const NETWORK_AUTHENTICATION_REQUIRED = 511;
  81. /**
  82. * Send an HTTP request to a URI.
  83. *
  84. * Please note: The only URI that are supported in the HTTP Transport implementation
  85. * are the HTTP and HTTPS protocols.
  86. *
  87. * @access public
  88. * @since 2.7.0
  89. *
  90. * @global string $wp_version
  91. *
  92. * @param string $url The request URL.
  93. * @param string|array $args {
  94. * Optional. Array or string of HTTP request arguments.
  95. *
  96. * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
  97. * Some transports technically allow others, but should not be
  98. * assumed. Default 'GET'.
  99. * @type int $timeout How long the connection should stay open in seconds. Default 5.
  100. * @type int $redirection Number of allowed redirects. Not supported by all transports
  101. * Default 5.
  102. * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
  103. * Default '1.0'.
  104. * @type string $user-agent User-agent value sent.
  105. * Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
  106. * @type bool $reject_unsafe_urls Whether to pass URLs through {@see wp_http_validate_url()}.
  107. * Default false.
  108. * @type bool $blocking Whether the calling code requires the result of the request.
  109. * If set to false, the request will be sent to the remote server,
  110. * and processing returned to the calling code immediately, the caller
  111. * will know if the request succeeded or failed, but will not receive
  112. * any response from the remote server. Default true.
  113. * @type string|array $headers Array or string of headers to send with the request.
  114. * Default empty array.
  115. * @type array $cookies List of cookies to send with the request. Default empty array.
  116. * @type string|array $body Body to send with the request. Default null.
  117. * @type bool $compress Whether to compress the $body when sending the request.
  118. * Default false.
  119. * @type bool $decompress Whether to decompress a compressed response. If set to false and
  120. * compressed content is returned in the response anyway, it will
  121. * need to be separately decompressed. Default true.
  122. * @type bool $sslverify Whether to verify SSL for the request. Default true.
  123. * @type string sslcertificates Absolute path to an SSL certificate .crt file.
  124. * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
  125. * @type bool $stream Whether to stream to a file. If set to true and no filename was
  126. * given, it will be droped it in the WP temp dir and its name will
  127. * be set using the basename of the URL. Default false.
  128. * @type string $filename Filename of the file to write to when streaming. $stream must be
  129. * set to true. Default null.
  130. * @type int $limit_response_size Size in bytes to limit the response to. Default null.
  131. *
  132. * }
  133. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  134. * A WP_Error instance upon error.
  135. */
  136. public function request( $url, $args = array() ) {
  137. global $wp_version;
  138. $defaults = array(
  139. 'method' => 'GET',
  140. /**
  141. * Filter the timeout value for an HTTP request.
  142. *
  143. * @since 2.7.0
  144. *
  145. * @param int $timeout_value Time in seconds until a request times out.
  146. * Default 5.
  147. */
  148. 'timeout' => apply_filters( 'http_request_timeout', 5 ),
  149. /**
  150. * Filter the number of redirects allowed during an HTTP request.
  151. *
  152. * @since 2.7.0
  153. *
  154. * @param int $redirect_count Number of redirects allowed. Default 5.
  155. */
  156. 'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
  157. /**
  158. * Filter the version of the HTTP protocol used in a request.
  159. *
  160. * @since 2.7.0
  161. *
  162. * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
  163. * Default '1.0'.
  164. */
  165. 'httpversion' => apply_filters( 'http_request_version', '1.0' ),
  166. /**
  167. * Filter the user agent value sent with an HTTP request.
  168. *
  169. * @since 2.7.0
  170. *
  171. * @param string $user_agent WordPress user agent string.
  172. */
  173. 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
  174. /**
  175. * Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
  176. *
  177. * @since 3.6.0
  178. *
  179. * @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
  180. * Default false.
  181. */
  182. 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
  183. 'blocking' => true,
  184. 'headers' => array(),
  185. 'cookies' => array(),
  186. 'body' => null,
  187. 'compress' => false,
  188. 'decompress' => true,
  189. 'sslverify' => true,
  190. 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
  191. 'stream' => false,
  192. 'filename' => null,
  193. 'limit_response_size' => null,
  194. );
  195. // Pre-parse for the HEAD checks.
  196. $args = wp_parse_args( $args );
  197. // By default, Head requests do not cause redirections.
  198. if ( isset($args['method']) && 'HEAD' == $args['method'] )
  199. $defaults['redirection'] = 0;
  200. $r = wp_parse_args( $args, $defaults );
  201. /**
  202. * Filter the arguments used in an HTTP request.
  203. *
  204. * @since 2.7.0
  205. *
  206. * @param array $r An array of HTTP request arguments.
  207. * @param string $url The request URL.
  208. */
  209. $r = apply_filters( 'http_request_args', $r, $url );
  210. // The transports decrement this, store a copy of the original value for loop purposes.
  211. if ( ! isset( $r['_redirection'] ) )
  212. $r['_redirection'] = $r['redirection'];
  213. /**
  214. * Filter whether to preempt an HTTP request's return value.
  215. *
  216. * Returning a non-false value from the filter will short-circuit the HTTP request and return
  217. * early with that value. A filter should return either:
  218. *
  219. * - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
  220. * - A WP_Error instance
  221. * - boolean false (to avoid short-circuiting the response)
  222. *
  223. * Returning any other value may result in unexpected behaviour.
  224. *
  225. * @since 2.9.0
  226. *
  227. * @param false|array|WP_Error $preempt Whether to preempt an HTTP request's return value. Default false.
  228. * @param array $r HTTP request arguments.
  229. * @param string $url The request URL.
  230. */
  231. $pre = apply_filters( 'pre_http_request', false, $r, $url );
  232. if ( false !== $pre )
  233. return $pre;
  234. if ( function_exists( 'wp_kses_bad_protocol' ) ) {
  235. if ( $r['reject_unsafe_urls'] )
  236. $url = wp_http_validate_url( $url );
  237. if ( $url ) {
  238. $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
  239. }
  240. }
  241. $arrURL = @parse_url( $url );
  242. if ( empty( $url ) || empty( $arrURL['scheme'] ) )
  243. return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
  244. if ( $this->block_request( $url ) )
  245. return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
  246. /*
  247. * Determine if this is a https call and pass that on to the transport functions
  248. * so that we can blacklist the transports that do not support ssl verification
  249. */
  250. $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
  251. // Determine if this request is to OUR install of WordPress.
  252. $homeURL = parse_url( get_bloginfo( 'url' ) );
  253. $r['local'] = 'localhost' == $arrURL['host'] || ( isset( $homeURL['host'] ) && $homeURL['host'] == $arrURL['host'] );
  254. unset( $homeURL );
  255. /*
  256. * If we are streaming to a file but no filename was given drop it in the WP temp dir
  257. * and pick its name using the basename of the $url.
  258. */
  259. if ( $r['stream'] && empty( $r['filename'] ) ) {
  260. $r['filename'] = get_temp_dir() . wp_unique_filename( get_temp_dir(), basename( $url ) );
  261. }
  262. /*
  263. * Force some settings if we are streaming to a file and check for existence and perms
  264. * of destination directory.
  265. */
  266. if ( $r['stream'] ) {
  267. $r['blocking'] = true;
  268. if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
  269. return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
  270. }
  271. if ( is_null( $r['headers'] ) )
  272. $r['headers'] = array();
  273. if ( ! is_array( $r['headers'] ) ) {
  274. $processedHeaders = self::processHeaders( $r['headers'], $url );
  275. $r['headers'] = $processedHeaders['headers'];
  276. }
  277. if ( isset( $r['headers']['User-Agent'] ) ) {
  278. $r['user-agent'] = $r['headers']['User-Agent'];
  279. unset( $r['headers']['User-Agent'] );
  280. }
  281. if ( isset( $r['headers']['user-agent'] ) ) {
  282. $r['user-agent'] = $r['headers']['user-agent'];
  283. unset( $r['headers']['user-agent'] );
  284. }
  285. if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
  286. $r['headers']['connection'] = 'close';
  287. }
  288. // Construct Cookie: header if any cookies are set.
  289. self::buildCookieHeader( $r );
  290. // Avoid issues where mbstring.func_overload is enabled.
  291. mbstring_binary_safe_encoding();
  292. if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
  293. if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
  294. $r['headers']['Accept-Encoding'] = $encoding;
  295. }
  296. if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
  297. if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
  298. $r['body'] = http_build_query( $r['body'], null, '&' );
  299. if ( ! isset( $r['headers']['Content-Type'] ) )
  300. $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
  301. }
  302. if ( '' === $r['body'] )
  303. $r['body'] = null;
  304. if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
  305. $r['headers']['Content-Length'] = strlen( $r['body'] );
  306. }
  307. $response = $this->_dispatch_request( $url, $r );
  308. reset_mbstring_encoding();
  309. if ( is_wp_error( $response ) )
  310. return $response;
  311. // Append cookies that were used in this request to the response
  312. if ( ! empty( $r['cookies'] ) ) {
  313. $cookies_set = wp_list_pluck( $response['cookies'], 'name' );
  314. foreach ( $r['cookies'] as $cookie ) {
  315. if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
  316. $response['cookies'][] = $cookie;
  317. }
  318. }
  319. }
  320. return $response;
  321. }
  322. /**
  323. * Tests which transports are capable of supporting the request.
  324. *
  325. * @since 3.2.0
  326. * @access public
  327. *
  328. * @param array $args Request arguments
  329. * @param string $url URL to Request
  330. *
  331. * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
  332. */
  333. public function _get_first_available_transport( $args, $url = null ) {
  334. $transports = array( 'curl', 'streams' );
  335. /**
  336. * Filter which HTTP transports are available and in what order.
  337. *
  338. * @since 3.7.0
  339. *
  340. * @param array $transports Array of HTTP transports to check. Default array contains
  341. * 'curl', and 'streams', in that order.
  342. * @param array $args HTTP request arguments.
  343. * @param string $url The URL to request.
  344. */
  345. $request_order = apply_filters( 'http_api_transports', $transports, $args, $url );
  346. // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
  347. foreach ( $request_order as $transport ) {
  348. if ( in_array( $transport, $transports ) ) {
  349. $transport = ucfirst( $transport );
  350. }
  351. $class = 'WP_Http_' . $transport;
  352. // Check to see if this transport is a possibility, calls the transport statically.
  353. if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
  354. continue;
  355. return $class;
  356. }
  357. return false;
  358. }
  359. /**
  360. * Dispatches a HTTP request to a supporting transport.
  361. *
  362. * Tests each transport in order to find a transport which matches the request arguments.
  363. * Also caches the transport instance to be used later.
  364. *
  365. * The order for requests is cURL, and then PHP Streams.
  366. *
  367. * @since 3.2.0
  368. *
  369. * @static
  370. * @access private
  371. *
  372. * @param string $url URL to Request
  373. * @param array $args Request arguments
  374. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  375. */
  376. private function _dispatch_request( $url, $args ) {
  377. static $transports = array();
  378. $class = $this->_get_first_available_transport( $args, $url );
  379. if ( !$class )
  380. return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
  381. // Transport claims to support request, instantiate it and give it a whirl.
  382. if ( empty( $transports[$class] ) )
  383. $transports[$class] = new $class;
  384. $response = $transports[$class]->request( $url, $args );
  385. /**
  386. * Fires after an HTTP API response is received and before the response is returned.
  387. *
  388. * @since 2.8.0
  389. *
  390. * @param array|WP_Error $response HTTP response or WP_Error object.
  391. * @param string $context Context under which the hook is fired.
  392. * @param string $class HTTP transport used.
  393. * @param array $args HTTP request arguments.
  394. * @param string $url The request URL.
  395. */
  396. do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
  397. if ( is_wp_error( $response ) )
  398. return $response;
  399. /**
  400. * Filter the HTTP API response immediately before the response is returned.
  401. *
  402. * @since 2.9.0
  403. *
  404. * @param array $response HTTP response.
  405. * @param array $args HTTP request arguments.
  406. * @param string $url The request URL.
  407. */
  408. return apply_filters( 'http_response', $response, $args, $url );
  409. }
  410. /**
  411. * Uses the POST HTTP method.
  412. *
  413. * Used for sending data that is expected to be in the body.
  414. *
  415. * @access public
  416. * @since 2.7.0
  417. *
  418. * @param string $url The request URL.
  419. * @param string|array $args Optional. Override the defaults.
  420. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  421. */
  422. public function post($url, $args = array()) {
  423. $defaults = array('method' => 'POST');
  424. $r = wp_parse_args( $args, $defaults );
  425. return $this->request($url, $r);
  426. }
  427. /**
  428. * Uses the GET HTTP method.
  429. *
  430. * Used for sending data that is expected to be in the body.
  431. *
  432. * @access public
  433. * @since 2.7.0
  434. *
  435. * @param string $url The request URL.
  436. * @param string|array $args Optional. Override the defaults.
  437. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  438. */
  439. public function get($url, $args = array()) {
  440. $defaults = array('method' => 'GET');
  441. $r = wp_parse_args( $args, $defaults );
  442. return $this->request($url, $r);
  443. }
  444. /**
  445. * Uses the HEAD HTTP method.
  446. *
  447. * Used for sending data that is expected to be in the body.
  448. *
  449. * @access public
  450. * @since 2.7.0
  451. *
  452. * @param string $url The request URL.
  453. * @param string|array $args Optional. Override the defaults.
  454. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  455. */
  456. public function head($url, $args = array()) {
  457. $defaults = array('method' => 'HEAD');
  458. $r = wp_parse_args( $args, $defaults );
  459. return $this->request($url, $r);
  460. }
  461. /**
  462. * Parses the responses and splits the parts into headers and body.
  463. *
  464. * @access public
  465. * @static
  466. * @since 2.7.0
  467. *
  468. * @param string $strResponse The full response string
  469. * @return array Array with 'headers' and 'body' keys.
  470. */
  471. public static function processResponse($strResponse) {
  472. $res = explode("\r\n\r\n", $strResponse, 2);
  473. return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
  474. }
  475. /**
  476. * Transform header string into an array.
  477. *
  478. * If an array is given then it is assumed to be raw header data with numeric keys with the
  479. * headers as the values. No headers must be passed that were already processed.
  480. *
  481. * @access public
  482. * @static
  483. * @since 2.7.0
  484. *
  485. * @param string|array $headers
  486. * @param string $url The URL that was requested
  487. * @return array Processed string headers. If duplicate headers are encountered,
  488. * Then a numbered array is returned as the value of that header-key.
  489. */
  490. public static function processHeaders( $headers, $url = '' ) {
  491. // Split headers, one per array element.
  492. if ( is_string($headers) ) {
  493. // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
  494. $headers = str_replace("\r\n", "\n", $headers);
  495. /*
  496. * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
  497. * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
  498. */
  499. $headers = preg_replace('/\n[ \t]/', ' ', $headers);
  500. // Create the headers array.
  501. $headers = explode("\n", $headers);
  502. }
  503. $response = array('code' => 0, 'message' => '');
  504. /*
  505. * If a redirection has taken place, The headers for each page request may have been passed.
  506. * In this case, determine the final HTTP header and parse from there.
  507. */
  508. for ( $i = count($headers)-1; $i >= 0; $i-- ) {
  509. if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
  510. $headers = array_splice($headers, $i);
  511. break;
  512. }
  513. }
  514. $cookies = array();
  515. $newheaders = array();
  516. foreach ( (array) $headers as $tempheader ) {
  517. if ( empty($tempheader) )
  518. continue;
  519. if ( false === strpos($tempheader, ':') ) {
  520. $stack = explode(' ', $tempheader, 3);
  521. $stack[] = '';
  522. list( , $response['code'], $response['message']) = $stack;
  523. continue;
  524. }
  525. list($key, $value) = explode(':', $tempheader, 2);
  526. $key = strtolower( $key );
  527. $value = trim( $value );
  528. if ( isset( $newheaders[ $key ] ) ) {
  529. if ( ! is_array( $newheaders[ $key ] ) )
  530. $newheaders[$key] = array( $newheaders[ $key ] );
  531. $newheaders[ $key ][] = $value;
  532. } else {
  533. $newheaders[ $key ] = $value;
  534. }
  535. if ( 'set-cookie' == $key )
  536. $cookies[] = new WP_Http_Cookie( $value, $url );
  537. }
  538. // Cast the Response Code to an int
  539. $response['code'] = intval( $response['code'] );
  540. return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
  541. }
  542. /**
  543. * Takes the arguments for a ::request() and checks for the cookie array.
  544. *
  545. * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
  546. * which are each parsed into strings and added to the Cookie: header (within the arguments array).
  547. * Edits the array by reference.
  548. *
  549. * @access public
  550. * @version 2.8.0
  551. * @static
  552. *
  553. * @param array $r Full array of args passed into ::request()
  554. */
  555. public static function buildCookieHeader( &$r ) {
  556. if ( ! empty($r['cookies']) ) {
  557. // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
  558. foreach ( $r['cookies'] as $name => $value ) {
  559. if ( ! is_object( $value ) )
  560. $r['cookies'][ $name ] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
  561. }
  562. $cookies_header = '';
  563. foreach ( (array) $r['cookies'] as $cookie ) {
  564. $cookies_header .= $cookie->getHeaderValue() . '; ';
  565. }
  566. $cookies_header = substr( $cookies_header, 0, -2 );
  567. $r['headers']['cookie'] = $cookies_header;
  568. }
  569. }
  570. /**
  571. * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
  572. *
  573. * Based off the HTTP http_encoding_dechunk function.
  574. *
  575. * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
  576. *
  577. * @access public
  578. * @since 2.7.0
  579. * @static
  580. *
  581. * @param string $body Body content
  582. * @return string Chunked decoded body on success or raw body on failure.
  583. */
  584. public static function chunkTransferDecode( $body ) {
  585. // The body is not chunked encoded or is malformed.
  586. if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
  587. return $body;
  588. $parsed_body = '';
  589. // We'll be altering $body, so need a backup in case of error.
  590. $body_original = $body;
  591. while ( true ) {
  592. $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
  593. if ( ! $has_chunk || empty( $match[1] ) )
  594. return $body_original;
  595. $length = hexdec( $match[1] );
  596. $chunk_length = strlen( $match[0] );
  597. // Parse out the chunk of data.
  598. $parsed_body .= substr( $body, $chunk_length, $length );
  599. // Remove the chunk from the raw data.
  600. $body = substr( $body, $length + $chunk_length );
  601. // End of the document.
  602. if ( '0' === trim( $body ) )
  603. return $parsed_body;
  604. }
  605. }
  606. /**
  607. * Block requests through the proxy.
  608. *
  609. * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
  610. * prevent plugins from working and core functionality, if you don't include api.wordpress.org.
  611. *
  612. * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
  613. * file and this will only allow localhost and your site to make requests. The constant
  614. * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
  615. * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
  616. * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
  617. *
  618. * @since 2.8.0
  619. * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
  620. * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
  621. *
  622. * @staticvar array|null $accessible_hosts
  623. * @staticvar array $wildcard_regex
  624. *
  625. * @param string $uri URI of url.
  626. * @return bool True to block, false to allow.
  627. */
  628. public function block_request($uri) {
  629. // We don't need to block requests, because nothing is blocked.
  630. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
  631. return false;
  632. $check = parse_url($uri);
  633. if ( ! $check )
  634. return true;
  635. $home = parse_url( get_option('siteurl') );
  636. // Don't block requests back to ourselves by default.
  637. if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
  638. /**
  639. * Filter whether to block local requests through the proxy.
  640. *
  641. * @since 2.8.0
  642. *
  643. * @param bool $block Whether to block local requests through proxy.
  644. * Default false.
  645. */
  646. return apply_filters( 'block_local_requests', false );
  647. }
  648. if ( !defined('WP_ACCESSIBLE_HOSTS') )
  649. return true;
  650. static $accessible_hosts = null;
  651. static $wildcard_regex = array();
  652. if ( null === $accessible_hosts ) {
  653. $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
  654. if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
  655. $wildcard_regex = array();
  656. foreach ( $accessible_hosts as $host )
  657. $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
  658. $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
  659. }
  660. }
  661. if ( !empty($wildcard_regex) )
  662. return !preg_match($wildcard_regex, $check['host']);
  663. else
  664. return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
  665. }
  666. /**
  667. * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
  668. *
  669. * @access protected
  670. * @deprecated 4.4.0 Use wp_parse_url()
  671. * @see wp_parse_url()
  672. *
  673. * @param string $url The URL to parse.
  674. * @return bool|array False on failure; Array of URL components on success;
  675. * See parse_url()'s return values.
  676. */
  677. protected static function parse_url( $url ) {
  678. _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
  679. return wp_parse_url( $url );
  680. }
  681. /**
  682. * Converts a relative URL to an absolute URL relative to a given URL.
  683. *
  684. * If an Absolute URL is provided, no processing of that URL is done.
  685. *
  686. * @since 3.4.0
  687. *
  688. * @static
  689. * @access public
  690. *
  691. * @param string $maybe_relative_path The URL which might be relative
  692. * @param string $url The URL which $maybe_relative_path is relative to
  693. * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
  694. */
  695. public static function make_absolute_url( $maybe_relative_path, $url ) {
  696. if ( empty( $url ) )
  697. return $maybe_relative_path;
  698. if ( ! $url_parts = wp_parse_url( $url ) ) {
  699. return $maybe_relative_path;
  700. }
  701. if ( ! $relative_url_parts = wp_parse_url( $maybe_relative_path ) ) {
  702. return $maybe_relative_path;
  703. }
  704. // Check for a scheme on the 'relative' url
  705. if ( ! empty( $relative_url_parts['scheme'] ) ) {
  706. return $maybe_relative_path;
  707. }
  708. $absolute_path = $url_parts['scheme'] . '://';
  709. // 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
  710. if ( isset( $relative_url_parts['host'] ) ) {
  711. $absolute_path .= $relative_url_parts['host'];
  712. if ( isset( $relative_url_parts['port'] ) )
  713. $absolute_path .= ':' . $relative_url_parts['port'];
  714. } else {
  715. $absolute_path .= $url_parts['host'];
  716. if ( isset( $url_parts['port'] ) )
  717. $absolute_path .= ':' . $url_parts['port'];
  718. }
  719. // Start off with the Absolute URL path.
  720. $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
  721. // If it's a root-relative path, then great.
  722. if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
  723. $path = $relative_url_parts['path'];
  724. // Else it's a relative path.
  725. } elseif ( ! empty( $relative_url_parts['path'] ) ) {
  726. // Strip off any file components from the absolute path.
  727. $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
  728. // Build the new path.
  729. $path .= $relative_url_parts['path'];
  730. // Strip all /path/../ out of the path.
  731. while ( strpos( $path, '../' ) > 1 ) {
  732. $path = preg_replace( '![^/]+/\.\./!', '', $path );
  733. }
  734. // Strip any final leading ../ from the path.
  735. $path = preg_replace( '!^/(\.\./)+!', '', $path );
  736. }
  737. // Add the Query string.
  738. if ( ! empty( $relative_url_parts['query'] ) )
  739. $path .= '?' . $relative_url_parts['query'];
  740. return $absolute_path . '/' . ltrim( $path, '/' );
  741. }
  742. /**
  743. * Handles HTTP Redirects and follows them if appropriate.
  744. *
  745. * @since 3.7.0
  746. *
  747. * @static
  748. *
  749. * @param string $url The URL which was requested.
  750. * @param array $args The Arguments which were used to make the request.
  751. * @param array $response The Response of the HTTP request.
  752. * @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
  753. */
  754. public static function handle_redirects( $url, $args, $response ) {
  755. // If no redirects are present, or, redirects were not requested, perform no action.
  756. if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
  757. return false;
  758. // Only perform redirections on redirection http codes.
  759. if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
  760. return false;
  761. // Don't redirect if we've run out of redirects.
  762. if ( $args['redirection']-- <= 0 )
  763. return new WP_Error( 'http_request_failed', __('Too many redirects.') );
  764. $redirect_location = $response['headers']['location'];
  765. // If there were multiple Location headers, use the last header specified.
  766. if ( is_array( $redirect_location ) )
  767. $redirect_location = array_pop( $redirect_location );
  768. $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
  769. // POST requests should not POST to a redirected location.
  770. if ( 'POST' == $args['method'] ) {
  771. if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
  772. $args['method'] = 'GET';
  773. }
  774. // Include valid cookies in the redirect process.
  775. if ( ! empty( $response['cookies'] ) ) {
  776. foreach ( $response['cookies'] as $cookie ) {
  777. if ( $cookie->test( $redirect_location ) )
  778. $args['cookies'][] = $cookie;
  779. }
  780. }
  781. return wp_remote_request( $redirect_location, $args );
  782. }
  783. /**
  784. * Determines if a specified string represents an IP address or not.
  785. *
  786. * This function also detects the type of the IP address, returning either
  787. * '4' or '6' to represent a IPv4 and IPv6 address respectively.
  788. * This does not verify if the IP is a valid IP, only that it appears to be
  789. * an IP address.
  790. *
  791. * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex
  792. *
  793. * @since 3.7.0
  794. * @static
  795. *
  796. * @param string $maybe_ip A suspected IP address
  797. * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
  798. */
  799. public static function is_ip_address( $maybe_ip ) {
  800. if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
  801. return 4;
  802. 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, ' []' ) ) )
  803. return 6;
  804. return false;
  805. }
  806. }