Router.php 13 KB

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