Router.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Route;
  8. use DirectoryIterator;
  9. use OC\AppFramework\Routing\RouteParser;
  10. use OCP\App\AppPathNotFoundException;
  11. use OCP\App\IAppManager;
  12. use OCP\AppFramework\App;
  13. use OCP\AppFramework\Http\Attribute\Route as RouteAttribute;
  14. use OCP\Diagnostics\IEventLogger;
  15. use OCP\IConfig;
  16. use OCP\IRequest;
  17. use OCP\Route\IRouter;
  18. use OCP\Util;
  19. use Psr\Container\ContainerInterface;
  20. use Psr\Log\LoggerInterface;
  21. use ReflectionAttribute;
  22. use ReflectionClass;
  23. use ReflectionException;
  24. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  25. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  26. use Symfony\Component\Routing\Generator\UrlGenerator;
  27. use Symfony\Component\Routing\Matcher\UrlMatcher;
  28. use Symfony\Component\Routing\RequestContext;
  29. use Symfony\Component\Routing\RouteCollection;
  30. class Router implements IRouter {
  31. /** @var RouteCollection[] */
  32. protected $collections = [];
  33. /** @var null|RouteCollection */
  34. protected $collection = null;
  35. /** @var null|string */
  36. protected $collectionName = null;
  37. /** @var null|RouteCollection */
  38. protected $root = null;
  39. /** @var null|UrlGenerator */
  40. protected $generator = null;
  41. /** @var string[]|null */
  42. protected $routingFiles;
  43. /** @var bool */
  44. protected $loaded = false;
  45. /** @var array */
  46. protected $loadedApps = [];
  47. /** @var RequestContext */
  48. protected $context;
  49. public function __construct(
  50. protected LoggerInterface $logger,
  51. IRequest $request,
  52. private IConfig $config,
  53. private IEventLogger $eventLogger,
  54. private ContainerInterface $container,
  55. private IAppManager $appManager,
  56. ) {
  57. $baseUrl = \OC::$WEBROOT;
  58. if (!($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) {
  59. $baseUrl .= '/index.php';
  60. }
  61. if (!\OC::$CLI && isset($_SERVER['REQUEST_METHOD'])) {
  62. $method = $_SERVER['REQUEST_METHOD'];
  63. } else {
  64. $method = 'GET';
  65. }
  66. $host = $request->getServerHost();
  67. $schema = $request->getServerProtocol();
  68. $this->context = new RequestContext($baseUrl, $method, $host, $schema);
  69. // TODO cache
  70. $this->root = $this->getCollection('root');
  71. }
  72. /**
  73. * Get the files to load the routes from
  74. *
  75. * @return string[]
  76. */
  77. public function getRoutingFiles() {
  78. if ($this->routingFiles === null) {
  79. $this->routingFiles = [];
  80. foreach (\OC_APP::getEnabledApps() as $app) {
  81. try {
  82. $appPath = $this->appManager->getAppPath($app);
  83. $file = $appPath . '/appinfo/routes.php';
  84. if (file_exists($file)) {
  85. $this->routingFiles[$app] = $file;
  86. }
  87. } catch (AppPathNotFoundException) {
  88. /* ignore */
  89. }
  90. }
  91. }
  92. return $this->routingFiles;
  93. }
  94. /**
  95. * Loads the routes
  96. *
  97. * @param null|string $app
  98. */
  99. public function loadRoutes($app = null) {
  100. if (is_string($app)) {
  101. $app = $this->appManager->cleanAppId($app);
  102. }
  103. $requestedApp = $app;
  104. if ($this->loaded) {
  105. return;
  106. }
  107. $this->eventLogger->start('route:load:' . $requestedApp, 'Loading Routes for ' . $requestedApp);
  108. if (is_null($app)) {
  109. $this->loaded = true;
  110. $routingFiles = $this->getRoutingFiles();
  111. foreach (\OC_App::getEnabledApps() as $enabledApp) {
  112. $this->loadAttributeRoutes($enabledApp);
  113. }
  114. } else {
  115. if (isset($this->loadedApps[$app])) {
  116. return;
  117. }
  118. try {
  119. $appPath = $this->appManager->getAppPath($app);
  120. $file = $appPath . '/appinfo/routes.php';
  121. if (file_exists($file)) {
  122. $routingFiles = [$app => $file];
  123. } else {
  124. $routingFiles = [];
  125. }
  126. } catch (AppPathNotFoundException) {
  127. $routingFiles = [];
  128. }
  129. if ($this->appManager->isEnabledForUser($app)) {
  130. $this->loadAttributeRoutes($app);
  131. }
  132. }
  133. foreach ($routingFiles as $app => $file) {
  134. if (!isset($this->loadedApps[$app])) {
  135. if (!\OC_App::isAppLoaded($app)) {
  136. // app MUST be loaded before app routes
  137. // try again next time loadRoutes() is called
  138. $this->loaded = false;
  139. continue;
  140. }
  141. $this->loadedApps[$app] = true;
  142. $this->useCollection($app);
  143. $this->requireRouteFile($file, $app);
  144. $collection = $this->getCollection($app);
  145. $this->root->addCollection($collection);
  146. // Also add the OCS collection
  147. $collection = $this->getCollection($app.'.ocs');
  148. $collection->addPrefix('/ocsapp');
  149. $this->root->addCollection($collection);
  150. }
  151. }
  152. if (!isset($this->loadedApps['core'])) {
  153. $this->loadedApps['core'] = true;
  154. $this->useCollection('root');
  155. $this->setupRoutes($this->getAttributeRoutes('core'), 'core');
  156. require_once __DIR__ . '/../../../core/routes.php';
  157. // Also add the OCS collection
  158. $collection = $this->getCollection('root.ocs');
  159. $collection->addPrefix('/ocsapp');
  160. $this->root->addCollection($collection);
  161. }
  162. if ($this->loaded) {
  163. $collection = $this->getCollection('ocs');
  164. $collection->addPrefix('/ocs');
  165. $this->root->addCollection($collection);
  166. }
  167. $this->eventLogger->end('route:load:' . $requestedApp);
  168. }
  169. /**
  170. * @param string $name
  171. * @return \Symfony\Component\Routing\RouteCollection
  172. */
  173. protected function getCollection($name) {
  174. if (!isset($this->collections[$name])) {
  175. $this->collections[$name] = new RouteCollection();
  176. }
  177. return $this->collections[$name];
  178. }
  179. /**
  180. * Sets the collection to use for adding routes
  181. *
  182. * @param string $name Name of the collection to use.
  183. * @return void
  184. */
  185. public function useCollection($name) {
  186. $this->collection = $this->getCollection($name);
  187. $this->collectionName = $name;
  188. }
  189. /**
  190. * returns the current collection name in use for adding routes
  191. *
  192. * @return string the collection name
  193. */
  194. public function getCurrentCollection() {
  195. return $this->collectionName;
  196. }
  197. /**
  198. * Create a \OC\Route\Route.
  199. *
  200. * @param string $name Name of the route to create.
  201. * @param string $pattern The pattern to match
  202. * @param array $defaults An array of default parameter values
  203. * @param array $requirements An array of requirements for parameters (regexes)
  204. * @return \OC\Route\Route
  205. */
  206. public function create($name,
  207. $pattern,
  208. array $defaults = [],
  209. array $requirements = []) {
  210. $route = new Route($pattern, $defaults, $requirements);
  211. $this->collection->add($name, $route);
  212. return $route;
  213. }
  214. /**
  215. * Find the route matching $url
  216. *
  217. * @param string $url The url to find
  218. * @throws \Exception
  219. * @return array
  220. */
  221. public function findMatchingRoute(string $url): array {
  222. $this->eventLogger->start('route:match', 'Match route');
  223. if (str_starts_with($url, '/apps/')) {
  224. // empty string / 'apps' / $app / rest of the route
  225. [, , $app,] = explode('/', $url, 4);
  226. $app = $this->appManager->cleanAppId($app);
  227. \OC::$REQUESTEDAPP = $app;
  228. $this->loadRoutes($app);
  229. } elseif (str_starts_with($url, '/ocsapp/apps/')) {
  230. // empty string / 'ocsapp' / 'apps' / $app / rest of the route
  231. [, , , $app,] = explode('/', $url, 5);
  232. $app = $this->appManager->cleanAppId($app);
  233. \OC::$REQUESTEDAPP = $app;
  234. $this->loadRoutes($app);
  235. } elseif (str_starts_with($url, '/settings/')) {
  236. $this->loadRoutes('settings');
  237. } elseif (str_starts_with($url, '/core/')) {
  238. \OC::$REQUESTEDAPP = $url;
  239. if (!$this->config->getSystemValueBool('maintenance') && !Util::needUpgrade()) {
  240. \OC_App::loadApps();
  241. }
  242. $this->loadRoutes('core');
  243. } else {
  244. $this->loadRoutes();
  245. }
  246. $matcher = new UrlMatcher($this->root, $this->context);
  247. try {
  248. $parameters = $matcher->match($url);
  249. } catch (ResourceNotFoundException $e) {
  250. if (!str_ends_with($url, '/')) {
  251. // We allow links to apps/files? for backwards compatibility reasons
  252. // However, since Symfony does not allow empty route names, the route
  253. // we need to match is '/', so we need to append the '/' here.
  254. try {
  255. $parameters = $matcher->match($url . '/');
  256. } catch (ResourceNotFoundException $newException) {
  257. // If we still didn't match a route, we throw the original exception
  258. throw $e;
  259. }
  260. } else {
  261. throw $e;
  262. }
  263. }
  264. $this->eventLogger->end('route:match');
  265. return $parameters;
  266. }
  267. /**
  268. * Find and execute the route matching $url
  269. *
  270. * @param string $url The url to find
  271. * @throws \Exception
  272. * @return void
  273. */
  274. public function match($url) {
  275. $parameters = $this->findMatchingRoute($url);
  276. $this->eventLogger->start('route:run', 'Run route');
  277. if (isset($parameters['caller'])) {
  278. $caller = $parameters['caller'];
  279. unset($parameters['caller']);
  280. unset($parameters['action']);
  281. $application = $this->getApplicationClass($caller[0]);
  282. \OC\AppFramework\App::main($caller[1], $caller[2], $application->getContainer(), $parameters);
  283. } elseif (isset($parameters['action'])) {
  284. $action = $parameters['action'];
  285. if (!is_callable($action)) {
  286. throw new \Exception('not a callable action');
  287. }
  288. unset($parameters['action']);
  289. unset($parameters['caller']);
  290. $this->eventLogger->start('route:run:call', 'Run callable route');
  291. call_user_func($action, $parameters);
  292. $this->eventLogger->end('route:run:call');
  293. } elseif (isset($parameters['file'])) {
  294. include $parameters['file'];
  295. } else {
  296. throw new \Exception('no action available');
  297. }
  298. $this->eventLogger->end('route:run');
  299. }
  300. /**
  301. * Get the url generator
  302. *
  303. * @return \Symfony\Component\Routing\Generator\UrlGenerator
  304. *
  305. */
  306. public function getGenerator() {
  307. if ($this->generator !== null) {
  308. return $this->generator;
  309. }
  310. return $this->generator = new UrlGenerator($this->root, $this->context);
  311. }
  312. /**
  313. * Generate url based on $name and $parameters
  314. *
  315. * @param string $name Name of the route to use.
  316. * @param array $parameters Parameters for the route
  317. * @param bool $absolute
  318. * @return string
  319. */
  320. public function generate($name,
  321. $parameters = [],
  322. $absolute = false) {
  323. $referenceType = UrlGenerator::ABSOLUTE_URL;
  324. if ($absolute === false) {
  325. $referenceType = UrlGenerator::ABSOLUTE_PATH;
  326. }
  327. /*
  328. * The route name has to be lowercase, for symfony to match it correctly.
  329. * This is required because smyfony allows mixed casing for controller names in the routes.
  330. * To avoid breaking all the existing route names, registering and matching will only use the lowercase names.
  331. * This is also safe on the PHP side because class and method names collide regardless of the casing.
  332. */
  333. $name = strtolower($name);
  334. $name = $this->fixLegacyRootName($name);
  335. if (str_contains($name, '.')) {
  336. [$appName, $other] = explode('.', $name, 3);
  337. // OCS routes are prefixed with "ocs."
  338. if ($appName === 'ocs') {
  339. $appName = $other;
  340. }
  341. $this->loadRoutes($appName);
  342. try {
  343. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  344. } catch (RouteNotFoundException $e) {
  345. }
  346. }
  347. // Fallback load all routes
  348. $this->loadRoutes();
  349. try {
  350. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  351. } catch (RouteNotFoundException $e) {
  352. $this->logger->info($e->getMessage(), ['exception' => $e]);
  353. return '';
  354. }
  355. }
  356. protected function fixLegacyRootName(string $routeName): string {
  357. if ($routeName === 'files.viewcontroller.showfile') {
  358. return 'files.view.showfile';
  359. }
  360. if ($routeName === 'files_sharing.sharecontroller.showshare') {
  361. return 'files_sharing.share.showshare';
  362. }
  363. if ($routeName === 'files_sharing.sharecontroller.showauthenticate') {
  364. return 'files_sharing.share.showauthenticate';
  365. }
  366. if ($routeName === 'files_sharing.sharecontroller.authenticate') {
  367. return 'files_sharing.share.authenticate';
  368. }
  369. if ($routeName === 'files_sharing.sharecontroller.downloadshare') {
  370. return 'files_sharing.share.downloadshare';
  371. }
  372. if ($routeName === 'files_sharing.publicpreview.directlink') {
  373. return 'files_sharing.publicpreview.directlink';
  374. }
  375. if ($routeName === 'cloud_federation_api.requesthandlercontroller.addshare') {
  376. return 'cloud_federation_api.requesthandler.addshare';
  377. }
  378. if ($routeName === 'cloud_federation_api.requesthandlercontroller.receivenotification') {
  379. return 'cloud_federation_api.requesthandler.receivenotification';
  380. }
  381. return $routeName;
  382. }
  383. private function loadAttributeRoutes(string $app): void {
  384. $routes = $this->getAttributeRoutes($app);
  385. if (count($routes) === 0) {
  386. return;
  387. }
  388. $this->useCollection($app);
  389. $this->setupRoutes($routes, $app);
  390. $collection = $this->getCollection($app);
  391. $this->root->addCollection($collection);
  392. // Also add the OCS collection
  393. $collection = $this->getCollection($app . '.ocs');
  394. $collection->addPrefix('/ocsapp');
  395. $this->root->addCollection($collection);
  396. }
  397. /**
  398. * @throws ReflectionException
  399. */
  400. private function getAttributeRoutes(string $app): array {
  401. $routes = [];
  402. if ($app === 'core') {
  403. $appControllerPath = __DIR__ . '/../../../core/Controller';
  404. $appNameSpace = 'OC\\Core';
  405. } else {
  406. try {
  407. $appControllerPath = $this->appManager->getAppPath($app) . '/lib/Controller';
  408. } catch (AppPathNotFoundException) {
  409. return [];
  410. }
  411. $appNameSpace = App::buildAppNamespace($app);
  412. }
  413. if (!file_exists($appControllerPath)) {
  414. return [];
  415. }
  416. $dir = new DirectoryIterator($appControllerPath);
  417. foreach ($dir as $file) {
  418. if (!str_ends_with($file->getPathname(), 'Controller.php')) {
  419. continue;
  420. }
  421. $class = new ReflectionClass($appNameSpace . '\\Controller\\' . basename($file->getPathname(), '.php'));
  422. foreach ($class->getMethods() as $method) {
  423. foreach ($method->getAttributes(RouteAttribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
  424. $route = $attribute->newInstance();
  425. $serializedRoute = $route->toArray();
  426. // Remove 'Controller' suffix
  427. $serializedRoute['name'] = substr($class->getShortName(), 0, -10) . '#' . $method->getName();
  428. $key = $route->getType();
  429. $routes[$key] ??= [];
  430. $routes[$key][] = $serializedRoute;
  431. }
  432. }
  433. }
  434. return $routes;
  435. }
  436. /**
  437. * To isolate the variable scope used inside the $file it is required in it's own method
  438. *
  439. * @param string $file the route file location to include
  440. * @param string $appName
  441. */
  442. private function requireRouteFile($file, $appName) {
  443. $this->setupRoutes(include_once $file, $appName);
  444. }
  445. /**
  446. * If a routes.php file returns an array, try to set up the application and
  447. * register the routes for the app. The application class will be chosen by
  448. * camelcasing the appname, e.g.: my_app will be turned into
  449. * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
  450. * App will be initialized. This makes it optional to ship an
  451. * appinfo/application.php by using the built in query resolver
  452. *
  453. * @param array $routes the application routes
  454. * @param string $appName the name of the app.
  455. */
  456. private function setupRoutes($routes, $appName) {
  457. if (is_array($routes)) {
  458. $routeParser = new RouteParser();
  459. $defaultRoutes = $routeParser->parseDefaultRoutes($routes, $appName);
  460. $ocsRoutes = $routeParser->parseOCSRoutes($routes, $appName);
  461. $this->root->addCollection($defaultRoutes);
  462. $ocsRoutes->addPrefix('/ocsapp');
  463. $this->root->addCollection($ocsRoutes);
  464. }
  465. }
  466. private function getApplicationClass(string $appName) {
  467. $appNameSpace = App::buildAppNamespace($appName);
  468. $applicationClassName = $appNameSpace . '\\AppInfo\\Application';
  469. if (class_exists($applicationClassName)) {
  470. $application = $this->container->get($applicationClassName);
  471. } else {
  472. $application = new App($appName);
  473. }
  474. return $application;
  475. }
  476. }