Router.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OC\Route;
  34. use OC\AppFramework\Routing\RouteParser;
  35. use OCP\AppFramework\App;
  36. use OCP\Diagnostics\IEventLogger;
  37. use OCP\IConfig;
  38. use OCP\IRequest;
  39. use OCP\Route\IRouter;
  40. use OCP\Util;
  41. use Psr\Container\ContainerInterface;
  42. use Psr\Log\LoggerInterface;
  43. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  44. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  45. use Symfony\Component\Routing\Generator\UrlGenerator;
  46. use Symfony\Component\Routing\Matcher\UrlMatcher;
  47. use Symfony\Component\Routing\RequestContext;
  48. use Symfony\Component\Routing\RouteCollection;
  49. class Router implements IRouter {
  50. /** @var RouteCollection[] */
  51. protected $collections = [];
  52. /** @var null|RouteCollection */
  53. protected $collection = null;
  54. /** @var null|string */
  55. protected $collectionName = null;
  56. /** @var null|RouteCollection */
  57. protected $root = null;
  58. /** @var null|UrlGenerator */
  59. protected $generator = null;
  60. /** @var string[]|null */
  61. protected $routingFiles;
  62. /** @var bool */
  63. protected $loaded = false;
  64. /** @var array */
  65. protected $loadedApps = [];
  66. protected LoggerInterface $logger;
  67. /** @var RequestContext */
  68. protected $context;
  69. private IEventLogger $eventLogger;
  70. private IConfig $config;
  71. private ContainerInterface $container;
  72. public function __construct(
  73. LoggerInterface $logger,
  74. IRequest $request,
  75. IConfig $config,
  76. IEventLogger $eventLogger,
  77. ContainerInterface $container
  78. ) {
  79. $this->logger = $logger;
  80. $this->config = $config;
  81. $baseUrl = \OC::$WEBROOT;
  82. if (!($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) {
  83. $baseUrl .= '/index.php';
  84. }
  85. if (!\OC::$CLI && isset($_SERVER['REQUEST_METHOD'])) {
  86. $method = $_SERVER['REQUEST_METHOD'];
  87. } else {
  88. $method = 'GET';
  89. }
  90. $host = $request->getServerHost();
  91. $schema = $request->getServerProtocol();
  92. $this->context = new RequestContext($baseUrl, $method, $host, $schema);
  93. // TODO cache
  94. $this->root = $this->getCollection('root');
  95. $this->eventLogger = $eventLogger;
  96. $this->container = $container;
  97. }
  98. /**
  99. * Get the files to load the routes from
  100. *
  101. * @return string[]
  102. */
  103. public function getRoutingFiles() {
  104. if ($this->routingFiles === null) {
  105. $this->routingFiles = [];
  106. foreach (\OC_APP::getEnabledApps() as $app) {
  107. $appPath = \OC_App::getAppPath($app);
  108. if ($appPath !== false) {
  109. $file = $appPath . '/appinfo/routes.php';
  110. if (file_exists($file)) {
  111. $this->routingFiles[$app] = $file;
  112. }
  113. }
  114. }
  115. }
  116. return $this->routingFiles;
  117. }
  118. /**
  119. * Loads the routes
  120. *
  121. * @param null|string $app
  122. */
  123. public function loadRoutes($app = null) {
  124. if (is_string($app)) {
  125. $app = \OC_App::cleanAppId($app);
  126. }
  127. $requestedApp = $app;
  128. if ($this->loaded) {
  129. return;
  130. }
  131. if (is_null($app)) {
  132. $this->loaded = true;
  133. $routingFiles = $this->getRoutingFiles();
  134. } else {
  135. if (isset($this->loadedApps[$app])) {
  136. return;
  137. }
  138. $appPath = \OC_App::getAppPath($app);
  139. $file = $appPath . '/appinfo/routes.php';
  140. if ($appPath !== false && file_exists($file)) {
  141. $routingFiles = [$app => $file];
  142. } else {
  143. $routingFiles = [];
  144. }
  145. }
  146. $this->eventLogger->start('route:load:' . $requestedApp, 'Loading Routes for ' . $requestedApp);
  147. foreach ($routingFiles as $app => $file) {
  148. if (!isset($this->loadedApps[$app])) {
  149. if (!\OC_App::isAppLoaded($app)) {
  150. // app MUST be loaded before app routes
  151. // try again next time loadRoutes() is called
  152. $this->loaded = false;
  153. continue;
  154. }
  155. $this->loadedApps[$app] = true;
  156. $this->useCollection($app);
  157. $this->requireRouteFile($file, $app);
  158. $collection = $this->getCollection($app);
  159. $this->root->addCollection($collection);
  160. // Also add the OCS collection
  161. $collection = $this->getCollection($app.'.ocs');
  162. $collection->addPrefix('/ocsapp');
  163. $this->root->addCollection($collection);
  164. }
  165. }
  166. if (!isset($this->loadedApps['core'])) {
  167. $this->loadedApps['core'] = true;
  168. $this->useCollection('root');
  169. require_once __DIR__ . '/../../../core/routes.php';
  170. // Also add the OCS collection
  171. $collection = $this->getCollection('root.ocs');
  172. $collection->addPrefix('/ocsapp');
  173. $this->root->addCollection($collection);
  174. }
  175. if ($this->loaded) {
  176. $collection = $this->getCollection('ocs');
  177. $collection->addPrefix('/ocs');
  178. $this->root->addCollection($collection);
  179. }
  180. $this->eventLogger->end('route:load:' . $requestedApp);
  181. }
  182. /**
  183. * @param string $name
  184. * @return \Symfony\Component\Routing\RouteCollection
  185. */
  186. protected function getCollection($name) {
  187. if (!isset($this->collections[$name])) {
  188. $this->collections[$name] = new RouteCollection();
  189. }
  190. return $this->collections[$name];
  191. }
  192. /**
  193. * Sets the collection to use for adding routes
  194. *
  195. * @param string $name Name of the collection to use.
  196. * @return void
  197. */
  198. public function useCollection($name) {
  199. $this->collection = $this->getCollection($name);
  200. $this->collectionName = $name;
  201. }
  202. /**
  203. * returns the current collection name in use for adding routes
  204. *
  205. * @return string the collection name
  206. */
  207. public function getCurrentCollection() {
  208. return $this->collectionName;
  209. }
  210. /**
  211. * Create a \OC\Route\Route.
  212. *
  213. * @param string $name Name of the route to create.
  214. * @param string $pattern The pattern to match
  215. * @param array $defaults An array of default parameter values
  216. * @param array $requirements An array of requirements for parameters (regexes)
  217. * @return \OC\Route\Route
  218. */
  219. public function create($name,
  220. $pattern,
  221. array $defaults = [],
  222. array $requirements = []) {
  223. $route = new Route($pattern, $defaults, $requirements);
  224. $this->collection->add($name, $route);
  225. return $route;
  226. }
  227. /**
  228. * Find the route matching $url
  229. *
  230. * @param string $url The url to find
  231. * @throws \Exception
  232. * @return array
  233. */
  234. public function findMatchingRoute(string $url): array {
  235. $this->eventLogger->start('route:match', 'Match route');
  236. if (substr($url, 0, 6) === '/apps/') {
  237. // empty string / 'apps' / $app / rest of the route
  238. [, , $app,] = explode('/', $url, 4);
  239. $app = \OC_App::cleanAppId($app);
  240. \OC::$REQUESTEDAPP = $app;
  241. $this->loadRoutes($app);
  242. } elseif (substr($url, 0, 13) === '/ocsapp/apps/') {
  243. // empty string / 'ocsapp' / 'apps' / $app / rest of the route
  244. [, , , $app,] = explode('/', $url, 5);
  245. $app = \OC_App::cleanAppId($app);
  246. \OC::$REQUESTEDAPP = $app;
  247. $this->loadRoutes($app);
  248. } elseif (substr($url, 0, 10) === '/settings/') {
  249. $this->loadRoutes('settings');
  250. } elseif (substr($url, 0, 6) === '/core/') {
  251. \OC::$REQUESTEDAPP = $url;
  252. if (!$this->config->getSystemValueBool('maintenance') && !Util::needUpgrade()) {
  253. \OC_App::loadApps();
  254. }
  255. $this->loadRoutes('core');
  256. } else {
  257. $this->loadRoutes();
  258. }
  259. $matcher = new UrlMatcher($this->root, $this->context);
  260. try {
  261. $parameters = $matcher->match($url);
  262. } catch (ResourceNotFoundException $e) {
  263. if (substr($url, -1) !== '/') {
  264. // We allow links to apps/files? for backwards compatibility reasons
  265. // However, since Symfony does not allow empty route names, the route
  266. // we need to match is '/', so we need to append the '/' here.
  267. try {
  268. $parameters = $matcher->match($url . '/');
  269. } catch (ResourceNotFoundException $newException) {
  270. // If we still didn't match a route, we throw the original exception
  271. throw $e;
  272. }
  273. } else {
  274. throw $e;
  275. }
  276. }
  277. $this->eventLogger->end('route:match');
  278. return $parameters;
  279. }
  280. /**
  281. * Find and execute the route matching $url
  282. *
  283. * @param string $url The url to find
  284. * @throws \Exception
  285. * @return void
  286. */
  287. public function match($url) {
  288. $parameters = $this->findMatchingRoute($url);
  289. $this->eventLogger->start('route:run', 'Run route');
  290. if (isset($parameters['caller'])) {
  291. $caller = $parameters['caller'];
  292. unset($parameters['caller']);
  293. unset($parameters['action']);
  294. $application = $this->getApplicationClass($caller[0]);
  295. \OC\AppFramework\App::main($caller[1], $caller[2], $application->getContainer(), $parameters);
  296. } elseif (isset($parameters['action'])) {
  297. $action = $parameters['action'];
  298. if (!is_callable($action)) {
  299. throw new \Exception('not a callable action');
  300. }
  301. unset($parameters['action']);
  302. unset($parameters['caller']);
  303. $this->eventLogger->start('route:run:call', 'Run callable route');
  304. call_user_func($action, $parameters);
  305. $this->eventLogger->end('route:run:call');
  306. } elseif (isset($parameters['file'])) {
  307. include $parameters['file'];
  308. } else {
  309. throw new \Exception('no action available');
  310. }
  311. $this->eventLogger->end('route:run');
  312. }
  313. /**
  314. * Get the url generator
  315. *
  316. * @return \Symfony\Component\Routing\Generator\UrlGenerator
  317. *
  318. */
  319. public function getGenerator() {
  320. if (null !== $this->generator) {
  321. return $this->generator;
  322. }
  323. return $this->generator = new UrlGenerator($this->root, $this->context);
  324. }
  325. /**
  326. * Generate url based on $name and $parameters
  327. *
  328. * @param string $name Name of the route to use.
  329. * @param array $parameters Parameters for the route
  330. * @param bool $absolute
  331. * @return string
  332. */
  333. public function generate($name,
  334. $parameters = [],
  335. $absolute = false) {
  336. $referenceType = UrlGenerator::ABSOLUTE_URL;
  337. if ($absolute === false) {
  338. $referenceType = UrlGenerator::ABSOLUTE_PATH;
  339. }
  340. $name = $this->fixLegacyRootName($name);
  341. if (str_contains($name, '.')) {
  342. [$appName, $other] = explode('.', $name, 3);
  343. // OCS routes are prefixed with "ocs."
  344. if ($appName === 'ocs') {
  345. $appName = $other;
  346. }
  347. $this->loadRoutes($appName);
  348. try {
  349. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  350. } catch (RouteNotFoundException $e) {
  351. }
  352. }
  353. // Fallback load all routes
  354. $this->loadRoutes();
  355. try {
  356. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  357. } catch (RouteNotFoundException $e) {
  358. $this->logger->info($e->getMessage(), ['exception' => $e]);
  359. return '';
  360. }
  361. }
  362. protected function fixLegacyRootName(string $routeName): string {
  363. if ($routeName === 'files.viewcontroller.showFile') {
  364. return 'files.View.showFile';
  365. }
  366. if ($routeName === 'files_sharing.sharecontroller.showShare') {
  367. return 'files_sharing.Share.showShare';
  368. }
  369. if ($routeName === 'files_sharing.sharecontroller.showAuthenticate') {
  370. return 'files_sharing.Share.showAuthenticate';
  371. }
  372. if ($routeName === 'files_sharing.sharecontroller.authenticate') {
  373. return 'files_sharing.Share.authenticate';
  374. }
  375. if ($routeName === 'files_sharing.sharecontroller.downloadShare') {
  376. return 'files_sharing.Share.downloadShare';
  377. }
  378. if ($routeName === 'files_sharing.publicpreview.directLink') {
  379. return 'files_sharing.PublicPreview.directLink';
  380. }
  381. if ($routeName === 'cloud_federation_api.requesthandlercontroller.addShare') {
  382. return 'cloud_federation_api.RequestHandler.addShare';
  383. }
  384. if ($routeName === 'cloud_federation_api.requesthandlercontroller.receiveNotification') {
  385. return 'cloud_federation_api.RequestHandler.receiveNotification';
  386. }
  387. return $routeName;
  388. }
  389. /**
  390. * To isolate the variable scope used inside the $file it is required in it's own method
  391. *
  392. * @param string $file the route file location to include
  393. * @param string $appName
  394. */
  395. private function requireRouteFile($file, $appName) {
  396. $this->setupRoutes(include_once $file, $appName);
  397. }
  398. /**
  399. * If a routes.php file returns an array, try to set up the application and
  400. * register the routes for the app. The application class will be chosen by
  401. * camelcasing the appname, e.g.: my_app will be turned into
  402. * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
  403. * App will be initialized. This makes it optional to ship an
  404. * appinfo/application.php by using the built in query resolver
  405. *
  406. * @param array $routes the application routes
  407. * @param string $appName the name of the app.
  408. */
  409. private function setupRoutes($routes, $appName) {
  410. if (is_array($routes)) {
  411. $routeParser = new RouteParser();
  412. $defaultRoutes = $routeParser->parseDefaultRoutes($routes, $appName);
  413. $ocsRoutes = $routeParser->parseOCSRoutes($routes, $appName);
  414. $this->root->addCollection($defaultRoutes);
  415. $ocsRoutes->addPrefix('/ocsapp');
  416. $this->root->addCollection($ocsRoutes);
  417. }
  418. }
  419. private function getApplicationClass(string $appName) {
  420. $appNameSpace = App::buildAppNamespace($appName);
  421. $applicationClassName = $appNameSpace . '\\AppInfo\\Application';
  422. if (class_exists($applicationClassName)) {
  423. $application = $this->container->get($applicationClassName);
  424. } else {
  425. $application = new App($appName);
  426. }
  427. return $application;
  428. }
  429. }