App.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\AppFramework;
  31. use OC\AppFramework\DependencyInjection\DIContainer;
  32. use OC\AppFramework\Http\Dispatcher;
  33. use OC\AppFramework\Http\Request;
  34. use OCP\Profiler\IProfiler;
  35. use OC\Profiler\RoutingDataCollector;
  36. use OCP\AppFramework\QueryException;
  37. use OCP\AppFramework\Http;
  38. use OCP\AppFramework\Http\ICallbackResponse;
  39. use OCP\AppFramework\Http\IOutput;
  40. use OCP\Diagnostics\IEventLogger;
  41. use OCP\HintException;
  42. use OCP\IRequest;
  43. /**
  44. * Entry point for every request in your app. You can consider this as your
  45. * public static void main() method
  46. *
  47. * Handles all the dependency injection, controllers and output flow
  48. */
  49. class App {
  50. /** @var string[] */
  51. private static $nameSpaceCache = [];
  52. /**
  53. * Turns an app id into a namespace by either reading the appinfo.xml's
  54. * namespace tag or uppercasing the appid's first letter
  55. * @param string $appId the app id
  56. * @param string $topNamespace the namespace which should be prepended to
  57. * the transformed app id, defaults to OCA\
  58. * @return string the starting namespace for the app
  59. */
  60. public static function buildAppNamespace(string $appId, string $topNamespace = 'OCA\\'): string {
  61. // Hit the cache!
  62. if (isset(self::$nameSpaceCache[$appId])) {
  63. return $topNamespace . self::$nameSpaceCache[$appId];
  64. }
  65. $appInfo = \OC_App::getAppInfo($appId);
  66. if (isset($appInfo['namespace'])) {
  67. self::$nameSpaceCache[$appId] = trim($appInfo['namespace']);
  68. } else {
  69. if ($appId !== 'spreed') {
  70. // if the tag is not found, fall back to uppercasing the first letter
  71. self::$nameSpaceCache[$appId] = ucfirst($appId);
  72. } else {
  73. // For the Talk app (appid spreed) the above fallback doesn't work.
  74. // This leads to a problem when trying to install it freshly,
  75. // because the apps namespace is already registered before the
  76. // app is downloaded from the appstore, because of the hackish
  77. // global route index.php/call/{token} which is registered via
  78. // the core/routes.php so it does not have the app namespace.
  79. // @ref https://github.com/nextcloud/server/pull/19433
  80. self::$nameSpaceCache[$appId] = 'Talk';
  81. }
  82. }
  83. return $topNamespace . self::$nameSpaceCache[$appId];
  84. }
  85. public static function getAppIdForClass(string $className, string $topNamespace = 'OCA\\'): ?string {
  86. if (strpos($className, $topNamespace) !== 0) {
  87. return null;
  88. }
  89. foreach (self::$nameSpaceCache as $appId => $namespace) {
  90. if (strpos($className, $topNamespace . $namespace . '\\') === 0) {
  91. return $appId;
  92. }
  93. }
  94. return null;
  95. }
  96. /**
  97. * Shortcut for calling a controller method and printing the result
  98. *
  99. * @param string $controllerName the name of the controller under which it is
  100. * stored in the DI container
  101. * @param string $methodName the method that you want to call
  102. * @param DIContainer $container an instance of a pimple container.
  103. * @param array $urlParams list of URL parameters (optional)
  104. * @throws HintException
  105. */
  106. public static function main(string $controllerName, string $methodName, DIContainer $container, array $urlParams = null) {
  107. /** @var IProfiler $profiler */
  108. $profiler = $container->get(IProfiler::class);
  109. $eventLogger = $container->get(IEventLogger::class);
  110. // Disable profiler on the profiler UI
  111. $profiler->setEnabled($profiler->isEnabled() && !is_null($urlParams) && isset($urlParams['_route']) && !str_starts_with($urlParams['_route'], 'profiler.'));
  112. if ($profiler->isEnabled()) {
  113. \OC::$server->get(IEventLogger::class)->activate();
  114. $profiler->add(new RoutingDataCollector($container['AppName'], $controllerName, $methodName));
  115. }
  116. $eventLogger->start('app:controller:params', 'Gather controller parameters');
  117. if (!is_null($urlParams)) {
  118. /** @var Request $request */
  119. $request = $container->get(IRequest::class);
  120. $request->setUrlParameters($urlParams);
  121. } elseif (isset($container['urlParams']) && !is_null($container['urlParams'])) {
  122. /** @var Request $request */
  123. $request = $container->get(IRequest::class);
  124. $request->setUrlParameters($container['urlParams']);
  125. }
  126. $appName = $container['AppName'];
  127. $eventLogger->end('app:controller:params');
  128. $eventLogger->start('app:controller:load', 'Load app controller');
  129. // first try $controllerName then go for \OCA\AppName\Controller\$controllerName
  130. try {
  131. $controller = $container->get($controllerName);
  132. } catch (QueryException $e) {
  133. if (strpos($controllerName, '\\Controller\\') !== false) {
  134. // This is from a global registered app route that is not enabled.
  135. [/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3);
  136. throw new HintException('App ' . strtolower($app) . ' is not enabled');
  137. }
  138. if ($appName === 'core') {
  139. $appNameSpace = 'OC\\Core';
  140. } else {
  141. $appNameSpace = self::buildAppNamespace($appName);
  142. }
  143. $controllerName = $appNameSpace . '\\Controller\\' . $controllerName;
  144. $controller = $container->query($controllerName);
  145. }
  146. $eventLogger->end('app:controller:load');
  147. $eventLogger->start('app:controller:dispatcher', 'Initialize dispatcher and pre-middleware');
  148. // initialize the dispatcher and run all the middleware before the controller
  149. /** @var Dispatcher $dispatcher */
  150. $dispatcher = $container['Dispatcher'];
  151. $eventLogger->end('app:controller:dispatcher');
  152. $eventLogger->start('app:controller:run', 'Run app controller');
  153. [
  154. $httpHeaders,
  155. $responseHeaders,
  156. $responseCookies,
  157. $output,
  158. $response
  159. ] = $dispatcher->dispatch($controller, $methodName);
  160. $eventLogger->end('app:controller:run');
  161. $io = $container[IOutput::class];
  162. if ($profiler->isEnabled()) {
  163. $eventLogger->end('runtime');
  164. $profile = $profiler->collect($container->get(IRequest::class), $response);
  165. $profiler->saveProfile($profile);
  166. $io->setHeader('X-Debug-Token:' . $profile->getToken());
  167. $io->setHeader('Server-Timing: token;desc="' . $profile->getToken() . '"');
  168. }
  169. if (!is_null($httpHeaders)) {
  170. $io->setHeader($httpHeaders);
  171. }
  172. foreach ($responseHeaders as $name => $value) {
  173. $io->setHeader($name . ': ' . $value);
  174. }
  175. foreach ($responseCookies as $name => $value) {
  176. $expireDate = null;
  177. if ($value['expireDate'] instanceof \DateTime) {
  178. $expireDate = $value['expireDate']->getTimestamp();
  179. }
  180. $sameSite = $value['sameSite'] ?? 'Lax';
  181. $io->setCookie(
  182. $name,
  183. $value['value'],
  184. $expireDate,
  185. $container->getServer()->getWebRoot(),
  186. null,
  187. $container->getServer()->getRequest()->getServerProtocol() === 'https',
  188. true,
  189. $sameSite
  190. );
  191. }
  192. /*
  193. * Status 204 does not have a body and no Content Length
  194. * Status 304 does not have a body and does not need a Content Length
  195. * https://tools.ietf.org/html/rfc7230#section-3.3
  196. * https://tools.ietf.org/html/rfc7230#section-3.3.2
  197. */
  198. $emptyResponse = false;
  199. if (preg_match('/^HTTP\/\d\.\d (\d{3}) .*$/', $httpHeaders, $matches)) {
  200. $status = (int)$matches[1];
  201. if ($status === Http::STATUS_NO_CONTENT || $status === Http::STATUS_NOT_MODIFIED) {
  202. $emptyResponse = true;
  203. }
  204. }
  205. if (!$emptyResponse) {
  206. if ($response instanceof ICallbackResponse) {
  207. $response->callback($io);
  208. } elseif (!is_null($output)) {
  209. $io->setHeader('Content-Length: ' . strlen($output));
  210. $io->setOutput($output);
  211. }
  212. }
  213. }
  214. /**
  215. * Shortcut for calling a controller method and printing the result.
  216. * Similar to App:main except that no headers will be sent.
  217. *
  218. * @param string $controllerName the name of the controller under which it is
  219. * stored in the DI container
  220. * @param string $methodName the method that you want to call
  221. * @param array $urlParams an array with variables extracted from the routes
  222. * @param DIContainer $container an instance of a pimple container.
  223. */
  224. public static function part(string $controllerName, string $methodName, array $urlParams,
  225. DIContainer $container) {
  226. $container['urlParams'] = $urlParams;
  227. $controller = $container[$controllerName];
  228. $dispatcher = $container['Dispatcher'];
  229. [, , $output] = $dispatcher->dispatch($controller, $methodName);
  230. return $output;
  231. }
  232. }