You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

447 lines
13 KiB

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