Router.php 16 KB

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