Dispatcher.php 8.1 KB

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