/wp-includes/class-http.php

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