You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Dispatcher.php 7.7KB

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