Router.php 16 KB

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