Router.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 = \OC_App::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. $appPath = \OC_App::getAppPath($app);
  119. $file = $appPath . '/appinfo/routes.php';
  120. if ($appPath !== false && file_exists($file)) {
  121. $routingFiles = [$app => $file];
  122. } else {
  123. $routingFiles = [];
  124. }
  125. if ($this->appManager->isEnabledForUser($app)) {
  126. $this->loadAttributeRoutes($app);
  127. }
  128. }
  129. foreach ($routingFiles as $app => $file) {
  130. if (!isset($this->loadedApps[$app])) {
  131. if (!\OC_App::isAppLoaded($app)) {
  132. // app MUST be loaded before app routes
  133. // try again next time loadRoutes() is called
  134. $this->loaded = false;
  135. continue;
  136. }
  137. $this->loadedApps[$app] = true;
  138. $this->useCollection($app);
  139. $this->requireRouteFile($file, $app);
  140. $collection = $this->getCollection($app);
  141. $this->root->addCollection($collection);
  142. // Also add the OCS collection
  143. $collection = $this->getCollection($app.'.ocs');
  144. $collection->addPrefix('/ocsapp');
  145. $this->root->addCollection($collection);
  146. }
  147. }
  148. if (!isset($this->loadedApps['core'])) {
  149. $this->loadedApps['core'] = true;
  150. $this->useCollection('root');
  151. $this->setupRoutes($this->getAttributeRoutes('core'), 'core');
  152. require_once __DIR__ . '/../../../core/routes.php';
  153. // Also add the OCS collection
  154. $collection = $this->getCollection('root.ocs');
  155. $collection->addPrefix('/ocsapp');
  156. $this->root->addCollection($collection);
  157. }
  158. if ($this->loaded) {
  159. $collection = $this->getCollection('ocs');
  160. $collection->addPrefix('/ocs');
  161. $this->root->addCollection($collection);
  162. }
  163. $this->eventLogger->end('route:load:' . $requestedApp);
  164. }
  165. /**
  166. * @param string $name
  167. * @return \Symfony\Component\Routing\RouteCollection
  168. */
  169. protected function getCollection($name) {
  170. if (!isset($this->collections[$name])) {
  171. $this->collections[$name] = new RouteCollection();
  172. }
  173. return $this->collections[$name];
  174. }
  175. /**
  176. * Sets the collection to use for adding routes
  177. *
  178. * @param string $name Name of the collection to use.
  179. * @return void
  180. */
  181. public function useCollection($name) {
  182. $this->collection = $this->getCollection($name);
  183. $this->collectionName = $name;
  184. }
  185. /**
  186. * returns the current collection name in use for adding routes
  187. *
  188. * @return string the collection name
  189. */
  190. public function getCurrentCollection() {
  191. return $this->collectionName;
  192. }
  193. /**
  194. * Create a \OC\Route\Route.
  195. *
  196. * @param string $name Name of the route to create.
  197. * @param string $pattern The pattern to match
  198. * @param array $defaults An array of default parameter values
  199. * @param array $requirements An array of requirements for parameters (regexes)
  200. * @return \OC\Route\Route
  201. */
  202. public function create($name,
  203. $pattern,
  204. array $defaults = [],
  205. array $requirements = []) {
  206. $route = new Route($pattern, $defaults, $requirements);
  207. $this->collection->add($name, $route);
  208. return $route;
  209. }
  210. /**
  211. * Find the route matching $url
  212. *
  213. * @param string $url The url to find
  214. * @throws \Exception
  215. * @return array
  216. */
  217. public function findMatchingRoute(string $url): array {
  218. $this->eventLogger->start('route:match', 'Match route');
  219. if (str_starts_with($url, '/apps/')) {
  220. // empty string / 'apps' / $app / rest of the route
  221. [, , $app,] = explode('/', $url, 4);
  222. $app = \OC_App::cleanAppId($app);
  223. \OC::$REQUESTEDAPP = $app;
  224. $this->loadRoutes($app);
  225. } elseif (str_starts_with($url, '/ocsapp/apps/')) {
  226. // empty string / 'ocsapp' / 'apps' / $app / rest of the route
  227. [, , , $app,] = explode('/', $url, 5);
  228. $app = \OC_App::cleanAppId($app);
  229. \OC::$REQUESTEDAPP = $app;
  230. $this->loadRoutes($app);
  231. } elseif (str_starts_with($url, '/settings/')) {
  232. $this->loadRoutes('settings');
  233. } elseif (str_starts_with($url, '/core/')) {
  234. \OC::$REQUESTEDAPP = $url;
  235. if (!$this->config->getSystemValueBool('maintenance') && !Util::needUpgrade()) {
  236. \OC_App::loadApps();
  237. }
  238. $this->loadRoutes('core');
  239. } else {
  240. $this->loadRoutes();
  241. }
  242. $matcher = new UrlMatcher($this->root, $this->context);
  243. try {
  244. $parameters = $matcher->match($url);
  245. } catch (ResourceNotFoundException $e) {
  246. if (!str_ends_with($url, '/')) {
  247. // We allow links to apps/files? for backwards compatibility reasons
  248. // However, since Symfony does not allow empty route names, the route
  249. // we need to match is '/', so we need to append the '/' here.
  250. try {
  251. $parameters = $matcher->match($url . '/');
  252. } catch (ResourceNotFoundException $newException) {
  253. // If we still didn't match a route, we throw the original exception
  254. throw $e;
  255. }
  256. } else {
  257. throw $e;
  258. }
  259. }
  260. $this->eventLogger->end('route:match');
  261. return $parameters;
  262. }
  263. /**
  264. * Find and execute the route matching $url
  265. *
  266. * @param string $url The url to find
  267. * @throws \Exception
  268. * @return void
  269. */
  270. public function match($url) {
  271. $parameters = $this->findMatchingRoute($url);
  272. $this->eventLogger->start('route:run', 'Run route');
  273. if (isset($parameters['caller'])) {
  274. $caller = $parameters['caller'];
  275. unset($parameters['caller']);
  276. unset($parameters['action']);
  277. $application = $this->getApplicationClass($caller[0]);
  278. \OC\AppFramework\App::main($caller[1], $caller[2], $application->getContainer(), $parameters);
  279. } elseif (isset($parameters['action'])) {
  280. $action = $parameters['action'];
  281. if (!is_callable($action)) {
  282. throw new \Exception('not a callable action');
  283. }
  284. unset($parameters['action']);
  285. unset($parameters['caller']);
  286. $this->eventLogger->start('route:run:call', 'Run callable route');
  287. call_user_func($action, $parameters);
  288. $this->eventLogger->end('route:run:call');
  289. } elseif (isset($parameters['file'])) {
  290. include $parameters['file'];
  291. } else {
  292. throw new \Exception('no action available');
  293. }
  294. $this->eventLogger->end('route:run');
  295. }
  296. /**
  297. * Get the url generator
  298. *
  299. * @return \Symfony\Component\Routing\Generator\UrlGenerator
  300. *
  301. */
  302. public function getGenerator() {
  303. if ($this->generator !== null) {
  304. return $this->generator;
  305. }
  306. return $this->generator = new UrlGenerator($this->root, $this->context);
  307. }
  308. /**
  309. * Generate url based on $name and $parameters
  310. *
  311. * @param string $name Name of the route to use.
  312. * @param array $parameters Parameters for the route
  313. * @param bool $absolute
  314. * @return string
  315. */
  316. public function generate($name,
  317. $parameters = [],
  318. $absolute = false) {
  319. $referenceType = UrlGenerator::ABSOLUTE_URL;
  320. if ($absolute === false) {
  321. $referenceType = UrlGenerator::ABSOLUTE_PATH;
  322. }
  323. /*
  324. * The route name has to be lowercase, for symfony to match it correctly.
  325. * This is required because smyfony allows mixed casing for controller names in the routes.
  326. * To avoid breaking all the existing route names, registering and matching will only use the lowercase names.
  327. * This is also safe on the PHP side because class and method names collide regardless of the casing.
  328. */
  329. $name = strtolower($name);
  330. $name = $this->fixLegacyRootName($name);
  331. if (str_contains($name, '.')) {
  332. [$appName, $other] = explode('.', $name, 3);
  333. // OCS routes are prefixed with "ocs."
  334. if ($appName === 'ocs') {
  335. $appName = $other;
  336. }
  337. $this->loadRoutes($appName);
  338. try {
  339. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  340. } catch (RouteNotFoundException $e) {
  341. }
  342. }
  343. // Fallback load all routes
  344. $this->loadRoutes();
  345. try {
  346. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  347. } catch (RouteNotFoundException $e) {
  348. $this->logger->info($e->getMessage(), ['exception' => $e]);
  349. return '';
  350. }
  351. }
  352. protected function fixLegacyRootName(string $routeName): string {
  353. if ($routeName === 'files.viewcontroller.showfile') {
  354. return 'files.view.showfile';
  355. }
  356. if ($routeName === 'files_sharing.sharecontroller.showshare') {
  357. return 'files_sharing.share.showshare';
  358. }
  359. if ($routeName === 'files_sharing.sharecontroller.showauthenticate') {
  360. return 'files_sharing.share.showauthenticate';
  361. }
  362. if ($routeName === 'files_sharing.sharecontroller.authenticate') {
  363. return 'files_sharing.share.authenticate';
  364. }
  365. if ($routeName === 'files_sharing.sharecontroller.downloadshare') {
  366. return 'files_sharing.share.downloadshare';
  367. }
  368. if ($routeName === 'files_sharing.publicpreview.directlink') {
  369. return 'files_sharing.publicpreview.directlink';
  370. }
  371. if ($routeName === 'cloud_federation_api.requesthandlercontroller.addshare') {
  372. return 'cloud_federation_api.requesthandler.addshare';
  373. }
  374. if ($routeName === 'cloud_federation_api.requesthandlercontroller.receivenotification') {
  375. return 'cloud_federation_api.requesthandler.receivenotification';
  376. }
  377. return $routeName;
  378. }
  379. private function loadAttributeRoutes(string $app): void {
  380. $routes = $this->getAttributeRoutes($app);
  381. if (count($routes) === 0) {
  382. return;
  383. }
  384. $this->useCollection($app);
  385. $this->setupRoutes($routes, $app);
  386. $collection = $this->getCollection($app);
  387. $this->root->addCollection($collection);
  388. // Also add the OCS collection
  389. $collection = $this->getCollection($app . '.ocs');
  390. $collection->addPrefix('/ocsapp');
  391. $this->root->addCollection($collection);
  392. }
  393. /**
  394. * @throws ReflectionException
  395. */
  396. private function getAttributeRoutes(string $app): array {
  397. $routes = [];
  398. if ($app === 'core') {
  399. $appControllerPath = __DIR__ . '/../../../core/Controller';
  400. $appNameSpace = 'OC\\Core';
  401. } else {
  402. $appControllerPath = \OC_App::getAppPath($app) . '/lib/Controller';
  403. $appNameSpace = App::buildAppNamespace($app);
  404. }
  405. if (!file_exists($appControllerPath)) {
  406. return [];
  407. }
  408. $dir = new DirectoryIterator($appControllerPath);
  409. foreach ($dir as $file) {
  410. if (!str_ends_with($file->getPathname(), 'Controller.php')) {
  411. continue;
  412. }
  413. $class = new ReflectionClass($appNameSpace . '\\Controller\\' . basename($file->getPathname(), '.php'));
  414. foreach ($class->getMethods() as $method) {
  415. foreach ($method->getAttributes(RouteAttribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
  416. $route = $attribute->newInstance();
  417. $serializedRoute = $route->toArray();
  418. // Remove 'Controller' suffix
  419. $serializedRoute['name'] = substr($class->getShortName(), 0, -10) . '#' . $method->getName();
  420. $key = $route->getType();
  421. $routes[$key] ??= [];
  422. $routes[$key][] = $serializedRoute;
  423. }
  424. }
  425. }
  426. return $routes;
  427. }
  428. /**
  429. * To isolate the variable scope used inside the $file it is required in it's own method
  430. *
  431. * @param string $file the route file location to include
  432. * @param string $appName
  433. */
  434. private function requireRouteFile($file, $appName) {
  435. $this->setupRoutes(include_once $file, $appName);
  436. }
  437. /**
  438. * If a routes.php file returns an array, try to set up the application and
  439. * register the routes for the app. The application class will be chosen by
  440. * camelcasing the appname, e.g.: my_app will be turned into
  441. * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
  442. * App will be initialized. This makes it optional to ship an
  443. * appinfo/application.php by using the built in query resolver
  444. *
  445. * @param array $routes the application routes
  446. * @param string $appName the name of the app.
  447. */
  448. private function setupRoutes($routes, $appName) {
  449. if (is_array($routes)) {
  450. $routeParser = new RouteParser();
  451. $defaultRoutes = $routeParser->parseDefaultRoutes($routes, $appName);
  452. $ocsRoutes = $routeParser->parseOCSRoutes($routes, $appName);
  453. $this->root->addCollection($defaultRoutes);
  454. $ocsRoutes->addPrefix('/ocsapp');
  455. $this->root->addCollection($ocsRoutes);
  456. }
  457. }
  458. private function getApplicationClass(string $appName) {
  459. $appNameSpace = App::buildAppNamespace($appName);
  460. $applicationClassName = $appNameSpace . '\\AppInfo\\Application';
  461. if (class_exists($applicationClassName)) {
  462. $application = $this->container->get($applicationClassName);
  463. } else {
  464. $application = new App($appName);
  465. }
  466. return $application;
  467. }
  468. }