1
0

Router.php 13 KB

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