Нет описания

class-http.php 39KB

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