暂无描述

class-wp-http.php 39KB

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. 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 dropped 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. $parsed_url = parse_url( $url );
  256. if ( empty( $url ) || empty( $parsed_url['scheme'] ) ) {
  257. $response = new WP_Error( 'http_request_failed', __( 'A valid URL was not provided.' ) );
  258. /** This action is documented in wp-includes/class-wp-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-wp-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-wp-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. $processed_headers = WP_Http::processHeaders( $parsed_args['headers'] );
  290. $parsed_args['headers'] = $processed_headers['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 a successful 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. $attributes = array_filter(
  419. $value->get_attributes(),
  420. static function( $attr ) {
  421. return null !== $attr;
  422. }
  423. );
  424. $cookie_jar[ $value->name ] = new Requests_Cookie( $value->name, $value->value, $attributes, array( 'host-only' => $value->host_only ) );
  425. } elseif ( is_scalar( $value ) ) {
  426. $cookie_jar[ $name ] = new Requests_Cookie( $name, $value );
  427. }
  428. }
  429. return $cookie_jar;
  430. }
  431. /**
  432. * Match redirect behaviour to browser handling.
  433. *
  434. * Changes 302 redirects from POST to GET to match browser handling. Per
  435. * RFC 7231, user agents can deviate from the strict reading of the
  436. * specification for compatibility purposes.
  437. *
  438. * @since 4.6.0
  439. *
  440. * @param string $location URL to redirect to.
  441. * @param array $headers Headers for the redirect.
  442. * @param string|array $data Body to send with the request.
  443. * @param array $options Redirect request options.
  444. * @param Requests_Response $original Response object.
  445. */
  446. public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) {
  447. // Browser compatibility.
  448. if ( 302 === $original->status_code ) {
  449. $options['type'] = Requests::GET;
  450. }
  451. }
  452. /**
  453. * Validate redirected URLs.
  454. *
  455. * @since 4.7.5
  456. *
  457. * @throws Requests_Exception On unsuccessful URL validation.
  458. * @param string $location URL to redirect to.
  459. */
  460. public static function validate_redirects( $location ) {
  461. if ( ! wp_http_validate_url( $location ) ) {
  462. throw new Requests_Exception( __( 'A valid URL was not provided.' ), 'wp_http.redirect_failed_validation' );
  463. }
  464. }
  465. /**
  466. * Tests which transports are capable of supporting the request.
  467. *
  468. * @since 3.2.0
  469. *
  470. * @param array $args Request arguments.
  471. * @param string $url URL to request.
  472. * @return string|false Class name for the first transport that claims to support the request.
  473. * False if no transport claims to support the request.
  474. */
  475. public function _get_first_available_transport( $args, $url = null ) {
  476. $transports = array( 'curl', 'streams' );
  477. /**
  478. * Filters which HTTP transports are available and in what order.
  479. *
  480. * @since 3.7.0
  481. *
  482. * @param string[] $transports Array of HTTP transports to check. Default array contains
  483. * 'curl' and 'streams', in that order.
  484. * @param array $args HTTP request arguments.
  485. * @param string $url The URL to request.
  486. */
  487. $request_order = apply_filters( 'http_api_transports', $transports, $args, $url );
  488. // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
  489. foreach ( $request_order as $transport ) {
  490. if ( in_array( $transport, $transports, true ) ) {
  491. $transport = ucfirst( $transport );
  492. }
  493. $class = 'WP_Http_' . $transport;
  494. // Check to see if this transport is a possibility, calls the transport statically.
  495. if ( ! call_user_func( array( $class, 'test' ), $args, $url ) ) {
  496. continue;
  497. }
  498. return $class;
  499. }
  500. return false;
  501. }
  502. /**
  503. * Dispatches a HTTP request to a supporting transport.
  504. *
  505. * Tests each transport in order to find a transport which matches the request arguments.
  506. * Also caches the transport instance to be used later.
  507. *
  508. * The order for requests is cURL, and then PHP Streams.
  509. *
  510. * @since 3.2.0
  511. * @deprecated 5.1.0 Use WP_Http::request()
  512. * @see WP_Http::request()
  513. *
  514. * @param string $url URL to request.
  515. * @param array $args Request arguments.
  516. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  517. * A WP_Error instance upon error.
  518. */
  519. private function _dispatch_request( $url, $args ) {
  520. static $transports = array();
  521. $class = $this->_get_first_available_transport( $args, $url );
  522. if ( ! $class ) {
  523. return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
  524. }
  525. // Transport claims to support request, instantiate it and give it a whirl.
  526. if ( empty( $transports[ $class ] ) ) {
  527. $transports[ $class ] = new $class;
  528. }
  529. $response = $transports[ $class ]->request( $url, $args );
  530. /** This action is documented in wp-includes/class-wp-http.php */
  531. do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
  532. if ( is_wp_error( $response ) ) {
  533. return $response;
  534. }
  535. /** This filter is documented in wp-includes/class-wp-http.php */
  536. return apply_filters( 'http_response', $response, $args, $url );
  537. }
  538. /**
  539. * Uses the POST HTTP method.
  540. *
  541. * Used for sending data that is expected to be in the body.
  542. *
  543. * @since 2.7.0
  544. *
  545. * @param string $url The request URL.
  546. * @param string|array $args Optional. Override the defaults.
  547. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  548. * A WP_Error instance upon error.
  549. */
  550. public function post( $url, $args = array() ) {
  551. $defaults = array( 'method' => 'POST' );
  552. $parsed_args = wp_parse_args( $args, $defaults );
  553. return $this->request( $url, $parsed_args );
  554. }
  555. /**
  556. * Uses the GET HTTP method.
  557. *
  558. * Used for sending data that is expected to be in the body.
  559. *
  560. * @since 2.7.0
  561. *
  562. * @param string $url The request URL.
  563. * @param string|array $args Optional. Override the defaults.
  564. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  565. * A WP_Error instance upon error.
  566. */
  567. public function get( $url, $args = array() ) {
  568. $defaults = array( 'method' => 'GET' );
  569. $parsed_args = wp_parse_args( $args, $defaults );
  570. return $this->request( $url, $parsed_args );
  571. }
  572. /**
  573. * Uses the HEAD HTTP method.
  574. *
  575. * Used for sending data that is expected to be in the body.
  576. *
  577. * @since 2.7.0
  578. *
  579. * @param string $url The request URL.
  580. * @param string|array $args Optional. Override the defaults.
  581. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  582. * A WP_Error instance upon error.
  583. */
  584. public function head( $url, $args = array() ) {
  585. $defaults = array( 'method' => 'HEAD' );
  586. $parsed_args = wp_parse_args( $args, $defaults );
  587. return $this->request( $url, $parsed_args );
  588. }
  589. /**
  590. * Parses the responses and splits the parts into headers and body.
  591. *
  592. * @since 2.7.0
  593. *
  594. * @param string $response The full response string.
  595. * @return array {
  596. * Array with response headers and body.
  597. *
  598. * @type string $headers HTTP response headers.
  599. * @type string $body HTTP response body.
  600. * }
  601. */
  602. public static function processResponse( $response ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  603. $response = explode( "\r\n\r\n", $response, 2 );
  604. return array(
  605. 'headers' => $response[0],
  606. 'body' => isset( $response[1] ) ? $response[1] : '',
  607. );
  608. }
  609. /**
  610. * Transforms header string into an array.
  611. *
  612. * @since 2.7.0
  613. *
  614. * @param string|array $headers The original headers. If a string is passed, it will be converted
  615. * to an array. If an array is passed, then it is assumed to be
  616. * raw header data with numeric keys with the headers as the values.
  617. * No headers must be passed that were already processed.
  618. * @param string $url Optional. The URL that was requested. Default empty.
  619. * @return array {
  620. * Processed string headers. If duplicate headers are encountered,
  621. * then a numbered array is returned as the value of that header-key.
  622. *
  623. * @type array $response {
  624. * @type int $code The response status code. Default 0.
  625. * @type string $message The response message. Default empty.
  626. * }
  627. * @type array $newheaders The processed header data as a multidimensional array.
  628. * @type WP_Http_Cookie[] $cookies If the original headers contain the 'Set-Cookie' key,
  629. * an array containing `WP_Http_Cookie` objects is returned.
  630. * }
  631. */
  632. public static function processHeaders( $headers, $url = '' ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  633. // Split headers, one per array element.
  634. if ( is_string( $headers ) ) {
  635. // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
  636. $headers = str_replace( "\r\n", "\n", $headers );
  637. /*
  638. * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
  639. * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
  640. */
  641. $headers = preg_replace( '/\n[ \t]/', ' ', $headers );
  642. // Create the headers array.
  643. $headers = explode( "\n", $headers );
  644. }
  645. $response = array(
  646. 'code' => 0,
  647. 'message' => '',
  648. );
  649. /*
  650. * If a redirection has taken place, The headers for each page request may have been passed.
  651. * In this case, determine the final HTTP header and parse from there.
  652. */
  653. for ( $i = count( $headers ) - 1; $i >= 0; $i-- ) {
  654. if ( ! empty( $headers[ $i ] ) && false === strpos( $headers[ $i ], ':' ) ) {
  655. $headers = array_splice( $headers, $i );
  656. break;
  657. }
  658. }
  659. $cookies = array();
  660. $newheaders = array();
  661. foreach ( (array) $headers as $tempheader ) {
  662. if ( empty( $tempheader ) ) {
  663. continue;
  664. }
  665. if ( false === strpos( $tempheader, ':' ) ) {
  666. $stack = explode( ' ', $tempheader, 3 );
  667. $stack[] = '';
  668. list( , $response['code'], $response['message']) = $stack;
  669. continue;
  670. }
  671. list($key, $value) = explode( ':', $tempheader, 2 );
  672. $key = strtolower( $key );
  673. $value = trim( $value );
  674. if ( isset( $newheaders[ $key ] ) ) {
  675. if ( ! is_array( $newheaders[ $key ] ) ) {
  676. $newheaders[ $key ] = array( $newheaders[ $key ] );
  677. }
  678. $newheaders[ $key ][] = $value;
  679. } else {
  680. $newheaders[ $key ] = $value;
  681. }
  682. if ( 'set-cookie' === $key ) {
  683. $cookies[] = new WP_Http_Cookie( $value, $url );
  684. }
  685. }
  686. // Cast the Response Code to an int.
  687. $response['code'] = (int) $response['code'];
  688. return array(
  689. 'response' => $response,
  690. 'headers' => $newheaders,
  691. 'cookies' => $cookies,
  692. );
  693. }
  694. /**
  695. * Takes the arguments for a ::request() and checks for the cookie array.
  696. *
  697. * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
  698. * which are each parsed into strings and added to the Cookie: header (within the arguments array).
  699. * Edits the array by reference.
  700. *
  701. * @since 2.8.0
  702. *
  703. * @param array $r Full array of args passed into ::request()
  704. */
  705. public static function buildCookieHeader( &$r ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  706. if ( ! empty( $r['cookies'] ) ) {
  707. // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
  708. foreach ( $r['cookies'] as $name => $value ) {
  709. if ( ! is_object( $value ) ) {
  710. $r['cookies'][ $name ] = new WP_Http_Cookie(
  711. array(
  712. 'name' => $name,
  713. 'value' => $value,
  714. )
  715. );
  716. }
  717. }
  718. $cookies_header = '';
  719. foreach ( (array) $r['cookies'] as $cookie ) {
  720. $cookies_header .= $cookie->getHeaderValue() . '; ';
  721. }
  722. $cookies_header = substr( $cookies_header, 0, -2 );
  723. $r['headers']['cookie'] = $cookies_header;
  724. }
  725. }
  726. /**
  727. * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
  728. *
  729. * Based off the HTTP http_encoding_dechunk function.
  730. *
  731. * @link https://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
  732. *
  733. * @since 2.7.0
  734. *
  735. * @param string $body Body content.
  736. * @return string Chunked decoded body on success or raw body on failure.
  737. */
  738. public static function chunkTransferDecode( $body ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  739. // The body is not chunked encoded or is malformed.
  740. if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) ) {
  741. return $body;
  742. }
  743. $parsed_body = '';
  744. // We'll be altering $body, so need a backup in case of error.
  745. $body_original = $body;
  746. while ( true ) {
  747. $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
  748. if ( ! $has_chunk || empty( $match[1] ) ) {
  749. return $body_original;
  750. }
  751. $length = hexdec( $match[1] );
  752. $chunk_length = strlen( $match[0] );
  753. // Parse out the chunk of data.
  754. $parsed_body .= substr( $body, $chunk_length, $length );
  755. // Remove the chunk from the raw data.
  756. $body = substr( $body, $length + $chunk_length );
  757. // End of the document.
  758. if ( '0' === trim( $body ) ) {
  759. return $parsed_body;
  760. }
  761. }
  762. }
  763. /**
  764. * Determines whether an HTTP API request to the given URL should be blocked.
  765. *
  766. * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
  767. * prevent plugins from working and core functionality, if you don't include `api.wordpress.org`.
  768. *
  769. * You block external URL requests by defining `WP_HTTP_BLOCK_EXTERNAL` as true in your `wp-config.php`
  770. * file and this will only allow localhost and your site to make requests. The constant
  771. * `WP_ACCESSIBLE_HOSTS` will allow additional hosts to go through for requests. The format of the
  772. * `WP_ACCESSIBLE_HOSTS` constant is a comma separated list of hostnames to allow, wildcard domains
  773. * are supported, eg `*.wordpress.org` will allow for all subdomains of `wordpress.org` to be contacted.
  774. *
  775. * @since 2.8.0
  776. *
  777. * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
  778. * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
  779. *
  780. * @param string $uri URI of url.
  781. * @return bool True to block, false to allow.
  782. */
  783. public function block_request( $uri ) {
  784. // We don't need to block requests, because nothing is blocked.
  785. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) {
  786. return false;
  787. }
  788. $check = parse_url( $uri );
  789. if ( ! $check ) {
  790. return true;
  791. }
  792. $home = parse_url( get_option( 'siteurl' ) );
  793. // Don't block requests back to ourselves by default.
  794. if ( 'localhost' === $check['host'] || ( isset( $home['host'] ) && $home['host'] === $check['host'] ) ) {
  795. /**
  796. * Filters whether to block local HTTP API requests.
  797. *
  798. * A local request is one to `localhost` or to the same host as the site itself.
  799. *
  800. * @since 2.8.0
  801. *
  802. * @param bool $block Whether to block local requests. Default false.
  803. */
  804. return apply_filters( 'block_local_requests', false );
  805. }
  806. if ( ! defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
  807. return true;
  808. }
  809. static $accessible_hosts = null;
  810. static $wildcard_regex = array();
  811. if ( null === $accessible_hosts ) {
  812. $accessible_hosts = preg_split( '|,\s*|', WP_ACCESSIBLE_HOSTS );
  813. if ( false !== strpos( WP_ACCESSIBLE_HOSTS, '*' ) ) {
  814. $wildcard_regex = array();
  815. foreach ( $accessible_hosts as $host ) {
  816. $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
  817. }
  818. $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
  819. }
  820. }
  821. if ( ! empty( $wildcard_regex ) ) {
  822. return ! preg_match( $wildcard_regex, $check['host'] );
  823. } else {
  824. return ! in_array( $check['host'], $accessible_hosts, true ); // Inverse logic, if it's in the array, then don't block it.
  825. }
  826. }
  827. /**
  828. * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
  829. *
  830. * @deprecated 4.4.0 Use wp_parse_url()
  831. * @see wp_parse_url()
  832. *
  833. * @param string $url The URL to parse.
  834. * @return bool|array False on failure; Array of URL components on success;
  835. * See parse_url()'s return values.
  836. */
  837. protected static function parse_url( $url ) {
  838. _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
  839. return wp_parse_url( $url );
  840. }
  841. /**
  842. * Converts a relative URL to an absolute URL relative to a given URL.
  843. *
  844. * If an Absolute URL is provided, no processing of that URL is done.
  845. *
  846. * @since 3.4.0
  847. *
  848. * @param string $maybe_relative_path The URL which might be relative.
  849. * @param string $url The URL which $maybe_relative_path is relative to.
  850. * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
  851. */
  852. public static function make_absolute_url( $maybe_relative_path, $url ) {
  853. if ( empty( $url ) ) {
  854. return $maybe_relative_path;
  855. }
  856. $url_parts = wp_parse_url( $url );
  857. if ( ! $url_parts ) {
  858. return $maybe_relative_path;
  859. }
  860. $relative_url_parts = wp_parse_url( $maybe_relative_path );
  861. if ( ! $relative_url_parts ) {
  862. return $maybe_relative_path;
  863. }
  864. // Check for a scheme on the 'relative' URL.
  865. if ( ! empty( $relative_url_parts['scheme'] ) ) {
  866. return $maybe_relative_path;
  867. }
  868. $absolute_path = $url_parts['scheme'] . '://';
  869. // Schemeless URLs will make it this far, so we check for a host in the relative URL
  870. // and convert it to a protocol-URL.
  871. if ( isset( $relative_url_parts['host'] ) ) {
  872. $absolute_path .= $relative_url_parts['host'];
  873. if ( isset( $relative_url_parts['port'] ) ) {
  874. $absolute_path .= ':' . $relative_url_parts['port'];
  875. }
  876. } else {
  877. $absolute_path .= $url_parts['host'];
  878. if ( isset( $url_parts['port'] ) ) {
  879. $absolute_path .= ':' . $url_parts['port'];
  880. }
  881. }
  882. // Start off with the absolute URL path.
  883. $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
  884. // If it's a root-relative path, then great.
  885. if ( ! empty( $relative_url_parts['path'] ) && '/' === $relative_url_parts['path'][0] ) {
  886. $path = $relative_url_parts['path'];
  887. // Else it's a relative path.
  888. } elseif ( ! empty( $relative_url_parts['path'] ) ) {
  889. // Strip off any file components from the absolute path.
  890. $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
  891. // Build the new path.
  892. $path .= $relative_url_parts['path'];
  893. // Strip all /path/../ out of the path.
  894. while ( strpos( $path, '../' ) > 1 ) {
  895. $path = preg_replace( '![^/]+/\.\./!', '', $path );
  896. }
  897. // Strip any final leading ../ from the path.
  898. $path = preg_replace( '!^/(\.\./)+!', '', $path );
  899. }
  900. // Add the query string.
  901. if ( ! empty( $relative_url_parts['query'] ) ) {
  902. $path .= '?' . $relative_url_parts['query'];
  903. }
  904. return $absolute_path . '/' . ltrim( $path, '/' );
  905. }
  906. /**
  907. * Handles an HTTP redirect and follows it if appropriate.
  908. *
  909. * @since 3.7.0
  910. *
  911. * @param string $url The URL which was requested.
  912. * @param array $args The arguments which were used to make the request.
  913. * @param array $response The response of the HTTP request.
  914. * @return array|false|WP_Error An HTTP API response array if the redirect is successfully followed,
  915. * false if no redirect is present, or a WP_Error object if there's an error.
  916. */
  917. public static function handle_redirects( $url, $args, $response ) {
  918. // If no redirects are present, or, redirects were not requested, perform no action.
  919. if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) {
  920. return false;
  921. }
  922. // Only perform redirections on redirection http codes.
  923. if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) {
  924. return false;
  925. }
  926. // Don't redirect if we've run out of redirects.
  927. if ( $args['redirection']-- <= 0 ) {
  928. return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
  929. }
  930. $redirect_location = $response['headers']['location'];
  931. // If there were multiple Location headers, use the last header specified.
  932. if ( is_array( $redirect_location ) ) {
  933. $redirect_location = array_pop( $redirect_location );
  934. }
  935. $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
  936. // POST requests should not POST to a redirected location.
  937. if ( 'POST' === $args['method'] ) {
  938. if ( in_array( $response['response']['code'], array( 302, 303 ), true ) ) {
  939. $args['method'] = 'GET';
  940. }
  941. }
  942. // Include valid cookies in the redirect process.
  943. if ( ! empty( $response['cookies'] ) ) {
  944. foreach ( $response['cookies'] as $cookie ) {
  945. if ( $cookie->test( $redirect_location ) ) {
  946. $args['cookies'][] = $cookie;
  947. }
  948. }
  949. }
  950. return wp_remote_request( $redirect_location, $args );
  951. }
  952. /**
  953. * Determines if a specified string represents an IP address or not.
  954. *
  955. * This function also detects the type of the IP address, returning either
  956. * '4' or '6' to represent a IPv4 and IPv6 address respectively.
  957. * This does not verify if the IP is a valid IP, only that it appears to be
  958. * an IP address.
  959. *
  960. * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex.
  961. *
  962. * @since 3.7.0
  963. *
  964. * @param string $maybe_ip A suspected IP address.
  965. * @return int|false Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
  966. */
  967. public static function is_ip_address( $maybe_ip ) {
  968. if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) ) {
  969. return 4;
  970. }
  971. 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, ' []' ) ) ) {
  972. return 6;
  973. }
  974. return false;
  975. }
  976. }