Client.php 20 KB

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