App.php 9.1 KB

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