Router.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 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 && 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. $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. $collection = $this->getCollection('ocs');
  166. $collection->addPrefix('/ocs');
  167. $this->root->addCollection($collection);
  168. }
  169. \OC::$server->getEventLogger()->end('loadroutes' . $requestedApp);
  170. }
  171. /**
  172. * @return string
  173. * @deprecated
  174. */
  175. public function getCacheKey() {
  176. return '';
  177. }
  178. /**
  179. * @param string $name
  180. * @return \Symfony\Component\Routing\RouteCollection
  181. */
  182. protected function getCollection($name) {
  183. if (!isset($this->collections[$name])) {
  184. $this->collections[$name] = new RouteCollection();
  185. }
  186. return $this->collections[$name];
  187. }
  188. /**
  189. * Sets the collection to use for adding routes
  190. *
  191. * @param string $name Name of the collection to use.
  192. * @return void
  193. */
  194. public function useCollection($name) {
  195. $this->collection = $this->getCollection($name);
  196. $this->collectionName = $name;
  197. }
  198. /**
  199. * returns the current collection name in use for adding routes
  200. *
  201. * @return string the collection name
  202. */
  203. public function getCurrentCollection() {
  204. return $this->collectionName;
  205. }
  206. /**
  207. * Create a \OC\Route\Route.
  208. *
  209. * @param string $name Name of the route to create.
  210. * @param string $pattern The pattern to match
  211. * @param array $defaults An array of default parameter values
  212. * @param array $requirements An array of requirements for parameters (regexes)
  213. * @return \OC\Route\Route
  214. */
  215. public function create($name,
  216. $pattern,
  217. array $defaults = [],
  218. array $requirements = []) {
  219. $route = new Route($pattern, $defaults, $requirements);
  220. $this->collection->add($name, $route);
  221. return $route;
  222. }
  223. /**
  224. * Find the route matching $url
  225. *
  226. * @param string $url The url to find
  227. * @throws \Exception
  228. * @return void
  229. */
  230. public function match($url) {
  231. if (substr($url, 0, 6) === '/apps/') {
  232. // empty string / 'apps' / $app / rest of the route
  233. list(, , $app,) = explode('/', $url, 4);
  234. $app = \OC_App::cleanAppId($app);
  235. \OC::$REQUESTEDAPP = $app;
  236. $this->loadRoutes($app);
  237. } else if (substr($url, 0, 13) === '/ocsapp/apps/') {
  238. // empty string / 'ocsapp' / 'apps' / $app / rest of the route
  239. list(, , , $app,) = explode('/', $url, 5);
  240. $app = \OC_App::cleanAppId($app);
  241. \OC::$REQUESTEDAPP = $app;
  242. $this->loadRoutes($app);
  243. } else if (substr($url, 0, 6) === '/core/' or substr($url, 0, 10) === '/settings/') {
  244. \OC::$REQUESTEDAPP = $url;
  245. if (!\OC::$server->getConfig()->getSystemValue('maintenance', false) && !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. \OC::$server->getEventLogger()->start('run_route', 'Run route');
  271. if (isset($parameters['action'])) {
  272. $action = $parameters['action'];
  273. if (!is_callable($action)) {
  274. throw new \Exception('not a callable action');
  275. }
  276. unset($parameters['action']);
  277. call_user_func($action, $parameters);
  278. } elseif (isset($parameters['file'])) {
  279. include $parameters['file'];
  280. } else {
  281. throw new \Exception('no action available');
  282. }
  283. \OC::$server->getEventLogger()->end('run_route');
  284. }
  285. /**
  286. * Get the url generator
  287. *
  288. * @return \Symfony\Component\Routing\Generator\UrlGenerator
  289. *
  290. */
  291. public function getGenerator() {
  292. if (null !== $this->generator) {
  293. return $this->generator;
  294. }
  295. return $this->generator = new UrlGenerator($this->root, $this->context);
  296. }
  297. /**
  298. * Generate url based on $name and $parameters
  299. *
  300. * @param string $name Name of the route to use.
  301. * @param array $parameters Parameters for the route
  302. * @param bool $absolute
  303. * @return string
  304. */
  305. public function generate($name,
  306. $parameters = [],
  307. $absolute = false) {
  308. $this->loadRoutes();
  309. try {
  310. $referenceType = UrlGenerator::ABSOLUTE_URL;
  311. if ($absolute === false) {
  312. $referenceType = UrlGenerator::ABSOLUTE_PATH;
  313. }
  314. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  315. } catch (RouteNotFoundException $e) {
  316. $this->logger->logException($e);
  317. return '';
  318. }
  319. }
  320. /**
  321. * To isolate the variable scope used inside the $file it is required in it's own method
  322. *
  323. * @param string $file the route file location to include
  324. * @param string $appName
  325. */
  326. private function requireRouteFile($file, $appName) {
  327. $this->setupRoutes(include_once $file, $appName);
  328. }
  329. /**
  330. * If a routes.php file returns an array, try to set up the application and
  331. * register the routes for the app. The application class will be chosen by
  332. * camelcasing the appname, e.g.: my_app will be turned into
  333. * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
  334. * App will be intialized. This makes it optional to ship an
  335. * appinfo/application.php by using the built in query resolver
  336. *
  337. * @param array $routes the application routes
  338. * @param string $appName the name of the app.
  339. */
  340. private function setupRoutes($routes, $appName) {
  341. if (is_array($routes)) {
  342. $appNameSpace = App::buildAppNamespace($appName);
  343. $applicationClassName = $appNameSpace . '\\AppInfo\\Application';
  344. if (class_exists($applicationClassName)) {
  345. $application = new $applicationClassName();
  346. } else {
  347. $application = new App($appName);
  348. }
  349. $application->registerRoutes($this, $routes);
  350. }
  351. }
  352. }