Dispatcher.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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\Response;
  39. use OCP\Diagnostics\IEventLogger;
  40. use OCP\IConfig;
  41. use OCP\IRequest;
  42. use Psr\Container\ContainerInterface;
  43. use Psr\Log\LoggerInterface;
  44. /**
  45. * Class to dispatch the request to the middleware dispatcher
  46. */
  47. class Dispatcher {
  48. /** @var MiddlewareDispatcher */
  49. private $middlewareDispatcher;
  50. /** @var Http */
  51. private $protocol;
  52. /** @var ControllerMethodReflector */
  53. private $reflector;
  54. /** @var IRequest */
  55. private $request;
  56. /** @var IConfig */
  57. private $config;
  58. /** @var ConnectionAdapter */
  59. private $connection;
  60. /** @var LoggerInterface */
  61. private $logger;
  62. /** @var IEventLogger */
  63. private $eventLogger;
  64. private ContainerInterface $appContainer;
  65. /**
  66. * @param Http $protocol the http protocol with contains all status headers
  67. * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which
  68. * runs the middleware
  69. * @param ControllerMethodReflector $reflector the reflector that is used to inject
  70. * the arguments for the controller
  71. * @param IRequest $request the incoming request
  72. * @param IConfig $config
  73. * @param ConnectionAdapter $connection
  74. * @param LoggerInterface $logger
  75. * @param IEventLogger $eventLogger
  76. */
  77. public function __construct(Http $protocol,
  78. MiddlewareDispatcher $middlewareDispatcher,
  79. ControllerMethodReflector $reflector,
  80. IRequest $request,
  81. IConfig $config,
  82. ConnectionAdapter $connection,
  83. LoggerInterface $logger,
  84. IEventLogger $eventLogger,
  85. ContainerInterface $appContainer) {
  86. $this->protocol = $protocol;
  87. $this->middlewareDispatcher = $middlewareDispatcher;
  88. $this->reflector = $reflector;
  89. $this->request = $request;
  90. $this->config = $config;
  91. $this->connection = $connection;
  92. $this->logger = $logger;
  93. $this->eventLogger = $eventLogger;
  94. $this->appContainer = $appContainer;
  95. }
  96. /**
  97. * Handles a request and calls the dispatcher on the controller
  98. * @param Controller $controller the controller which will be called
  99. * @param string $methodName the method name which will be called on
  100. * the controller
  101. * @return array $array[0] contains a string with the http main header,
  102. * $array[1] contains headers in the form: $key => value, $array[2] contains
  103. * the response output
  104. * @throws \Exception
  105. */
  106. public function dispatch(Controller $controller, string $methodName): array {
  107. $out = [null, [], null];
  108. try {
  109. // prefill reflector with everything that's needed for the
  110. // middlewares
  111. $this->reflector->reflect($controller, $methodName);
  112. $this->middlewareDispatcher->beforeController($controller,
  113. $methodName);
  114. $databaseStatsBefore = [];
  115. if ($this->config->getSystemValueBool('debug', false)) {
  116. $databaseStatsBefore = $this->connection->getInner()->getStats();
  117. }
  118. $response = $this->executeController($controller, $methodName);
  119. if (!empty($databaseStatsBefore)) {
  120. $databaseStatsAfter = $this->connection->getInner()->getStats();
  121. $numBuilt = $databaseStatsAfter['built'] - $databaseStatsBefore['built'];
  122. $numExecuted = $databaseStatsAfter['executed'] - $databaseStatsBefore['executed'];
  123. if ($numBuilt > 50) {
  124. $this->logger->debug('Controller {class}::{method} created {count} QueryBuilder objects, please check if they are created inside a loop by accident.', [
  125. 'class' => get_class($controller),
  126. 'method' => $methodName,
  127. 'count' => $numBuilt,
  128. ]);
  129. }
  130. if ($numExecuted > 100) {
  131. $this->logger->warning('Controller {class}::{method} executed {count} queries.', [
  132. 'class' => get_class($controller),
  133. 'method' => $methodName,
  134. 'count' => $numExecuted,
  135. ]);
  136. }
  137. }
  138. // if an exception appears, the middleware checks if it can handle the
  139. // exception and creates a response. If no response is created, it is
  140. // assumed that there's no middleware who can handle it and the error is
  141. // thrown again
  142. } catch (\Exception $exception) {
  143. $response = $this->middlewareDispatcher->afterException(
  144. $controller, $methodName, $exception);
  145. } catch (\Throwable $throwable) {
  146. $exception = new \Exception($throwable->getMessage() . ' in file \'' . $throwable->getFile() . '\' line ' . $throwable->getLine(), $throwable->getCode(), $throwable);
  147. $response = $this->middlewareDispatcher->afterException(
  148. $controller, $methodName, $exception);
  149. }
  150. $response = $this->middlewareDispatcher->afterController(
  151. $controller, $methodName, $response);
  152. // depending on the cache object the headers need to be changed
  153. $out[0] = $this->protocol->getStatusHeader($response->getStatus());
  154. $out[1] = array_merge($response->getHeaders());
  155. $out[2] = $response->getCookies();
  156. $out[3] = $this->middlewareDispatcher->beforeOutput(
  157. $controller, $methodName, $response->render()
  158. );
  159. $out[4] = $response;
  160. return $out;
  161. }
  162. /**
  163. * Uses the reflected parameters, types and request parameters to execute
  164. * the controller
  165. * @param Controller $controller the controller to be executed
  166. * @param string $methodName the method on the controller that should be executed
  167. * @return Response
  168. */
  169. private function executeController(Controller $controller, string $methodName): Response {
  170. $arguments = [];
  171. // valid types that will be casted
  172. $types = ['int', 'integer', 'bool', 'boolean', 'float', 'double'];
  173. foreach ($this->reflector->getParameters() as $param => $default) {
  174. // try to get the parameter from the request object and cast
  175. // it to the type annotated in the @param annotation
  176. $value = $this->request->getParam($param, $default);
  177. $type = $this->reflector->getType($param);
  178. // if this is submitted using GET or a POST form, 'false' should be
  179. // converted to false
  180. if (($type === 'bool' || $type === 'boolean') &&
  181. $value === 'false' &&
  182. (
  183. $this->request->method === 'GET' ||
  184. strpos($this->request->getHeader('Content-Type'),
  185. 'application/x-www-form-urlencoded') !== false
  186. )
  187. ) {
  188. $value = false;
  189. } elseif ($value !== null && \in_array($type, $types, true)) {
  190. settype($value, $type);
  191. } elseif ($value === null && $type !== null && $this->appContainer->has($type)) {
  192. $value = $this->appContainer->get($type);
  193. }
  194. $arguments[] = $value;
  195. }
  196. $this->eventLogger->start('controller:' . get_class($controller) . '::' . $methodName, 'App framework controller execution');
  197. $response = \call_user_func_array([$controller, $methodName], $arguments);
  198. $this->eventLogger->end('controller:' . get_class($controller) . '::' . $methodName);
  199. // format response
  200. if ($response instanceof DataResponse || !($response instanceof Response)) {
  201. // get format from the url format or request format parameter
  202. $format = $this->request->getParam('format');
  203. // if none is given try the first Accept header
  204. if ($format === null) {
  205. $headers = $this->request->getHeader('Accept');
  206. $format = $controller->getResponderByHTTPHeader($headers, null);
  207. }
  208. if ($format !== null) {
  209. $response = $controller->buildResponse($response, $format);
  210. } else {
  211. $response = $controller->buildResponse($response);
  212. }
  213. }
  214. return $response;
  215. }
  216. }