class-http.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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 int $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 int $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 whether to preempt an HTTP request's return value.
  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 either:
  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 Whether to preempt an HTTP request's return value. 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 and perms of destination directory
  275. $parsed_args['blocking'] = true;
  276. if ( ! wp_is_writable( dirname( $parsed_args['filename'] ) ) ) {
  277. $response = new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
  278. /** This action is documented in wp-includes/class-http.php */
  279. do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url );
  280. return $response;
  281. }
  282. }
  283. if ( is_null( $parsed_args['headers'] ) ) {
  284. $parsed_args['headers'] = array();
  285. }
  286. // WP allows passing in headers as a string, weirdly.
  287. if ( ! is_array( $parsed_args['headers'] ) ) {
  288. $processedHeaders = WP_Http::processHeaders( $parsed_args['headers'] );
  289. $parsed_args['headers'] = $processedHeaders['headers'];
  290. }
  291. // Setup arguments
  292. $headers = $parsed_args['headers'];
  293. $data = $parsed_args['body'];
  294. $type = $parsed_args['method'];
  295. $options = array(
  296. 'timeout' => $parsed_args['timeout'],
  297. 'useragent' => $parsed_args['user-agent'],
  298. 'blocking' => $parsed_args['blocking'],
  299. 'hooks' => new WP_HTTP_Requests_Hooks( $url, $parsed_args ),
  300. );
  301. // Ensure redirects follow browser behaviour.
  302. $options['hooks']->register( 'requests.before_redirect', array( get_class(), 'browser_redirect_compatibility' ) );
  303. // Validate redirected URLs.
  304. if ( function_exists( 'wp_kses_bad_protocol' ) && $parsed_args['reject_unsafe_urls'] ) {
  305. $options['hooks']->register( 'requests.before_redirect', array( get_class(), 'validate_redirects' ) );
  306. }
  307. if ( $parsed_args['stream'] ) {
  308. $options['filename'] = $parsed_args['filename'];
  309. }
  310. if ( empty( $parsed_args['redirection'] ) ) {
  311. $options['follow_redirects'] = false;
  312. } else {
  313. $options['redirects'] = $parsed_args['redirection'];
  314. }
  315. // Use byte limit, if we can
  316. if ( isset( $parsed_args['limit_response_size'] ) ) {
  317. $options['max_bytes'] = $parsed_args['limit_response_size'];
  318. }
  319. // If we've got cookies, use and convert them to Requests_Cookie.
  320. if ( ! empty( $parsed_args['cookies'] ) ) {
  321. $options['cookies'] = WP_Http::normalize_cookies( $parsed_args['cookies'] );
  322. }
  323. // SSL certificate handling
  324. if ( ! $parsed_args['sslverify'] ) {
  325. $options['verify'] = false;
  326. $options['verifyname'] = false;
  327. } else {
  328. $options['verify'] = $parsed_args['sslcertificates'];
  329. }
  330. // All non-GET/HEAD requests should put the arguments in the form body.
  331. if ( 'HEAD' !== $type && 'GET' !== $type ) {
  332. $options['data_format'] = 'body';
  333. }
  334. /**
  335. * Filters whether SSL should be verified for non-local requests.
  336. *
  337. * @since 2.8.0
  338. * @since 5.1.0 The `$url` parameter was added.
  339. *
  340. * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
  341. * @param string $url The request URL.
  342. */
  343. $options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'], $url );
  344. // Check for proxies.
  345. $proxy = new WP_HTTP_Proxy();
  346. if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
  347. $options['proxy'] = new Requests_Proxy_HTTP( $proxy->host() . ':' . $proxy->port() );
  348. if ( $proxy->use_authentication() ) {
  349. $options['proxy']->use_authentication = true;
  350. $options['proxy']->user = $proxy->username();
  351. $options['proxy']->pass = $proxy->password();
  352. }
  353. }
  354. // Avoid issues where mbstring.func_overload is enabled
  355. mbstring_binary_safe_encoding();
  356. try {
  357. $requests_response = Requests::request( $url, $headers, $data, $type, $options );
  358. // Convert the response into an array
  359. $http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] );
  360. $response = $http_response->to_array();
  361. // Add the original object to the array.
  362. $response['http_response'] = $http_response;
  363. } catch ( Requests_Exception $e ) {
  364. $response = new WP_Error( 'http_request_failed', $e->getMessage() );
  365. }
  366. reset_mbstring_encoding();
  367. /**
  368. * Fires after an HTTP API response is received and before the response is returned.
  369. *
  370. * @since 2.8.0
  371. *
  372. * @param array|WP_Error $response HTTP response or WP_Error object.
  373. * @param string $context Context under which the hook is fired.
  374. * @param string $class HTTP transport used.
  375. * @param array $parsed_args HTTP request arguments.
  376. * @param string $url The request URL.
  377. */
  378. do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url );
  379. if ( is_wp_error( $response ) ) {
  380. return $response;
  381. }
  382. if ( ! $parsed_args['blocking'] ) {
  383. return array(
  384. 'headers' => array(),
  385. 'body' => '',
  386. 'response' => array(
  387. 'code' => false,
  388. 'message' => false,
  389. ),
  390. 'cookies' => array(),
  391. 'http_response' => null,
  392. );
  393. }
  394. /**
  395. * Filters the HTTP API response immediately before the response is returned.
  396. *
  397. * @since 2.9.0
  398. *
  399. * @param array $response HTTP response.
  400. * @param array $parsed_args HTTP request arguments.
  401. * @param string $url The request URL.
  402. */
  403. return apply_filters( 'http_response', $response, $parsed_args, $url );
  404. }
  405. /**
  406. * Normalizes cookies for using in Requests.
  407. *
  408. * @since 4.6.0
  409. *
  410. * @param array $cookies Array of cookies to send with the request.
  411. * @return Requests_Cookie_Jar Cookie holder object.
  412. */
  413. public static function normalize_cookies( $cookies ) {
  414. $cookie_jar = new Requests_Cookie_Jar();
  415. foreach ( $cookies as $name => $value ) {
  416. if ( $value instanceof WP_Http_Cookie ) {
  417. $cookie_jar[ $value->name ] = new Requests_Cookie( $value->name, $value->value, $value->get_attributes(), array( 'host-only' => $value->host_only ) );
  418. } elseif ( is_scalar( $value ) ) {
  419. $cookie_jar[ $name ] = new Requests_Cookie( $name, $value );
  420. }
  421. }
  422. return $cookie_jar;
  423. }
  424. /**
  425. * Match redirect behaviour to browser handling.
  426. *
  427. * Changes 302 redirects from POST to GET to match browser handling. Per
  428. * RFC 7231, user agents can deviate from the strict reading of the
  429. * specification for compatibility purposes.
  430. *
  431. * @since 4.6.0
  432. *
  433. * @param string $location URL to redirect to.
  434. * @param array $headers Headers for the redirect.
  435. * @param string|array $data Body to send with the request.
  436. * @param array $options Redirect request options.
  437. * @param Requests_Response $original Response object.
  438. */
  439. public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) {
  440. // Browser compat
  441. if ( $original->status_code === 302 ) {
  442. $options['type'] = Requests::GET;
  443. }
  444. }
  445. /**
  446. * Validate redirected URLs.
  447. *
  448. * @since 4.7.5
  449. *
  450. * @throws Requests_Exception On unsuccessful URL validation
  451. * @param string $location URL to redirect to.
  452. */
  453. public static function validate_redirects( $location ) {
  454. if ( ! wp_http_validate_url( $location ) ) {
  455. throw new Requests_Exception( __( 'A valid URL was not provided.' ), 'wp_http.redirect_failed_validation' );
  456. }
  457. }
  458. /**
  459. * Tests which transports are capable of supporting the request.
  460. *
  461. * @since 3.2.0
  462. *
  463. * @param array $args Request arguments
  464. * @param string $url URL to Request
  465. *
  466. * @return string|false Class name for the first transport that claims to support the request. False if no transport claims to support the request.
  467. */
  468. public function _get_first_available_transport( $args, $url = null ) {
  469. $transports = array( 'curl', 'streams' );
  470. /**
  471. * Filters which HTTP transports are available and in what order.
  472. *
  473. * @since 3.7.0
  474. *
  475. * @param array $transports Array of HTTP transports to check. Default array contains
  476. * 'curl', and 'streams', in that order.
  477. * @param array $args HTTP request arguments.
  478. * @param string $url The URL to request.
  479. */
  480. $request_order = apply_filters( 'http_api_transports', $transports, $args, $url );
  481. // Loop over each transport on each HTTP request looking for one which will serve this request's needs.
  482. foreach ( $request_order as $transport ) {
  483. if ( in_array( $transport, $transports ) ) {
  484. $transport = ucfirst( $transport );
  485. }
  486. $class = 'WP_Http_' . $transport;
  487. // Check to see if this transport is a possibility, calls the transport statically.
  488. if ( ! call_user_func( array( $class, 'test' ), $args, $url ) ) {
  489. continue;
  490. }
  491. return $class;
  492. }
  493. return false;
  494. }
  495. /**
  496. * Dispatches a HTTP request to a supporting transport.
  497. *
  498. * Tests each transport in order to find a transport which matches the request arguments.
  499. * Also caches the transport instance to be used later.
  500. *
  501. * The order for requests is cURL, and then PHP Streams.
  502. *
  503. * @since 3.2.0
  504. * @deprecated 5.1.0 Use WP_Http::request()
  505. * @see WP_Http::request()
  506. *
  507. * @param string $url URL to Request
  508. * @param array $args Request arguments
  509. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  510. */
  511. private function _dispatch_request( $url, $args ) {
  512. static $transports = array();
  513. $class = $this->_get_first_available_transport( $args, $url );
  514. if ( ! $class ) {
  515. return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
  516. }
  517. // Transport claims to support request, instantiate it and give it a whirl.
  518. if ( empty( $transports[ $class ] ) ) {
  519. $transports[ $class ] = new $class;
  520. }
  521. $response = $transports[ $class ]->request( $url, $args );
  522. /** This action is documented in wp-includes/class-http.php */
  523. do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
  524. if ( is_wp_error( $response ) ) {
  525. return $response;
  526. }
  527. /** This filter is documented in wp-includes/class-http.php */
  528. return apply_filters( 'http_response', $response, $args, $url );
  529. }
  530. /**
  531. * Uses the POST HTTP method.
  532. *
  533. * Used for sending data that is expected to be in the body.
  534. *
  535. * @since 2.7.0
  536. *
  537. * @param string $url The request URL.
  538. * @param string|array $args Optional. Override the defaults.
  539. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  540. */
  541. public function post( $url, $args = array() ) {
  542. $defaults = array( 'method' => 'POST' );
  543. $parsed_args = wp_parse_args( $args, $defaults );
  544. return $this->request( $url, $parsed_args );
  545. }
  546. /**
  547. * Uses the GET HTTP method.
  548. *
  549. * Used for sending data that is expected to be in the body.
  550. *
  551. * @since 2.7.0
  552. *
  553. * @param string $url The request URL.
  554. * @param string|array $args Optional. Override the defaults.
  555. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  556. */
  557. public function get( $url, $args = array() ) {
  558. $defaults = array( 'method' => 'GET' );
  559. $parsed_args = wp_parse_args( $args, $defaults );
  560. return $this->request( $url, $parsed_args );
  561. }
  562. /**
  563. * Uses the HEAD HTTP method.
  564. *
  565. * Used for sending data that is expected to be in the body.
  566. *
  567. * @since 2.7.0
  568. *
  569. * @param string $url The request URL.
  570. * @param string|array $args Optional. Override the defaults.
  571. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  572. */
  573. public function head( $url, $args = array() ) {
  574. $defaults = array( 'method' => 'HEAD' );
  575. $parsed_args = wp_parse_args( $args, $defaults );
  576. return $this->request( $url, $parsed_args );
  577. }
  578. /**
  579. * Parses the responses and splits the parts into headers and body.
  580. *
  581. * @since 2.7.0
  582. *
  583. * @param string $strResponse The full response string
  584. * @return array Array with 'headers' and 'body' keys.
  585. */
  586. public static function processResponse( $strResponse ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  587. $res = explode( "\r\n\r\n", $strResponse, 2 );
  588. return array(
  589. 'headers' => $res[0],
  590. 'body' => isset( $res[1] ) ? $res[1] : '',
  591. );
  592. }
  593. /**
  594. * Transform header string into an array.
  595. *
  596. * If an array is given then it is assumed to be raw header data with numeric keys with the
  597. * headers as the values. No headers must be passed that were already processed.
  598. *
  599. * @since 2.7.0
  600. *
  601. * @param string|array $headers
  602. * @param string $url The URL that was requested
  603. * @return array Processed string headers. If duplicate headers are encountered,
  604. * Then a numbered array is returned as the value of that header-key.
  605. */
  606. public static function processHeaders( $headers, $url = '' ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  607. // Split headers, one per array element.
  608. if ( is_string( $headers ) ) {
  609. // Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
  610. $headers = str_replace( "\r\n", "\n", $headers );
  611. /*
  612. * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
  613. * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
  614. */
  615. $headers = preg_replace( '/\n[ \t]/', ' ', $headers );
  616. // Create the headers array.
  617. $headers = explode( "\n", $headers );
  618. }
  619. $response = array(
  620. 'code' => 0,
  621. 'message' => '',
  622. );
  623. /*
  624. * If a redirection has taken place, The headers for each page request may have been passed.
  625. * In this case, determine the final HTTP header and parse from there.
  626. */
  627. for ( $i = count( $headers ) - 1; $i >= 0; $i-- ) {
  628. if ( ! empty( $headers[ $i ] ) && false === strpos( $headers[ $i ], ':' ) ) {
  629. $headers = array_splice( $headers, $i );
  630. break;
  631. }
  632. }
  633. $cookies = array();
  634. $newheaders = array();
  635. foreach ( (array) $headers as $tempheader ) {
  636. if ( empty( $tempheader ) ) {
  637. continue;
  638. }
  639. if ( false === strpos( $tempheader, ':' ) ) {
  640. $stack = explode( ' ', $tempheader, 3 );
  641. $stack[] = '';
  642. list( , $response['code'], $response['message']) = $stack;
  643. continue;
  644. }
  645. list($key, $value) = explode( ':', $tempheader, 2 );
  646. $key = strtolower( $key );
  647. $value = trim( $value );
  648. if ( isset( $newheaders[ $key ] ) ) {
  649. if ( ! is_array( $newheaders[ $key ] ) ) {
  650. $newheaders[ $key ] = array( $newheaders[ $key ] );
  651. }
  652. $newheaders[ $key ][] = $value;
  653. } else {
  654. $newheaders[ $key ] = $value;
  655. }
  656. if ( 'set-cookie' == $key ) {
  657. $cookies[] = new WP_Http_Cookie( $value, $url );
  658. }
  659. }
  660. // Cast the Response Code to an int
  661. $response['code'] = intval( $response['code'] );
  662. return array(
  663. 'response' => $response,
  664. 'headers' => $newheaders,
  665. 'cookies' => $cookies,
  666. );
  667. }
  668. /**
  669. * Takes the arguments for a ::request() and checks for the cookie array.
  670. *
  671. * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
  672. * which are each parsed into strings and added to the Cookie: header (within the arguments array).
  673. * Edits the array by reference.
  674. *
  675. * @since 2.8.0
  676. *
  677. * @param array $r Full array of args passed into ::request()
  678. */
  679. public static function buildCookieHeader( &$r ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  680. if ( ! empty( $r['cookies'] ) ) {
  681. // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
  682. foreach ( $r['cookies'] as $name => $value ) {
  683. if ( ! is_object( $value ) ) {
  684. $r['cookies'][ $name ] = new WP_Http_Cookie(
  685. array(
  686. 'name' => $name,
  687. 'value' => $value,
  688. )
  689. );
  690. }
  691. }
  692. $cookies_header = '';
  693. foreach ( (array) $r['cookies'] as $cookie ) {
  694. $cookies_header .= $cookie->getHeaderValue() . '; ';
  695. }
  696. $cookies_header = substr( $cookies_header, 0, -2 );
  697. $r['headers']['cookie'] = $cookies_header;
  698. }
  699. }
  700. /**
  701. * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
  702. *
  703. * Based off the HTTP http_encoding_dechunk function.
  704. *
  705. * @link https://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
  706. *
  707. * @since 2.7.0
  708. *
  709. * @param string $body Body content
  710. * @return string Chunked decoded body on success or raw body on failure.
  711. */
  712. public static function chunkTransferDecode( $body ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
  713. // The body is not chunked encoded or is malformed.
  714. if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) ) {
  715. return $body;
  716. }
  717. $parsed_body = '';
  718. // We'll be altering $body, so need a backup in case of error.
  719. $body_original = $body;
  720. while ( true ) {
  721. $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
  722. if ( ! $has_chunk || empty( $match[1] ) ) {
  723. return $body_original;
  724. }
  725. $length = hexdec( $match[1] );
  726. $chunk_length = strlen( $match[0] );
  727. // Parse out the chunk of data.
  728. $parsed_body .= substr( $body, $chunk_length, $length );
  729. // Remove the chunk from the raw data.
  730. $body = substr( $body, $length + $chunk_length );
  731. // End of the document.
  732. if ( '0' === trim( $body ) ) {
  733. return $parsed_body;
  734. }
  735. }
  736. }
  737. /**
  738. * Determines whether an HTTP API request to the given URL should be blocked.
  739. *
  740. * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
  741. * prevent plugins from working and core functionality, if you don't include `api.wordpress.org`.
  742. *
  743. * You block external URL requests by defining `WP_HTTP_BLOCK_EXTERNAL` as true in your `wp-config.php`
  744. * file and this will only allow localhost and your site to make requests. The constant
  745. * `WP_ACCESSIBLE_HOSTS` will allow additional hosts to go through for requests. The format of the
  746. * `WP_ACCESSIBLE_HOSTS` constant is a comma separated list of hostnames to allow, wildcard domains
  747. * are supported, eg `*.wordpress.org` will allow for all subdomains of `wordpress.org` to be contacted.
  748. *
  749. * @since 2.8.0
  750. * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
  751. * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
  752. *
  753. * @staticvar array|null $accessible_hosts
  754. * @staticvar array $wildcard_regex
  755. *
  756. * @param string $uri URI of url.
  757. * @return bool True to block, false to allow.
  758. */
  759. public function block_request( $uri ) {
  760. // We don't need to block requests, because nothing is blocked.
  761. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) {
  762. return false;
  763. }
  764. $check = parse_url( $uri );
  765. if ( ! $check ) {
  766. return true;
  767. }
  768. $home = parse_url( get_option( 'siteurl' ) );
  769. // Don't block requests back to ourselves by default.
  770. if ( 'localhost' == $check['host'] || ( isset( $home['host'] ) && $home['host'] == $check['host'] ) ) {
  771. /**
  772. * Filters whether to block local HTTP API requests.
  773. *
  774. * A local request is one to `localhost` or to the same host as the site itself.
  775. *
  776. * @since 2.8.0
  777. *
  778. * @param bool $block Whether to block local requests. Default false.
  779. */
  780. return apply_filters( 'block_local_requests', false );
  781. }
  782. if ( ! defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
  783. return true;
  784. }
  785. static $accessible_hosts = null;
  786. static $wildcard_regex = array();
  787. if ( null === $accessible_hosts ) {
  788. $accessible_hosts = preg_split( '|,\s*|', WP_ACCESSIBLE_HOSTS );
  789. if ( false !== strpos( WP_ACCESSIBLE_HOSTS, '*' ) ) {
  790. $wildcard_regex = array();
  791. foreach ( $accessible_hosts as $host ) {
  792. $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
  793. }
  794. $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
  795. }
  796. }
  797. if ( ! empty( $wildcard_regex ) ) {
  798. return ! preg_match( $wildcard_regex, $check['host'] );
  799. } else {
  800. return ! in_array( $check['host'], $accessible_hosts ); // Inverse logic, if it's in the array, then don't block it.
  801. }
  802. }
  803. /**
  804. * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
  805. *
  806. * @deprecated 4.4.0 Use wp_parse_url()
  807. * @see wp_parse_url()
  808. *
  809. * @param string $url The URL to parse.
  810. * @return bool|array False on failure; Array of URL components on success;
  811. * See parse_url()'s return values.
  812. */
  813. protected static function parse_url( $url ) {
  814. _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
  815. return wp_parse_url( $url );
  816. }
  817. /**
  818. * Converts a relative URL to an absolute URL relative to a given URL.
  819. *
  820. * If an Absolute URL is provided, no processing of that URL is done.
  821. *
  822. * @since 3.4.0
  823. *
  824. * @param string $maybe_relative_path The URL which might be relative
  825. * @param string $url The URL which $maybe_relative_path is relative to
  826. * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
  827. */
  828. public static function make_absolute_url( $maybe_relative_path, $url ) {
  829. if ( empty( $url ) ) {
  830. return $maybe_relative_path;
  831. }
  832. $url_parts = wp_parse_url( $url );
  833. if ( ! $url_parts ) {
  834. return $maybe_relative_path;
  835. }
  836. $relative_url_parts = wp_parse_url( $maybe_relative_path );
  837. if ( ! $relative_url_parts ) {
  838. return $maybe_relative_path;
  839. }
  840. // Check for a scheme on the 'relative' url
  841. if ( ! empty( $relative_url_parts['scheme'] ) ) {
  842. return $maybe_relative_path;
  843. }
  844. $absolute_path = $url_parts['scheme'] . '://';
  845. // Schemeless URL's will make it this far, so we check for a host in the relative url and convert it to a protocol-url
  846. if ( isset( $relative_url_parts['host'] ) ) {
  847. $absolute_path .= $relative_url_parts['host'];
  848. if ( isset( $relative_url_parts['port'] ) ) {
  849. $absolute_path .= ':' . $relative_url_parts['port'];
  850. }
  851. } else {
  852. $absolute_path .= $url_parts['host'];
  853. if ( isset( $url_parts['port'] ) ) {
  854. $absolute_path .= ':' . $url_parts['port'];
  855. }
  856. }
  857. // Start off with the Absolute URL path.
  858. $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
  859. // If it's a root-relative path, then great.
  860. if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
  861. $path = $relative_url_parts['path'];
  862. // Else it's a relative path.
  863. } elseif ( ! empty( $relative_url_parts['path'] ) ) {
  864. // Strip off any file components from the absolute path.
  865. $path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
  866. // Build the new path.
  867. $path .= $relative_url_parts['path'];
  868. // Strip all /path/../ out of the path.
  869. while ( strpos( $path, '../' ) > 1 ) {
  870. $path = preg_replace( '![^/]+/\.\./!', '', $path );
  871. }
  872. // Strip any final leading ../ from the path.
  873. $path = preg_replace( '!^/(\.\./)+!', '', $path );
  874. }
  875. // Add the Query string.
  876. if ( ! empty( $relative_url_parts['query'] ) ) {
  877. $path .= '?' . $relative_url_parts['query'];
  878. }
  879. return $absolute_path . '/' . ltrim( $path, '/' );
  880. }
  881. /**
  882. * Handles an HTTP redirect and follows it if appropriate.
  883. *
  884. * @since 3.7.0
  885. *
  886. * @param string $url The URL which was requested.
  887. * @param array $args The arguments which were used to make the request.
  888. * @param array $response The response of the HTTP request.
  889. * @return false|WP_Error|array False if no redirect is present, a WP_Error object if there's an error, or an HTTP
  890. * API response array if the redirect is successfully followed.
  891. */
  892. public static function handle_redirects( $url, $args, $response ) {
  893. // If no redirects are present, or, redirects were not requested, perform no action.
  894. if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) {
  895. return false;
  896. }
  897. // Only perform redirections on redirection http codes.
  898. if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) {
  899. return false;
  900. }
  901. // Don't redirect if we've run out of redirects.
  902. if ( $args['redirection']-- <= 0 ) {
  903. return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
  904. }
  905. $redirect_location = $response['headers']['location'];
  906. // If there were multiple Location headers, use the last header specified.
  907. if ( is_array( $redirect_location ) ) {
  908. $redirect_location = array_pop( $redirect_location );
  909. }
  910. $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
  911. // POST requests should not POST to a redirected location.
  912. if ( 'POST' == $args['method'] ) {
  913. if ( in_array( $response['response']['code'], array( 302, 303 ) ) ) {
  914. $args['method'] = 'GET';
  915. }
  916. }
  917. // Include valid cookies in the redirect process.
  918. if ( ! empty( $response['cookies'] ) ) {
  919. foreach ( $response['cookies'] as $cookie ) {
  920. if ( $cookie->test( $redirect_location ) ) {
  921. $args['cookies'][] = $cookie;
  922. }
  923. }
  924. }
  925. return wp_remote_request( $redirect_location, $args );
  926. }
  927. /**
  928. * Determines if a specified string represents an IP address or not.
  929. *
  930. * This function also detects the type of the IP address, returning either
  931. * '4' or '6' to represent a IPv4 and IPv6 address respectively.
  932. * This does not verify if the IP is a valid IP, only that it appears to be
  933. * an IP address.
  934. *
  935. * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex
  936. *
  937. * @since 3.7.0
  938. *
  939. * @param string $maybe_ip A suspected IP address
  940. * @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
  941. */
  942. public static function is_ip_address( $maybe_ip ) {
  943. if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) ) {
  944. return 4;
  945. }
  946. if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) ) {
  947. return 6;
  948. }
  949. return false;
  950. }
  951. }