router.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. /**
  3. * @author Bart Visscher <bartv@thisnet.nl>
  4. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  5. * @author Joas Schilling <nickvergessen@owncloud.com>
  6. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  7. * @author Lukas Reschke <lukas@owncloud.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <icewind@owncloud.com>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. * @author Vincent Petry <pvince81@owncloud.com>
  12. *
  13. * @copyright Copyright (c) 2015, ownCloud, Inc.
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC\Route;
  30. use OCP\Route\IRouter;
  31. use OCP\AppFramework\App;
  32. use Symfony\Component\Routing\Matcher\UrlMatcher;
  33. use Symfony\Component\Routing\Generator\UrlGenerator;
  34. use Symfony\Component\Routing\RequestContext;
  35. use Symfony\Component\Routing\RouteCollection;
  36. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  37. class Router implements IRouter {
  38. /**
  39. * @var \Symfony\Component\Routing\RouteCollection[]
  40. */
  41. protected $collections = array();
  42. /**
  43. * @var \Symfony\Component\Routing\RouteCollection
  44. */
  45. protected $collection = null;
  46. /**
  47. * @var string
  48. */
  49. protected $collectionName = null;
  50. /**
  51. * @var \Symfony\Component\Routing\RouteCollection
  52. */
  53. protected $root = null;
  54. /**
  55. * @var \Symfony\Component\Routing\Generator\UrlGenerator
  56. */
  57. protected $generator = null;
  58. /**
  59. * @var string[]
  60. */
  61. protected $routingFiles;
  62. /**
  63. * @var string
  64. */
  65. protected $cacheKey;
  66. protected $loaded = false;
  67. protected $loadedApps = array();
  68. public function __construct() {
  69. $baseUrl = \OC_Helper::linkTo('', 'index.php');
  70. if (!\OC::$CLI) {
  71. $method = $_SERVER['REQUEST_METHOD'];
  72. } else {
  73. $method = 'GET';
  74. }
  75. $request = \OC::$server->getRequest();
  76. $host = $request->getServerHost();
  77. $schema = $request->getServerProtocol();
  78. $this->context = new RequestContext($baseUrl, $method, $host, $schema);
  79. // TODO cache
  80. $this->root = $this->getCollection('root');
  81. }
  82. /**
  83. * Get the files to load the routes from
  84. *
  85. * @return string[]
  86. */
  87. public function getRoutingFiles() {
  88. if (!isset($this->routingFiles)) {
  89. $this->routingFiles = array();
  90. foreach (\OC_APP::getEnabledApps() as $app) {
  91. $file = \OC_App::getAppPath($app) . '/appinfo/routes.php';
  92. if (file_exists($file)) {
  93. $this->routingFiles[$app] = $file;
  94. }
  95. }
  96. }
  97. return $this->routingFiles;
  98. }
  99. /**
  100. * @return string
  101. */
  102. public function getCacheKey() {
  103. if (!isset($this->cacheKey)) {
  104. $files = $this->getRoutingFiles();
  105. $files[] = 'settings/routes.php';
  106. $files[] = 'core/routes.php';
  107. $files[] = 'ocs/routes.php';
  108. $this->cacheKey = \OC\Cache::generateCacheKeyFromFiles($files);
  109. }
  110. return $this->cacheKey;
  111. }
  112. /**
  113. * loads the api routes
  114. * @return void
  115. */
  116. public function loadRoutes($app = null) {
  117. $requestedApp = $app;
  118. if ($this->loaded) {
  119. return;
  120. }
  121. if (is_null($app)) {
  122. $this->loaded = true;
  123. $routingFiles = $this->getRoutingFiles();
  124. } else {
  125. if (isset($this->loadedApps[$app])) {
  126. return;
  127. }
  128. $file = \OC_App::getAppPath($app) . '/appinfo/routes.php';
  129. if (file_exists($file)) {
  130. $routingFiles = array($app => $file);
  131. } else {
  132. $routingFiles = array();
  133. }
  134. }
  135. \OC::$server->getEventLogger()->start('loadroutes' . $requestedApp, 'Loading Routes');
  136. foreach ($routingFiles as $app => $file) {
  137. if (!isset($this->loadedApps[$app])) {
  138. $this->loadedApps[$app] = true;
  139. $this->useCollection($app);
  140. $this->requireRouteFile($file, $app);
  141. $collection = $this->getCollection($app);
  142. $collection->addPrefix('/apps/' . $app);
  143. $this->root->addCollection($collection);
  144. }
  145. }
  146. if (!isset($this->loadedApps['core'])) {
  147. $this->loadedApps['core'] = true;
  148. $this->useCollection('root');
  149. require_once 'settings/routes.php';
  150. require_once 'core/routes.php';
  151. // include ocs routes
  152. require_once 'ocs/routes.php';
  153. $collection = $this->getCollection('ocs');
  154. $collection->addPrefix('/ocs');
  155. $this->root->addCollection($collection);
  156. }
  157. \OC::$server->getEventLogger()->end('loadroutes' . $requestedApp);
  158. }
  159. /**
  160. * @param string $name
  161. * @return \Symfony\Component\Routing\RouteCollection
  162. */
  163. protected function getCollection($name) {
  164. if (!isset($this->collections[$name])) {
  165. $this->collections[$name] = new RouteCollection();
  166. }
  167. return $this->collections[$name];
  168. }
  169. /**
  170. * Sets the collection to use for adding routes
  171. *
  172. * @param string $name Name of the collection to use.
  173. * @return void
  174. */
  175. public function useCollection($name) {
  176. $this->collection = $this->getCollection($name);
  177. $this->collectionName = $name;
  178. }
  179. /**
  180. * returns the current collection name in use for adding routes
  181. *
  182. * @return string the collection name
  183. */
  184. public function getCurrentCollection() {
  185. return $this->collectionName;
  186. }
  187. /**
  188. * Create a \OC\Route\Route.
  189. *
  190. * @param string $name Name of the route to create.
  191. * @param string $pattern The pattern to match
  192. * @param array $defaults An array of default parameter values
  193. * @param array $requirements An array of requirements for parameters (regexes)
  194. * @return \OC\Route\Route
  195. */
  196. public function create($name, $pattern, array $defaults = array(), array $requirements = array()) {
  197. $route = new Route($pattern, $defaults, $requirements);
  198. $this->collection->add($name, $route);
  199. return $route;
  200. }
  201. /**
  202. * Find the route matching $url
  203. *
  204. * @param string $url The url to find
  205. * @throws \Exception
  206. * @return void
  207. */
  208. public function match($url) {
  209. if (substr($url, 0, 6) === '/apps/') {
  210. // empty string / 'apps' / $app / rest of the route
  211. list(, , $app,) = explode('/', $url, 4);
  212. \OC::$REQUESTEDAPP = $app;
  213. $this->loadRoutes($app);
  214. } else if (substr($url, 0, 6) === '/core/' or substr($url, 0, 10) === '/settings/') {
  215. \OC::$REQUESTEDAPP = $url;
  216. if (!\OC_Config::getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
  217. \OC_App::loadApps();
  218. }
  219. $this->loadRoutes('core');
  220. } else {
  221. $this->loadRoutes();
  222. }
  223. $matcher = new UrlMatcher($this->root, $this->context);
  224. try {
  225. $parameters = $matcher->match($url);
  226. } catch (ResourceNotFoundException $e) {
  227. if (substr($url, -1) !== '/') {
  228. // We allow links to apps/files? for backwards compatibility reasons
  229. // However, since Symfony does not allow empty route names, the route
  230. // we need to match is '/', so we need to append the '/' here.
  231. try {
  232. $parameters = $matcher->match($url . '/');
  233. } catch (ResourceNotFoundException $newException) {
  234. // If we still didn't match a route, we throw the original exception
  235. throw $e;
  236. }
  237. } else {
  238. throw $e;
  239. }
  240. }
  241. \OC::$server->getEventLogger()->start('run_route', 'Run route');
  242. if (isset($parameters['action'])) {
  243. $action = $parameters['action'];
  244. if (!is_callable($action)) {
  245. throw new \Exception('not a callable action');
  246. }
  247. unset($parameters['action']);
  248. call_user_func($action, $parameters);
  249. } elseif (isset($parameters['file'])) {
  250. include $parameters['file'];
  251. } else {
  252. throw new \Exception('no action available');
  253. }
  254. \OC::$server->getEventLogger()->end('run_route');
  255. }
  256. /**
  257. * Get the url generator
  258. * @return \Symfony\Component\Routing\Generator\UrlGenerator
  259. *
  260. */
  261. public function getGenerator() {
  262. if (null !== $this->generator) {
  263. return $this->generator;
  264. }
  265. return $this->generator = new UrlGenerator($this->root, $this->context);
  266. }
  267. /**
  268. * Generate url based on $name and $parameters
  269. *
  270. * @param string $name Name of the route to use.
  271. * @param array $parameters Parameters for the route
  272. * @param bool $absolute
  273. * @return string
  274. */
  275. public function generate($name, $parameters = array(), $absolute = false) {
  276. $this->loadRoutes();
  277. return $this->getGenerator()->generate($name, $parameters, $absolute);
  278. }
  279. /**
  280. * To isolate the variable scope used inside the $file it is required in it's own method
  281. * @param string $file the route file location to include
  282. * @param string $appName
  283. */
  284. private function requireRouteFile($file, $appName) {
  285. $this->setupRoutes(include_once $file, $appName);
  286. }
  287. /**
  288. * If a routes.php file returns an array, try to set up the application and
  289. * register the routes for the app. The application class will be chosen by
  290. * camelcasing the appname, e.g.: my_app will be turned into
  291. * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
  292. * App will be intialized. This makes it optional to ship an
  293. * appinfo/application.php by using the built in query resolver
  294. * @param array $routes the application routes
  295. * @param string $appName the name of the app.
  296. */
  297. private function setupRoutes($routes, $appName) {
  298. if (is_array($routes)) {
  299. $appNameSpace = App::buildAppNamespace($appName);
  300. $applicationClassName = $appNameSpace . '\\AppInfo\\Application';
  301. if (class_exists($applicationClassName)) {
  302. $application = new $applicationClassName();
  303. } else {
  304. $application = new App($appName);
  305. }
  306. $application->registerRoutes($this, $routes);
  307. }
  308. }
  309. }