Router.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 Felix Anand Epp <work@felixepp.de>
  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\ILogger;
  35. use OCP\Route\IRouter;
  36. use OCP\AppFramework\App;
  37. use OCP\Util;
  38. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  39. use Symfony\Component\Routing\Matcher\UrlMatcher;
  40. use Symfony\Component\Routing\Generator\UrlGenerator;
  41. use Symfony\Component\Routing\RequestContext;
  42. use Symfony\Component\Routing\RouteCollection;
  43. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  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 = \OC::$server->getURLGenerator()->linkTo('', 'index.php');
  73. }
  74. if (!\OC::$CLI) {
  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. $collection->addPrefix('/apps/' . $app);
  147. $this->root->addCollection($collection);
  148. // Also add the OCS collection
  149. $collection = $this->getCollection($app.'.ocs');
  150. $collection->addPrefix('/ocsapp');
  151. $this->root->addCollection($collection);
  152. }
  153. }
  154. if (!isset($this->loadedApps['core'])) {
  155. $this->loadedApps['core'] = true;
  156. $this->useCollection('root');
  157. require_once __DIR__ . '/../../../settings/routes.php';
  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. // include ocs routes, must be loaded last for /ocs prefix
  166. require_once __DIR__ . '/../../../ocs/routes.php';
  167. $collection = $this->getCollection('ocs');
  168. $collection->addPrefix('/ocs');
  169. $this->root->addCollection($collection);
  170. }
  171. \OC::$server->getEventLogger()->end('loadroutes' . $requestedApp);
  172. }
  173. /**
  174. * @return string
  175. * @deprecated
  176. */
  177. public function getCacheKey() {
  178. return '';
  179. }
  180. /**
  181. * @param string $name
  182. * @return \Symfony\Component\Routing\RouteCollection
  183. */
  184. protected function getCollection($name) {
  185. if (!isset($this->collections[$name])) {
  186. $this->collections[$name] = new RouteCollection();
  187. }
  188. return $this->collections[$name];
  189. }
  190. /**
  191. * Sets the collection to use for adding routes
  192. *
  193. * @param string $name Name of the collection to use.
  194. * @return void
  195. */
  196. public function useCollection($name) {
  197. $this->collection = $this->getCollection($name);
  198. $this->collectionName = $name;
  199. }
  200. /**
  201. * returns the current collection name in use for adding routes
  202. *
  203. * @return string the collection name
  204. */
  205. public function getCurrentCollection() {
  206. return $this->collectionName;
  207. }
  208. /**
  209. * Create a \OC\Route\Route.
  210. *
  211. * @param string $name Name of the route to create.
  212. * @param string $pattern The pattern to match
  213. * @param array $defaults An array of default parameter values
  214. * @param array $requirements An array of requirements for parameters (regexes)
  215. * @return \OC\Route\Route
  216. */
  217. public function create($name,
  218. $pattern,
  219. array $defaults = [],
  220. array $requirements = []) {
  221. $route = new Route($pattern, $defaults, $requirements);
  222. $this->collection->add($name, $route);
  223. return $route;
  224. }
  225. /**
  226. * Find the route matching $url
  227. *
  228. * @param string $url The url to find
  229. * @throws \Exception
  230. * @return void
  231. */
  232. public function match($url) {
  233. if (substr($url, 0, 6) === '/apps/') {
  234. // empty string / 'apps' / $app / rest of the route
  235. list(, , $app,) = explode('/', $url, 4);
  236. $app = \OC_App::cleanAppId($app);
  237. \OC::$REQUESTEDAPP = $app;
  238. $this->loadRoutes($app);
  239. } else if (substr($url, 0, 13) === '/ocsapp/apps/') {
  240. // empty string / 'ocsapp' / 'apps' / $app / rest of the route
  241. list(, , , $app,) = explode('/', $url, 5);
  242. $app = \OC_App::cleanAppId($app);
  243. \OC::$REQUESTEDAPP = $app;
  244. $this->loadRoutes($app);
  245. } else if (substr($url, 0, 6) === '/core/' or substr($url, 0, 10) === '/settings/') {
  246. \OC::$REQUESTEDAPP = $url;
  247. if (!\OC::$server->getConfig()->getSystemValue('maintenance', false) && !Util::needUpgrade()) {
  248. \OC_App::loadApps();
  249. }
  250. $this->loadRoutes('core');
  251. } else {
  252. $this->loadRoutes();
  253. }
  254. $matcher = new UrlMatcher($this->root, $this->context);
  255. try {
  256. $parameters = $matcher->match($url);
  257. } catch (ResourceNotFoundException $e) {
  258. if (substr($url, -1) !== '/') {
  259. // We allow links to apps/files? for backwards compatibility reasons
  260. // However, since Symfony does not allow empty route names, the route
  261. // we need to match is '/', so we need to append the '/' here.
  262. try {
  263. $parameters = $matcher->match($url . '/');
  264. } catch (ResourceNotFoundException $newException) {
  265. // If we still didn't match a route, we throw the original exception
  266. throw $e;
  267. }
  268. } else {
  269. throw $e;
  270. }
  271. }
  272. \OC::$server->getEventLogger()->start('run_route', 'Run route');
  273. if (isset($parameters['action'])) {
  274. $action = $parameters['action'];
  275. if (!is_callable($action)) {
  276. throw new \Exception('not a callable action');
  277. }
  278. unset($parameters['action']);
  279. call_user_func($action, $parameters);
  280. } elseif (isset($parameters['file'])) {
  281. include $parameters['file'];
  282. } else {
  283. throw new \Exception('no action available');
  284. }
  285. \OC::$server->getEventLogger()->end('run_route');
  286. }
  287. /**
  288. * Get the url generator
  289. *
  290. * @return \Symfony\Component\Routing\Generator\UrlGenerator
  291. *
  292. */
  293. public function getGenerator() {
  294. if (null !== $this->generator) {
  295. return $this->generator;
  296. }
  297. return $this->generator = new UrlGenerator($this->root, $this->context);
  298. }
  299. /**
  300. * Generate url based on $name and $parameters
  301. *
  302. * @param string $name Name of the route to use.
  303. * @param array $parameters Parameters for the route
  304. * @param bool $absolute
  305. * @return string
  306. */
  307. public function generate($name,
  308. $parameters = [],
  309. $absolute = false) {
  310. $this->loadRoutes();
  311. try {
  312. $referenceType = UrlGenerator::ABSOLUTE_URL;
  313. if ($absolute === false) {
  314. $referenceType = UrlGenerator::ABSOLUTE_PATH;
  315. }
  316. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  317. } catch (RouteNotFoundException $e) {
  318. $this->logger->logException($e);
  319. return '';
  320. }
  321. }
  322. /**
  323. * To isolate the variable scope used inside the $file it is required in it's own method
  324. *
  325. * @param string $file the route file location to include
  326. * @param string $appName
  327. */
  328. private function requireRouteFile($file, $appName) {
  329. $this->setupRoutes(include_once $file, $appName);
  330. }
  331. /**
  332. * If a routes.php file returns an array, try to set up the application and
  333. * register the routes for the app. The application class will be chosen by
  334. * camelcasing the appname, e.g.: my_app will be turned into
  335. * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
  336. * App will be intialized. This makes it optional to ship an
  337. * appinfo/application.php by using the built in query resolver
  338. *
  339. * @param array $routes the application routes
  340. * @param string $appName the name of the app.
  341. */
  342. private function setupRoutes($routes, $appName) {
  343. if (is_array($routes)) {
  344. $appNameSpace = App::buildAppNamespace($appName);
  345. $applicationClassName = $appNameSpace . '\\AppInfo\\Application';
  346. if (class_exists($applicationClassName)) {
  347. $application = new $applicationClassName();
  348. } else {
  349. $application = new App($appName);
  350. }
  351. $application->registerRoutes($this, $routes);
  352. }
  353. }
  354. }