Dispatcher.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\AppFramework\Http;
  9. use OC\AppFramework\Http;
  10. use OC\AppFramework\Middleware\MiddlewareDispatcher;
  11. use OC\AppFramework\Utility\ControllerMethodReflector;
  12. use OC\DB\ConnectionAdapter;
  13. use OCP\AppFramework\Controller;
  14. use OCP\AppFramework\Http\DataResponse;
  15. use OCP\AppFramework\Http\ParameterOutOfRangeException;
  16. use OCP\AppFramework\Http\Response;
  17. use OCP\Diagnostics\IEventLogger;
  18. use OCP\IConfig;
  19. use OCP\IRequest;
  20. use Psr\Container\ContainerInterface;
  21. use Psr\Log\LoggerInterface;
  22. /**
  23. * Class to dispatch the request to the middleware dispatcher
  24. */
  25. class Dispatcher {
  26. /** @var MiddlewareDispatcher */
  27. private $middlewareDispatcher;
  28. /** @var Http */
  29. private $protocol;
  30. /** @var ControllerMethodReflector */
  31. private $reflector;
  32. /** @var IRequest */
  33. private $request;
  34. /** @var IConfig */
  35. private $config;
  36. /** @var ConnectionAdapter */
  37. private $connection;
  38. /** @var LoggerInterface */
  39. private $logger;
  40. /** @var IEventLogger */
  41. private $eventLogger;
  42. private ContainerInterface $appContainer;
  43. /**
  44. * @param Http $protocol the http protocol with contains all status headers
  45. * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which
  46. * runs the middleware
  47. * @param ControllerMethodReflector $reflector the reflector that is used to inject
  48. * the arguments for the controller
  49. * @param IRequest $request the incoming request
  50. * @param IConfig $config
  51. * @param ConnectionAdapter $connection
  52. * @param LoggerInterface $logger
  53. * @param IEventLogger $eventLogger
  54. */
  55. public function __construct(Http $protocol,
  56. MiddlewareDispatcher $middlewareDispatcher,
  57. ControllerMethodReflector $reflector,
  58. IRequest $request,
  59. IConfig $config,
  60. ConnectionAdapter $connection,
  61. LoggerInterface $logger,
  62. IEventLogger $eventLogger,
  63. ContainerInterface $appContainer) {
  64. $this->protocol = $protocol;
  65. $this->middlewareDispatcher = $middlewareDispatcher;
  66. $this->reflector = $reflector;
  67. $this->request = $request;
  68. $this->config = $config;
  69. $this->connection = $connection;
  70. $this->logger = $logger;
  71. $this->eventLogger = $eventLogger;
  72. $this->appContainer = $appContainer;
  73. }
  74. /**
  75. * Handles a request and calls the dispatcher on the controller
  76. * @param Controller $controller the controller which will be called
  77. * @param string $methodName the method name which will be called on
  78. * the controller
  79. * @return array $array[0] contains a string with the http main header,
  80. * $array[1] contains headers in the form: $key => value, $array[2] contains
  81. * the response output
  82. * @throws \Exception
  83. */
  84. public function dispatch(Controller $controller, string $methodName): array {
  85. $out = [null, [], null];
  86. try {
  87. // prefill reflector with everything that's needed for the
  88. // middlewares
  89. $this->reflector->reflect($controller, $methodName);
  90. $this->middlewareDispatcher->beforeController($controller,
  91. $methodName);
  92. $databaseStatsBefore = [];
  93. if ($this->config->getSystemValueBool('debug', false)) {
  94. $databaseStatsBefore = $this->connection->getInner()->getStats();
  95. }
  96. $response = $this->executeController($controller, $methodName);
  97. if (!empty($databaseStatsBefore)) {
  98. $databaseStatsAfter = $this->connection->getInner()->getStats();
  99. $numBuilt = $databaseStatsAfter['built'] - $databaseStatsBefore['built'];
  100. $numExecuted = $databaseStatsAfter['executed'] - $databaseStatsBefore['executed'];
  101. if ($numBuilt > 50) {
  102. $this->logger->debug('Controller {class}::{method} created {count} QueryBuilder objects, please check if they are created inside a loop by accident.', [
  103. 'class' => get_class($controller),
  104. 'method' => $methodName,
  105. 'count' => $numBuilt,
  106. ]);
  107. }
  108. if ($numExecuted > 100) {
  109. $this->logger->warning('Controller {class}::{method} executed {count} queries.', [
  110. 'class' => get_class($controller),
  111. 'method' => $methodName,
  112. 'count' => $numExecuted,
  113. ]);
  114. }
  115. }
  116. // if an exception appears, the middleware checks if it can handle the
  117. // exception and creates a response. If no response is created, it is
  118. // assumed that there's no middleware who can handle it and the error is
  119. // thrown again
  120. } catch (\Exception $exception) {
  121. $response = $this->middlewareDispatcher->afterException(
  122. $controller, $methodName, $exception);
  123. } catch (\Throwable $throwable) {
  124. $exception = new \Exception($throwable->getMessage() . ' in file \'' . $throwable->getFile() . '\' line ' . $throwable->getLine(), $throwable->getCode(), $throwable);
  125. $response = $this->middlewareDispatcher->afterException(
  126. $controller, $methodName, $exception);
  127. }
  128. $response = $this->middlewareDispatcher->afterController(
  129. $controller, $methodName, $response);
  130. // depending on the cache object the headers need to be changed
  131. $out[0] = $this->protocol->getStatusHeader($response->getStatus());
  132. $out[1] = array_merge($response->getHeaders());
  133. $out[2] = $response->getCookies();
  134. $out[3] = $this->middlewareDispatcher->beforeOutput(
  135. $controller, $methodName, $response->render()
  136. );
  137. $out[4] = $response;
  138. return $out;
  139. }
  140. /**
  141. * Uses the reflected parameters, types and request parameters to execute
  142. * the controller
  143. * @param Controller $controller the controller to be executed
  144. * @param string $methodName the method on the controller that should be executed
  145. * @return Response
  146. */
  147. private function executeController(Controller $controller, string $methodName): Response {
  148. $arguments = [];
  149. // valid types that will be cast
  150. $types = ['int', 'integer', 'bool', 'boolean', 'float', 'double'];
  151. foreach ($this->reflector->getParameters() as $param => $default) {
  152. // try to get the parameter from the request object and cast
  153. // it to the type annotated in the @param annotation
  154. $value = $this->request->getParam($param, $default);
  155. $type = $this->reflector->getType($param);
  156. // Converted the string `'false'` to false when the controller wants a boolean
  157. if ($value === 'false' && ($type === 'bool' || $type === 'boolean')) {
  158. $value = false;
  159. } elseif ($value !== null && \in_array($type, $types, true)) {
  160. settype($value, $type);
  161. $this->ensureParameterValueSatisfiesRange($param, $value);
  162. } elseif ($value === null && $type !== null && $this->appContainer->has($type)) {
  163. $value = $this->appContainer->get($type);
  164. }
  165. $arguments[] = $value;
  166. }
  167. $this->eventLogger->start('controller:' . get_class($controller) . '::' . $methodName, 'App framework controller execution');
  168. $response = \call_user_func_array([$controller, $methodName], $arguments);
  169. $this->eventLogger->end('controller:' . get_class($controller) . '::' . $methodName);
  170. if (!($response instanceof Response)) {
  171. $this->logger->debug($controller::class . '::' . $methodName . ' returned raw data. Please wrap it in a Response or one of it\'s inheritors.');
  172. }
  173. // format response
  174. if ($response instanceof DataResponse || !($response instanceof Response)) {
  175. // get format from the url format or request format parameter
  176. $format = $this->request->getParam('format');
  177. // if none is given try the first Accept header
  178. if ($format === null) {
  179. $headers = $this->request->getHeader('Accept');
  180. $format = $controller->getResponderByHTTPHeader($headers, null);
  181. }
  182. if ($format !== null) {
  183. $response = $controller->buildResponse($response, $format);
  184. } else {
  185. $response = $controller->buildResponse($response);
  186. }
  187. }
  188. return $response;
  189. }
  190. /**
  191. * @psalm-param mixed $value
  192. * @throws ParameterOutOfRangeException
  193. */
  194. private function ensureParameterValueSatisfiesRange(string $param, $value): void {
  195. $rangeInfo = $this->reflector->getRange($param);
  196. if ($rangeInfo) {
  197. if ($value < $rangeInfo['min'] || $value > $rangeInfo['max']) {
  198. throw new ParameterOutOfRangeException(
  199. $param,
  200. $value,
  201. $rangeInfo['min'],
  202. $rangeInfo['max'],
  203. );
  204. }
  205. }
  206. }
  207. }