Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 

1019 wiersze
35 KiB

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