Router.php 15 KB

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