class-wp-http.php 39 KB

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