Client.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  10. * @link https://cakephp.org CakePHP(tm) Project
  11. * @since 3.0.0
  12. * @license https://opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Http;
  15. use Cake\Core\App;
  16. use Cake\Core\Exception\Exception;
  17. use Cake\Core\InstanceConfigTrait;
  18. use Cake\Http\Client\CookieCollection;
  19. use Cake\Http\Client\Request;
  20. use Cake\Http\Cookie\CookieInterface;
  21. use Cake\Utility\Hash;
  22. use Zend\Diactoros\Uri;
  23. /**
  24. * The end user interface for doing HTTP requests.
  25. *
  26. * ### Scoped clients
  27. *
  28. * If you're doing multiple requests to the same hostname its often convenient
  29. * to use the constructor arguments to create a scoped client. This allows you
  30. * to keep your code DRY and not repeat hostnames, authentication, and other options.
  31. *
  32. * ### Doing requests
  33. *
  34. * Once you've created an instance of Client you can do requests
  35. * using several methods. Each corresponds to a different HTTP method.
  36. *
  37. * - get()
  38. * - post()
  39. * - put()
  40. * - delete()
  41. * - patch()
  42. *
  43. * ### Cookie management
  44. *
  45. * Client will maintain cookies from the responses done with
  46. * a client instance. These cookies will be automatically added
  47. * to future requests to matching hosts. Cookies will respect the
  48. * `Expires`, `Path` and `Domain` attributes. You can get the client's
  49. * CookieCollection using cookies()
  50. *
  51. * You can use the 'cookieJar' constructor option to provide a custom
  52. * cookie jar instance you've restored from cache/disk. By default
  53. * an empty instance of Cake\Http\Client\CookieCollection will be created.
  54. *
  55. * ### Sending request bodies
  56. *
  57. * By default any POST/PUT/PATCH/DELETE request with $data will
  58. * send their data as `application/x-www-form-urlencoded` unless
  59. * there are attached files. In that case `multipart/form-data`
  60. * will be used.
  61. *
  62. * When sending request bodies you can use the `type` option to
  63. * set the Content-Type for the request:
  64. *
  65. * ```
  66. * $http->get('/users', [], ['type' => 'json']);
  67. * ```
  68. *
  69. * The `type` option sets both the `Content-Type` and `Accept` header, to
  70. * the same mime type. When using `type` you can use either a full mime
  71. * type or an alias. If you need different types in the Accept and Content-Type
  72. * headers you should set them manually and not use `type`
  73. *
  74. * ### Using authentication
  75. *
  76. * By using the `auth` key you can use authentication. The type sub option
  77. * can be used to specify which authentication strategy you want to use.
  78. * CakePHP comes with a few built-in strategies:
  79. *
  80. * - Basic
  81. * - Digest
  82. * - Oauth
  83. *
  84. * ### Using proxies
  85. *
  86. * By using the `proxy` key you can set authentication credentials for
  87. * a proxy if you need to use one.. The type sub option can be used to
  88. * specify which authentication strategy you want to use.
  89. * CakePHP comes with built-in support for basic authentication.
  90. *
  91. */
  92. class Client
  93. {
  94. use InstanceConfigTrait;
  95. /**
  96. * Default configuration for the client.
  97. *
  98. * @var array
  99. */
  100. protected $_defaultConfig = [
  101. 'adapter' => 'Cake\Http\Client\Adapter\Stream',
  102. 'host' => null,
  103. 'port' => null,
  104. 'scheme' => 'http',
  105. 'timeout' => 30,
  106. 'ssl_verify_peer' => true,
  107. 'ssl_verify_peer_name' => true,
  108. 'ssl_verify_depth' => 5,
  109. 'ssl_verify_host' => true,
  110. 'redirect' => false,
  111. ];
  112. /**
  113. * List of cookies from responses made with this client.
  114. *
  115. * Cookies are indexed by the cookie's domain or
  116. * request host name.
  117. *
  118. * @var \Cake\Http\Client\CookieCollection
  119. */
  120. protected $_cookies;
  121. /**
  122. * Adapter for sending requests. Defaults to
  123. * Cake\Http\Client\Adapter\Stream
  124. *
  125. * @var \Cake\Http\Client\Adapter\Stream
  126. */
  127. protected $_adapter;
  128. /**
  129. * Create a new HTTP Client.
  130. *
  131. * ### Config options
  132. *
  133. * You can set the following options when creating a client:
  134. *
  135. * - host - The hostname to do requests on.
  136. * - port - The port to use.
  137. * - scheme - The default scheme/protocol to use. Defaults to http.
  138. * - timeout - The timeout in seconds. Defaults to 30
  139. * - ssl_verify_peer - Whether or not SSL certificates should be validated.
  140. * Defaults to true.
  141. * - ssl_verify_peer_name - Whether or not peer names should be validated.
  142. * Defaults to true.
  143. * - ssl_verify_depth - The maximum certificate chain depth to travers.
  144. * Defaults to 5.
  145. * - ssl_verify_host - Verify that the certificate and hostname match.
  146. * Defaults to true.
  147. * - redirect - Number of redirects to follow. Defaults to false.
  148. *
  149. * @param array $config Config options for scoped clients.
  150. */
  151. public function __construct($config = [])
  152. {
  153. $this->setConfig($config);
  154. $adapter = $this->_config['adapter'];
  155. $this->setConfig('adapter', null);
  156. if (is_string($adapter)) {
  157. $adapter = new $adapter();
  158. }
  159. $this->_adapter = $adapter;
  160. if (!empty($this->_config['cookieJar'])) {
  161. $this->_cookies = $this->_config['cookieJar'];
  162. $this->setConfig('cookieJar', null);
  163. } else {
  164. $this->_cookies = new CookieCollection();
  165. }
  166. }
  167. /**
  168. * Get the cookies stored in the Client.
  169. *
  170. * @return \Cake\Http\Client\CookieCollection
  171. */
  172. public function cookies()
  173. {
  174. return $this->_cookies;
  175. }
  176. /**
  177. * Adds a cookie to the Client collection.
  178. *
  179. * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object.
  180. * @return $this
  181. */
  182. public function addCookie(CookieInterface $cookie)
  183. {
  184. $this->_cookies = $this->_cookies->add($cookie);
  185. return $this;
  186. }
  187. /**
  188. * Do a GET request.
  189. *
  190. * The $data argument supports a special `_content` key
  191. * for providing a request body in a GET request. This is
  192. * generally not used but services like ElasticSearch use
  193. * this feature.
  194. *
  195. * @param string $url The url or path you want to request.
  196. * @param array $data The query data you want to send.
  197. * @param array $options Additional options for the request.
  198. * @return \Cake\Http\Client\Response
  199. */
  200. public function get($url, $data = [], array $options = [])
  201. {
  202. $options = $this->_mergeOptions($options);
  203. $body = null;
  204. if (isset($data['_content'])) {
  205. $body = $data['_content'];
  206. unset($data['_content']);
  207. }
  208. $url = $this->buildUrl($url, $data, $options);
  209. return $this->_doRequest(
  210. Request::METHOD_GET,
  211. $url,
  212. $body,
  213. $options
  214. );
  215. }
  216. /**
  217. * Do a POST request.
  218. *
  219. * @param string $url The url or path you want to request.
  220. * @param mixed $data The post data you want to send.
  221. * @param array $options Additional options for the request.
  222. * @return \Cake\Http\Client\Response
  223. */
  224. public function post($url, $data = [], array $options = [])
  225. {
  226. $options = $this->_mergeOptions($options);
  227. $url = $this->buildUrl($url, [], $options);
  228. return $this->_doRequest(Request::METHOD_POST, $url, $data, $options);
  229. }
  230. /**
  231. * Do a PUT request.
  232. *
  233. * @param string $url The url or path you want to request.
  234. * @param mixed $data The request data you want to send.
  235. * @param array $options Additional options for the request.
  236. * @return \Cake\Http\Client\Response
  237. */
  238. public function put($url, $data = [], array $options = [])
  239. {
  240. $options = $this->_mergeOptions($options);
  241. $url = $this->buildUrl($url, [], $options);
  242. return $this->_doRequest(Request::METHOD_PUT, $url, $data, $options);
  243. }
  244. /**
  245. * Do a PATCH request.
  246. *
  247. * @param string $url The url or path you want to request.
  248. * @param mixed $data The request data you want to send.
  249. * @param array $options Additional options for the request.
  250. * @return \Cake\Http\Client\Response
  251. */
  252. public function patch($url, $data = [], array $options = [])
  253. {
  254. $options = $this->_mergeOptions($options);
  255. $url = $this->buildUrl($url, [], $options);
  256. return $this->_doRequest(Request::METHOD_PATCH, $url, $data, $options);
  257. }
  258. /**
  259. * Do an OPTIONS request.
  260. *
  261. * @param string $url The url or path you want to request.
  262. * @param mixed $data The request data you want to send.
  263. * @param array $options Additional options for the request.
  264. * @return \Cake\Http\Client\Response
  265. */
  266. public function options($url, $data = [], array $options = [])
  267. {
  268. $options = $this->_mergeOptions($options);
  269. $url = $this->buildUrl($url, [], $options);
  270. return $this->_doRequest(Request::METHOD_OPTIONS, $url, $data, $options);
  271. }
  272. /**
  273. * Do a TRACE request.
  274. *
  275. * @param string $url The url or path you want to request.
  276. * @param mixed $data The request data you want to send.
  277. * @param array $options Additional options for the request.
  278. * @return \Cake\Http\Client\Response
  279. */
  280. public function trace($url, $data = [], array $options = [])
  281. {
  282. $options = $this->_mergeOptions($options);
  283. $url = $this->buildUrl($url, [], $options);
  284. return $this->_doRequest(Request::METHOD_TRACE, $url, $data, $options);
  285. }
  286. /**
  287. * Do a DELETE request.
  288. *
  289. * @param string $url The url or path you want to request.
  290. * @param mixed $data The request data you want to send.
  291. * @param array $options Additional options for the request.
  292. * @return \Cake\Http\Client\Response
  293. */
  294. public function delete($url, $data = [], array $options = [])
  295. {
  296. $options = $this->_mergeOptions($options);
  297. $url = $this->buildUrl($url, [], $options);
  298. return $this->_doRequest(Request::METHOD_DELETE, $url, $data, $options);
  299. }
  300. /**
  301. * Do a HEAD request.
  302. *
  303. * @param string $url The url or path you want to request.
  304. * @param array $data The query string data you want to send.
  305. * @param array $options Additional options for the request.
  306. * @return \Cake\Http\Client\Response
  307. */
  308. public function head($url, array $data = [], array $options = [])
  309. {
  310. $options = $this->_mergeOptions($options);
  311. $url = $this->buildUrl($url, $data, $options);
  312. return $this->_doRequest(Request::METHOD_HEAD, $url, '', $options);
  313. }
  314. /**
  315. * Helper method for doing non-GET requests.
  316. *
  317. * @param string $method HTTP method.
  318. * @param string $url URL to request.
  319. * @param mixed $data The request body.
  320. * @param array $options The options to use. Contains auth, proxy etc.
  321. * @return \Cake\Http\Client\Response
  322. */
  323. protected function _doRequest($method, $url, $data, $options)
  324. {
  325. $request = $this->_createRequest(
  326. $method,
  327. $url,
  328. $data,
  329. $options
  330. );
  331. return $this->send($request, $options);
  332. }
  333. /**
  334. * Does a recursive merge of the parameter with the scope config.
  335. *
  336. * @param array $options Options to merge.
  337. * @return array Options merged with set config.
  338. */
  339. protected function _mergeOptions($options)
  340. {
  341. return Hash::merge($this->_config, $options);
  342. }
  343. /**
  344. * Send a request.
  345. *
  346. * Used internally by other methods, but can also be used to send
  347. * handcrafted Request objects.
  348. *
  349. * @param \Cake\Http\Client\Request $request The request to send.
  350. * @param array $options Additional options to use.
  351. * @return \Cake\Http\Client\Response
  352. */
  353. public function send(Request $request, $options = [])
  354. {
  355. $redirects = 0;
  356. if (isset($options['redirect'])) {
  357. $redirects = (int)$options['redirect'];
  358. unset($options['redirect']);
  359. }
  360. do {
  361. $response = $this->_sendRequest($request, $options);
  362. $handleRedirect = $response->isRedirect() && $redirects-- > 0;
  363. if ($handleRedirect) {
  364. $url = $request->getUri();
  365. $request = $this->_cookies->addToRequest($request, []);
  366. $location = $response->getHeaderLine('Location');
  367. $locationUrl = $this->buildUrl($location, [], [
  368. 'host' => $url->getHost(),
  369. 'port' => $url->getPort(),
  370. 'scheme' => $url->getScheme()
  371. ]);
  372. $request = $request->withUri(new Uri($locationUrl));
  373. }
  374. } while ($handleRedirect);
  375. return $response;
  376. }
  377. /**
  378. * Send a request without redirection.
  379. *
  380. * @param \Cake\Http\Client\Request $request The request to send.
  381. * @param array $options Additional options to use.
  382. * @return \Cake\Http\Client\Response
  383. */
  384. protected function _sendRequest(Request $request, $options)
  385. {
  386. $responses = $this->_adapter->send($request, $options);
  387. $url = $request->getUri();
  388. foreach ($responses as $response) {
  389. $this->_cookies = $this->_cookies->addFromResponse($response, $request);
  390. }
  391. return array_pop($responses);
  392. }
  393. /**
  394. * Generate a URL based on the scoped client options.
  395. *
  396. * @param string $url Either a full URL or just the path.
  397. * @param string|array $query The query data for the URL.
  398. * @param array $options The config options stored with Client::config()
  399. * @return string A complete url with scheme, port, host, path.
  400. */
  401. public function buildUrl($url, $query = [], $options = [])
  402. {
  403. if (empty($options) && empty($query)) {
  404. return $url;
  405. }
  406. if ($query) {
  407. $q = (strpos($url, '?') === false) ? '?' : '&';
  408. $url .= $q;
  409. $url .= is_string($query) ? $query : http_build_query($query);
  410. }
  411. $defaults = [
  412. 'host' => null,
  413. 'port' => null,
  414. 'scheme' => 'http',
  415. ];
  416. $options += $defaults;
  417. if (preg_match('#^//#', $url)) {
  418. $url = $options['scheme'] . ':' . $url;
  419. }
  420. if (preg_match('#^https?://#', $url)) {
  421. return $url;
  422. }
  423. $defaultPorts = [
  424. 'http' => 80,
  425. 'https' => 443
  426. ];
  427. $out = $options['scheme'] . '://' . $options['host'];
  428. if ($options['port'] && $options['port'] != $defaultPorts[$options['scheme']]) {
  429. $out .= ':' . $options['port'];
  430. }
  431. $out .= '/' . ltrim($url, '/');
  432. return $out;
  433. }
  434. /**
  435. * Creates a new request object based on the parameters.
  436. *
  437. * @param string $method HTTP method name.
  438. * @param string $url The url including query string.
  439. * @param mixed $data The request body.
  440. * @param array $options The options to use. Contains auth, proxy etc.
  441. * @return \Cake\Http\Client\Request
  442. */
  443. protected function _createRequest($method, $url, $data, $options)
  444. {
  445. $headers = isset($options['headers']) ? (array)$options['headers'] : [];
  446. if (isset($options['type'])) {
  447. $headers = array_merge($headers, $this->_typeHeaders($options['type']));
  448. }
  449. if (is_string($data) && !isset($headers['Content-Type']) && !isset($headers['content-type'])) {
  450. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  451. }
  452. $request = new Request($url, $method, $headers, $data);
  453. $cookies = isset($options['cookies']) ? $options['cookies'] : [];
  454. $request = $this->_cookies->addToRequest($request, $cookies);
  455. if (isset($options['auth'])) {
  456. $request = $this->_addAuthentication($request, $options);
  457. }
  458. if (isset($options['proxy'])) {
  459. $request = $this->_addProxy($request, $options);
  460. }
  461. return $request;
  462. }
  463. /**
  464. * Returns headers for Accept/Content-Type based on a short type
  465. * or full mime-type.
  466. *
  467. * @param string $type short type alias or full mimetype.
  468. * @return array Headers to set on the request.
  469. * @throws \Cake\Core\Exception\Exception When an unknown type alias is used.
  470. */
  471. protected function _typeHeaders($type)
  472. {
  473. if (strpos($type, '/') !== false) {
  474. return [
  475. 'Accept' => $type,
  476. 'Content-Type' => $type
  477. ];
  478. }
  479. $typeMap = [
  480. 'json' => 'application/json',
  481. 'xml' => 'application/xml',
  482. ];
  483. if (!isset($typeMap[$type])) {
  484. throw new Exception("Unknown type alias '$type'.");
  485. }
  486. return [
  487. 'Accept' => $typeMap[$type],
  488. 'Content-Type' => $typeMap[$type],
  489. ];
  490. }
  491. /**
  492. * Add authentication headers to the request.
  493. *
  494. * Uses the authentication type to choose the correct strategy
  495. * and use its methods to add headers.
  496. *
  497. * @param \Cake\Http\Client\Request $request The request to modify.
  498. * @param array $options Array of options containing the 'auth' key.
  499. * @return \Cake\Http\Client\Request The updated request object.
  500. */
  501. protected function _addAuthentication(Request $request, $options)
  502. {
  503. $auth = $options['auth'];
  504. $adapter = $this->_createAuth($auth, $options);
  505. $result = $adapter->authentication($request, $options['auth']);
  506. return $result ?: $request;
  507. }
  508. /**
  509. * Add proxy authentication headers.
  510. *
  511. * Uses the authentication type to choose the correct strategy
  512. * and use its methods to add headers.
  513. *
  514. * @param \Cake\Http\Client\Request $request The request to modify.
  515. * @param array $options Array of options containing the 'proxy' key.
  516. * @return \Cake\Http\Client\Request The updated request object.
  517. */
  518. protected function _addProxy(Request $request, $options)
  519. {
  520. $auth = $options['proxy'];
  521. $adapter = $this->_createAuth($auth, $options);
  522. $result = $adapter->proxyAuthentication($request, $options['proxy']);
  523. return $result ?: $request;
  524. }
  525. /**
  526. * Create the authentication strategy.
  527. *
  528. * Use the configuration options to create the correct
  529. * authentication strategy handler.
  530. *
  531. * @param array $auth The authentication options to use.
  532. * @param array $options The overall request options to use.
  533. * @return mixed Authentication strategy instance.
  534. * @throws \Cake\Core\Exception\Exception when an invalid strategy is chosen.
  535. */
  536. protected function _createAuth($auth, $options)
  537. {
  538. if (empty($auth['type'])) {
  539. $auth['type'] = 'basic';
  540. }
  541. $name = ucfirst($auth['type']);
  542. $class = App::className($name, 'Http/Client/Auth');
  543. if (!$class) {
  544. throw new Exception(
  545. sprintf('Invalid authentication type %s', $name)
  546. );
  547. }
  548. return new $class($this, $options);
  549. }
  550. }
  551. // @deprecated Backwards compatibility with earler 3.x versions.
  552. class_alias('Cake\Http\Client', 'Cake\Network\Http\Client');