Dispatcher.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Julius Härtl <jus@bitgrid.net>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Thomas Tanghus <thomas@tanghus.net>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC\AppFramework\Http;
  32. use OC\AppFramework\Http;
  33. use OC\AppFramework\Middleware\MiddlewareDispatcher;
  34. use OC\AppFramework\Utility\ControllerMethodReflector;
  35. use OC\DB\ConnectionAdapter;
  36. use OCP\AppFramework\Controller;
  37. use OCP\AppFramework\Http\DataResponse;
  38. use OCP\AppFramework\Http\ParameterOutOfRangeException;
  39. use OCP\AppFramework\Http\Response;
  40. use OCP\Diagnostics\IEventLogger;
  41. use OCP\IConfig;
  42. use OCP\IRequest;
  43. use Psr\Container\ContainerInterface;
  44. use Psr\Log\LoggerInterface;
  45. /**
  46. * Class to dispatch the request to the middleware dispatcher
  47. */
  48. class Dispatcher {
  49. /** @var MiddlewareDispatcher */
  50. private $middlewareDispatcher;
  51. /** @var Http */
  52. private $protocol;
  53. /** @var ControllerMethodReflector */
  54. private $reflector;
  55. /** @var IRequest */
  56. private $request;
  57. /** @var IConfig */
  58. private $config;
  59. /** @var ConnectionAdapter */
  60. private $connection;
  61. /** @var LoggerInterface */
  62. private $logger;
  63. /** @var IEventLogger */
  64. private $eventLogger;
  65. private ContainerInterface $appContainer;
  66. /**
  67. * @param Http $protocol the http protocol with contains all status headers
  68. * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which
  69. * runs the middleware
  70. * @param ControllerMethodReflector $reflector the reflector that is used to inject
  71. * the arguments for the controller
  72. * @param IRequest $request the incoming request
  73. * @param IConfig $config
  74. * @param ConnectionAdapter $connection
  75. * @param LoggerInterface $logger
  76. * @param IEventLogger $eventLogger
  77. */
  78. public function __construct(Http $protocol,
  79. MiddlewareDispatcher $middlewareDispatcher,
  80. ControllerMethodReflector $reflector,
  81. IRequest $request,
  82. IConfig $config,
  83. ConnectionAdapter $connection,
  84. LoggerInterface $logger,
  85. IEventLogger $eventLogger,
  86. ContainerInterface $appContainer) {
  87. $this->protocol = $protocol;
  88. $this->middlewareDispatcher = $middlewareDispatcher;
  89. $this->reflector = $reflector;
  90. $this->request = $request;
  91. $this->config = $config;
  92. $this->connection = $connection;
  93. $this->logger = $logger;
  94. $this->eventLogger = $eventLogger;
  95. $this->appContainer = $appContainer;
  96. }
  97. /**
  98. * Handles a request and calls the dispatcher on the controller
  99. * @param Controller $controller the controller which will be called
  100. * @param string $methodName the method name which will be called on
  101. * the controller
  102. * @return array $array[0] contains a string with the http main header,
  103. * $array[1] contains headers in the form: $key => value, $array[2] contains
  104. * the response output
  105. * @throws \Exception
  106. */
  107. public function dispatch(Controller $controller, string $methodName): array {
  108. $out = [null, [], null];
  109. try {
  110. // prefill reflector with everything that's needed for the
  111. // middlewares
  112. $this->reflector->reflect($controller, $methodName);
  113. $this->middlewareDispatcher->beforeController($controller,
  114. $methodName);
  115. $databaseStatsBefore = [];
  116. if ($this->config->getSystemValueBool('debug', false)) {
  117. $databaseStatsBefore = $this->connection->getInner()->getStats();
  118. }
  119. $response = $this->executeController($controller, $methodName);
  120. if (!empty($databaseStatsBefore)) {
  121. $databaseStatsAfter = $this->connection->getInner()->getStats();
  122. $numBuilt = $databaseStatsAfter['built'] - $databaseStatsBefore['built'];
  123. $numExecuted = $databaseStatsAfter['executed'] - $databaseStatsBefore['executed'];
  124. if ($numBuilt > 50) {
  125. $this->logger->debug('Controller {class}::{method} created {count} QueryBuilder objects, please check if they are created inside a loop by accident.', [
  126. 'class' => get_class($controller),
  127. 'method' => $methodName,
  128. 'count' => $numBuilt,
  129. ]);
  130. }
  131. if ($numExecuted > 100) {
  132. $this->logger->warning('Controller {class}::{method} executed {count} queries.', [
  133. 'class' => get_class($controller),
  134. 'method' => $methodName,
  135. 'count' => $numExecuted,
  136. ]);
  137. }
  138. }
  139. // if an exception appears, the middleware checks if it can handle the
  140. // exception and creates a response. If no response is created, it is
  141. // assumed that there's no middleware who can handle it and the error is
  142. // thrown again
  143. } catch (\Exception $exception) {
  144. $response = $this->middlewareDispatcher->afterException(
  145. $controller, $methodName, $exception);
  146. } catch (\Throwable $throwable) {
  147. $exception = new \Exception($throwable->getMessage() . ' in file \'' . $throwable->getFile() . '\' line ' . $throwable->getLine(), $throwable->getCode(), $throwable);
  148. $response = $this->middlewareDispatcher->afterException(
  149. $controller, $methodName, $exception);
  150. }
  151. $response = $this->middlewareDispatcher->afterController(
  152. $controller, $methodName, $response);
  153. // depending on the cache object the headers need to be changed
  154. $out[0] = $this->protocol->getStatusHeader($response->getStatus());
  155. $out[1] = array_merge($response->getHeaders());
  156. $out[2] = $response->getCookies();
  157. $out[3] = $this->middlewareDispatcher->beforeOutput(
  158. $controller, $methodName, $response->render()
  159. );
  160. $out[4] = $response;
  161. return $out;
  162. }
  163. /**
  164. * Uses the reflected parameters, types and request parameters to execute
  165. * the controller
  166. * @param Controller $controller the controller to be executed
  167. * @param string $methodName the method on the controller that should be executed
  168. * @return Response
  169. */
  170. private function executeController(Controller $controller, string $methodName): Response {
  171. $arguments = [];
  172. // valid types that will be cast
  173. $types = ['int', 'integer', 'bool', 'boolean', 'float', 'double'];
  174. foreach ($this->reflector->getParameters() as $param => $default) {
  175. // try to get the parameter from the request object and cast
  176. // it to the type annotated in the @param annotation
  177. $value = $this->request->getParam($param, $default);
  178. $type = $this->reflector->getType($param);
  179. // if this is submitted using GET or a POST form, 'false' should be
  180. // converted to false
  181. if (($type === 'bool' || $type === 'boolean') &&
  182. $value === 'false' &&
  183. (
  184. $this->request->method === 'GET' ||
  185. str_contains($this->request->getHeader('Content-Type'),
  186. 'application/x-www-form-urlencoded')
  187. )
  188. ) {
  189. $value = false;
  190. } elseif ($value !== null && \in_array($type, $types, true)) {
  191. settype($value, $type);
  192. $this->ensureParameterValueSatisfiesRange($param, $value);
  193. } elseif ($value === null && $type !== null && $this->appContainer->has($type)) {
  194. $value = $this->appContainer->get($type);
  195. }
  196. $arguments[] = $value;
  197. }
  198. $this->eventLogger->start('controller:' . get_class($controller) . '::' . $methodName, 'App framework controller execution');
  199. $response = \call_user_func_array([$controller, $methodName], $arguments);
  200. $this->eventLogger->end('controller:' . get_class($controller) . '::' . $methodName);
  201. // format response
  202. if ($response instanceof DataResponse || !($response instanceof Response)) {
  203. // get format from the url format or request format parameter
  204. $format = $this->request->getParam('format');
  205. // if none is given try the first Accept header
  206. if ($format === null) {
  207. $headers = $this->request->getHeader('Accept');
  208. $format = $controller->getResponderByHTTPHeader($headers, null);
  209. }
  210. if ($format !== null) {
  211. $response = $controller->buildResponse($response, $format);
  212. } else {
  213. $response = $controller->buildResponse($response);
  214. }
  215. }
  216. return $response;
  217. }
  218. /**
  219. * @psalm-param mixed $value
  220. * @throws ParameterOutOfRangeException
  221. */
  222. private function ensureParameterValueSatisfiesRange(string $param, $value): void {
  223. $rangeInfo = $this->reflector->getRange($param);
  224. if ($rangeInfo) {
  225. if ($value < $rangeInfo['min'] || $value > $rangeInfo['max']) {
  226. throw new ParameterOutOfRangeException(
  227. $param,
  228. $value,
  229. $rangeInfo['min'],
  230. $rangeInfo['max'],
  231. );
  232. }
  233. }
  234. }
  235. }