WP_Http

Core class used for managing HTTP transports and making HTTP requests.

Defined (1)

The class is defined in the following location(s).

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