1
0

App.php 8.2 KB

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