class-http.php 36 KB

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