class-http.php 35 KB

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