App.php 8.7 KB

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