Router.php 16 KB

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