Client.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <?php
  2. /**
  3. * Request Client. Processes a [Request] and handles [HTTP_Caching] if
  4. * available. Will usually return a [Response] object as a result of the
  5. * request unless an unexpected error occurs.
  6. *
  7. * @package Kohana
  8. * @category Base
  9. * @author Kohana Team
  10. * @copyright (c) Kohana Team
  11. * @license https://koseven.ga/LICENSE.md
  12. * @since 3.1.0
  13. */
  14. abstract class Kohana_Request_Client {
  15. /**
  16. * @var Cache Caching library for request caching
  17. */
  18. protected $_cache;
  19. /**
  20. * @var bool Should redirects be followed?
  21. */
  22. protected $_follow = FALSE;
  23. /**
  24. * @var array Headers to preserve when following a redirect
  25. */
  26. protected $_follow_headers = ['authorization'];
  27. /**
  28. * @var bool Follow 302 redirect with original request method?
  29. */
  30. protected $_strict_redirect = TRUE;
  31. /**
  32. * @var array Callbacks to use when response contains given headers
  33. */
  34. protected $_header_callbacks = [
  35. 'Location' => 'Request_Client::on_header_location'
  36. ];
  37. /**
  38. * @var int Maximum number of requests that header callbacks can trigger before the request is aborted
  39. */
  40. protected $_max_callback_depth = 5;
  41. /**
  42. * @var int Tracks the callback depth of the currently executing request
  43. */
  44. protected $_callback_depth = 1;
  45. /**
  46. * @var array Arbitrary parameters that are shared with header callbacks through their Request_Client object
  47. */
  48. protected $_callback_params = [];
  49. /**
  50. * Creates a new `Request_Client` object,
  51. * allows for dependency injection.
  52. *
  53. * @param array $params Params
  54. */
  55. public function __construct(array $params = [])
  56. {
  57. foreach ($params as $key => $value)
  58. {
  59. if (method_exists($this, $key))
  60. {
  61. $this->$key($value);
  62. }
  63. }
  64. }
  65. /**
  66. * Processes the request, executing the controller action that handles this
  67. * request, determined by the [Route].
  68. *
  69. * 1. Before the controller action is called, the [Controller::before] method
  70. * will be called.
  71. * 2. Next the controller action will be called.
  72. * 3. After the controller action is called, the [Controller::after] method
  73. * will be called.
  74. *
  75. * By default, the output from the controller is captured and returned, and
  76. * no headers are sent.
  77. *
  78. * $request->execute();
  79. *
  80. * @param Request $request
  81. * @param Response $response
  82. * @return Response
  83. * @throws Kohana_Exception
  84. * @uses [Kohana::$profiling]
  85. * @uses [Profiler]
  86. */
  87. public function execute(Request $request)
  88. {
  89. // Prevent too much recursion of header callback requests
  90. if ($this->callback_depth() > $this->max_callback_depth())
  91. throw new Request_Client_Recursion_Exception(
  92. "Could not execute request to :uri - too many recursions after :depth requests",
  93. [
  94. ':uri' => $request->uri(),
  95. ':depth' => $this->callback_depth() - 1,
  96. ]);
  97. // Execute the request and pass the currently used protocol
  98. $orig_response = $response = Response::factory(['_protocol' => $request->protocol()]);
  99. if (($cache = $this->cache()) instanceof HTTP_Cache)
  100. return $cache->execute($this, $request, $response);
  101. $response = $this->execute_request($request, $response);
  102. // Execute response callbacks
  103. foreach ($this->header_callbacks() as $header => $callback)
  104. {
  105. if ($response->headers($header))
  106. {
  107. $cb_result = call_user_func($callback, $request, $response, $this);
  108. if ($cb_result instanceof Request)
  109. {
  110. // If the callback returns a request, automatically assign client params
  111. $this->assign_client_properties($cb_result->client());
  112. $cb_result->client()->callback_depth($this->callback_depth() + 1);
  113. // Execute the request
  114. $response = $cb_result->execute();
  115. }
  116. elseif ($cb_result instanceof Response)
  117. {
  118. // Assign the returned response
  119. $response = $cb_result;
  120. }
  121. // If the callback has created a new response, do not process any further
  122. if ($response !== $orig_response)
  123. break;
  124. }
  125. }
  126. return $response;
  127. }
  128. /**
  129. * Processes the request passed to it and returns the response from
  130. * the URI resource identified.
  131. *
  132. * This method must be implemented by all clients.
  133. *
  134. * @param Request $request request to execute by client
  135. * @param Response $response
  136. * @return Response
  137. * @since 3.2.0
  138. */
  139. abstract public function execute_request(Request $request, Response $response);
  140. /**
  141. * Getter and setter for the internal caching engine,
  142. * used to cache responses if available and valid.
  143. *
  144. * @param HTTP_Cache $cache engine to use for caching
  145. * @return HTTP_Cache
  146. * @return Request_Client
  147. */
  148. public function cache(HTTP_Cache $cache = NULL)
  149. {
  150. if ($cache === NULL)
  151. return $this->_cache;
  152. $this->_cache = $cache;
  153. return $this;
  154. }
  155. /**
  156. * Getter and setter for the follow redirects
  157. * setting.
  158. *
  159. * @param bool $follow Boolean indicating if redirects should be followed
  160. * @return bool
  161. * @return Request_Client
  162. */
  163. public function follow($follow = NULL)
  164. {
  165. if ($follow === NULL)
  166. return $this->_follow;
  167. $this->_follow = $follow;
  168. return $this;
  169. }
  170. /**
  171. * Getter and setter for the follow redirects
  172. * headers array.
  173. *
  174. * @param array $follow_headers Array of headers to be re-used when following a Location header
  175. * @return array
  176. * @return Request_Client
  177. */
  178. public function follow_headers($follow_headers = NULL)
  179. {
  180. if ($follow_headers === NULL)
  181. return $this->_follow_headers;
  182. $this->_follow_headers = array_map('strtolower', $follow_headers);
  183. return $this;
  184. }
  185. /**
  186. * Getter and setter for the strict redirects setting
  187. *
  188. * [!!] HTTP/1.1 specifies that a 302 redirect should be followed using the
  189. * original request method. However, the vast majority of clients and servers
  190. * get this wrong, with 302 widely used for 'POST - 302 redirect - GET' patterns.
  191. * By default, Kohana's client is fully compliant with the HTTP spec. Some
  192. * non-compliant third party sites may require that strict_redirect is set
  193. * FALSE to force the client to switch to GET following a 302 response.
  194. *
  195. * @param bool $strict_redirect Boolean indicating if 302 redirects should be followed with the original method
  196. * @return Request_Client
  197. */
  198. public function strict_redirect($strict_redirect = NULL)
  199. {
  200. if ($strict_redirect === NULL)
  201. return $this->_strict_redirect;
  202. $this->_strict_redirect = $strict_redirect;
  203. return $this;
  204. }
  205. /**
  206. * Getter and setter for the header callbacks array.
  207. *
  208. * Accepts an array with HTTP response headers as keys and a PHP callback
  209. * function as values. These callbacks will be triggered if a response contains
  210. * the given header and can either issue a subsequent request or manipulate
  211. * the response as required.
  212. *
  213. * By default, the [Request_Client::on_header_location] callback is assigned
  214. * to the Location header to support automatic redirect following.
  215. *
  216. * $client->header_callbacks(array(
  217. * 'Location' => 'Request_Client::on_header_location',
  218. * 'WWW-Authenticate' => function($request, $response, $client) {return $new_response;},
  219. * );
  220. *
  221. * @param array $header_callbacks Array of callbacks to trigger on presence of given headers
  222. * @return Request_Client
  223. */
  224. public function header_callbacks($header_callbacks = NULL)
  225. {
  226. if ($header_callbacks === NULL)
  227. return $this->_header_callbacks;
  228. $this->_header_callbacks = $header_callbacks;
  229. return $this;
  230. }
  231. /**
  232. * Getter and setter for the maximum callback depth property.
  233. *
  234. * This protects the main execution from recursive callback execution (eg
  235. * following infinite redirects, conflicts between callbacks causing loops
  236. * etc). Requests will only be allowed to nest to the level set by this
  237. * param before execution is aborted with a Request_Client_Recursion_Exception.
  238. *
  239. * @param int $depth Maximum number of callback requests to execute before aborting
  240. * @return Request_Client|int
  241. */
  242. public function max_callback_depth($depth = NULL)
  243. {
  244. if ($depth === NULL)
  245. return $this->_max_callback_depth;
  246. $this->_max_callback_depth = $depth;
  247. return $this;
  248. }
  249. /**
  250. * Getter/Setter for the callback depth property, which is used to track
  251. * how many recursions have been executed within the current request execution.
  252. *
  253. * @param int $depth Current recursion depth
  254. * @return Request_Client|int
  255. */
  256. public function callback_depth($depth = NULL)
  257. {
  258. if ($depth === NULL)
  259. return $this->_callback_depth;
  260. $this->_callback_depth = $depth;
  261. return $this;
  262. }
  263. /**
  264. * Getter/Setter for the callback_params array, which allows additional
  265. * application-specific parameters to be shared with callbacks.
  266. *
  267. * As with other Kohana setter/getters, usage is:
  268. *
  269. * // Set full array
  270. * $client->callback_params(array('foo'=>'bar'));
  271. *
  272. * // Set single key
  273. * $client->callback_params('foo','bar');
  274. *
  275. * // Get full array
  276. * $params = $client->callback_params();
  277. *
  278. * // Get single key
  279. * $foo = $client->callback_params('foo');
  280. *
  281. * @param string|array $param
  282. * @param mixed $value
  283. * @return Request_Client|mixed
  284. */
  285. public function callback_params($param = NULL, $value = NULL)
  286. {
  287. // Getter for full array
  288. if ($param === NULL)
  289. return $this->_callback_params;
  290. // Setter for full array
  291. if (is_array($param))
  292. {
  293. $this->_callback_params = $param;
  294. return $this;
  295. }
  296. // Getter for single value
  297. elseif ($value === NULL)
  298. {
  299. return Arr::get($this->_callback_params, $param);
  300. }
  301. // Setter for single value
  302. else
  303. {
  304. $this->_callback_params[$param] = $value;
  305. return $this;
  306. }
  307. }
  308. /**
  309. * Assigns the properties of the current Request_Client to another
  310. * Request_Client instance - used when setting up a subsequent request.
  311. *
  312. * @param Request_Client $client
  313. */
  314. public function assign_client_properties(Request_Client $client)
  315. {
  316. $client->cache($this->cache());
  317. $client->follow($this->follow());
  318. $client->follow_headers($this->follow_headers());
  319. $client->header_callbacks($this->header_callbacks());
  320. $client->max_callback_depth($this->max_callback_depth());
  321. $client->callback_params($this->callback_params());
  322. }
  323. /**
  324. * The default handler for following redirects, triggered by the presence of
  325. * a Location header in the response.
  326. *
  327. * The client's follow property must be set TRUE and the HTTP response status
  328. * one of 201, 301, 302, 303 or 307 for the redirect to be followed.
  329. *
  330. * @param Request $request
  331. * @param Response $response
  332. * @param Request_Client $client
  333. */
  334. public static function on_header_location(Request $request, Response $response, Request_Client $client)
  335. {
  336. // Do we need to follow a Location header ?
  337. if ($client->follow() AND in_array($response->status(), [201, 301, 302, 303, 307]))
  338. {
  339. // Figure out which method to use for the follow request
  340. switch ($response->status())
  341. {
  342. default:
  343. case 301:
  344. case 307:
  345. $follow_method = $request->method();
  346. break;
  347. case 201:
  348. case 303:
  349. $follow_method = Request::GET;
  350. break;
  351. case 302:
  352. // Cater for sites with broken HTTP redirect implementations
  353. if ($client->strict_redirect())
  354. {
  355. $follow_method = $request->method();
  356. }
  357. else
  358. {
  359. $follow_method = Request::GET;
  360. }
  361. break;
  362. }
  363. // Prepare the additional request, copying any follow_headers that were present on the original request
  364. $orig_headers = $request->headers()->getArrayCopy();
  365. $follow_header_keys = array_intersect(array_keys($orig_headers), $client->follow_headers());
  366. $follow_headers = \Arr::extract($orig_headers, $follow_header_keys);
  367. $follow_request = Request::factory($response->headers('Location'))
  368. ->method($follow_method)
  369. ->headers($follow_headers);
  370. if ($follow_method !== Request::GET)
  371. {
  372. $follow_request->body($request->body());
  373. }
  374. return $follow_request;
  375. }
  376. return NULL;
  377. }
  378. }