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.

229 lines
7.6 KiB

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