URLGenerator.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Rudolf <github.com@daniel-rudolf.de>
  10. * @author Felix Epp <work@felixepp.de>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Julius Haertl <jus@bitgrid.net>
  14. * @author Julius Härtl <jus@bitgrid.net>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author mmccarn <mmccarn-github@mmsionline.us>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Robin Appelman <robin@icewind.nl>
  19. * @author Robin McCorkell <robin@mccorkell.me.uk>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author Thomas Müller <thomas.mueller@tmit.eu>
  22. * @author Thomas Tanghus <thomas@tanghus.net>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. namespace OC;
  40. use OC\Route\Router;
  41. use OCA\Theming\ThemingDefaults;
  42. use OCP\App\AppPathNotFoundException;
  43. use OCP\App\IAppManager;
  44. use OCP\ICacheFactory;
  45. use OCP\IConfig;
  46. use OCP\IRequest;
  47. use OCP\IURLGenerator;
  48. use OCP\IUserSession;
  49. use RuntimeException;
  50. /**
  51. * Class to generate URLs
  52. */
  53. class URLGenerator implements IURLGenerator {
  54. /** @var IConfig */
  55. private $config;
  56. /** @var IUserSession */
  57. public $userSession;
  58. /** @var ICacheFactory */
  59. private $cacheFactory;
  60. /** @var IRequest */
  61. private $request;
  62. /** @var Router */
  63. private $router;
  64. /** @var null|string */
  65. private $baseUrl = null;
  66. private ?IAppManager $appManager = null;
  67. public function __construct(IConfig $config,
  68. IUserSession $userSession,
  69. ICacheFactory $cacheFactory,
  70. IRequest $request,
  71. Router $router
  72. ) {
  73. $this->config = $config;
  74. $this->userSession = $userSession;
  75. $this->cacheFactory = $cacheFactory;
  76. $this->request = $request;
  77. $this->router = $router;
  78. }
  79. private function getAppManager(): IAppManager {
  80. if ($this->appManager !== null) {
  81. return $this->appManager;
  82. }
  83. $this->appManager = \OCP\Server::get(IAppManager::class);
  84. return $this->appManager;
  85. }
  86. /**
  87. * Creates an url using a defined route
  88. *
  89. * @param string $routeName
  90. * @param array $arguments args with param=>value, will be appended to the returned url
  91. * @return string the url
  92. *
  93. * Returns a url to the given route.
  94. */
  95. public function linkToRoute(string $routeName, array $arguments = []): string {
  96. return $this->router->generate($routeName, $arguments);
  97. }
  98. /**
  99. * Creates an absolute url using a defined route
  100. * @param string $routeName
  101. * @param array $arguments args with param=>value, will be appended to the returned url
  102. * @return string the url
  103. *
  104. * Returns an absolute url to the given route.
  105. */
  106. public function linkToRouteAbsolute(string $routeName, array $arguments = []): string {
  107. return $this->getAbsoluteURL($this->linkToRoute($routeName, $arguments));
  108. }
  109. public function linkToOCSRouteAbsolute(string $routeName, array $arguments = []): string {
  110. $route = $this->router->generate('ocs.'.$routeName, $arguments, false);
  111. $indexPhpPos = strpos($route, '/index.php/');
  112. if ($indexPhpPos !== false) {
  113. $route = substr($route, $indexPhpPos + 10);
  114. }
  115. $route = substr($route, 7);
  116. $route = '/ocs/v2.php' . $route;
  117. return $this->getAbsoluteURL($route);
  118. }
  119. /**
  120. * Creates an url
  121. *
  122. * @param string $appName app
  123. * @param string $file file
  124. * @param array $args array with param=>value, will be appended to the returned url
  125. * The value of $args will be urlencoded
  126. * @return string the url
  127. *
  128. * Returns a url to the given app and file.
  129. */
  130. public function linkTo(string $appName, string $file, array $args = []): string {
  131. $frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
  132. if ($appName !== '') {
  133. $app_path = $this->getAppManager()->getAppPath($appName);
  134. // Check if the app is in the app folder
  135. if (file_exists($app_path . '/' . $file)) {
  136. if (substr($file, -3) === 'php') {
  137. $urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $appName;
  138. if ($frontControllerActive) {
  139. $urlLinkTo = \OC::$WEBROOT . '/apps/' . $appName;
  140. }
  141. $urlLinkTo .= ($file !== 'index.php') ? '/' . $file : '';
  142. } else {
  143. $urlLinkTo = $this->getAppManager()->getAppWebPath($appName) . '/' . $file;
  144. }
  145. } else {
  146. $urlLinkTo = \OC::$WEBROOT . '/' . $appName . '/' . $file;
  147. }
  148. } else {
  149. if (file_exists(\OC::$SERVERROOT . '/core/' . $file)) {
  150. $urlLinkTo = \OC::$WEBROOT . '/core/' . $file;
  151. } else {
  152. if ($frontControllerActive && $file === 'index.php') {
  153. $urlLinkTo = \OC::$WEBROOT . '/';
  154. } else {
  155. $urlLinkTo = \OC::$WEBROOT . '/' . $file;
  156. }
  157. }
  158. }
  159. if ($args && $query = http_build_query($args, '', '&')) {
  160. $urlLinkTo .= '?' . $query;
  161. }
  162. return $urlLinkTo;
  163. }
  164. /**
  165. * Creates path to an image
  166. *
  167. * @param string $appName app
  168. * @param string $file image name
  169. * @throws \RuntimeException If the image does not exist
  170. * @return string the url
  171. *
  172. * Returns the path to the image.
  173. */
  174. public function imagePath(string $appName, string $file): string {
  175. $cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-');
  176. $cacheKey = $appName.'-'.$file;
  177. if ($key = $cache->get($cacheKey)) {
  178. return $key;
  179. }
  180. // Read the selected theme from the config file
  181. $theme = \OC_Util::getTheme();
  182. //if a theme has a png but not an svg always use the png
  183. $basename = substr(basename($file), 0, -4);
  184. try {
  185. $appPath = $this->getAppManager()->getAppPath($appName);
  186. } catch (AppPathNotFoundException $e) {
  187. if ($appName === 'core' || $appName === '') {
  188. $appName = 'core';
  189. $appPath = false;
  190. } else {
  191. throw new RuntimeException('image not found: image: ' . $file . ' webroot: ' . \OC::$WEBROOT . ' serverroot: ' . \OC::$SERVERROOT);
  192. }
  193. }
  194. // Check if the app is in the app folder
  195. $path = '';
  196. $themingEnabled = $this->config->getSystemValue('installed', false) && $this->getAppManager()->isEnabledForUser('theming');
  197. $themingImagePath = false;
  198. if ($themingEnabled) {
  199. $themingDefaults = \OC::$server->getThemingDefaults();
  200. if ($themingDefaults instanceof ThemingDefaults) {
  201. $themingImagePath = $themingDefaults->replaceImagePath($appName, $file);
  202. }
  203. }
  204. if (file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$appName/img/$file")) {
  205. $path = \OC::$WEBROOT . "/themes/$theme/apps/$appName/img/$file";
  206. } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$appName/img/$basename.svg")
  207. && file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$appName/img/$basename.png")) {
  208. $path = \OC::$WEBROOT . "/themes/$theme/apps/$appName/img/$basename.png";
  209. } elseif (!empty($appName) and file_exists(\OC::$SERVERROOT . "/themes/$theme/$appName/img/$file")) {
  210. $path = \OC::$WEBROOT . "/themes/$theme/$appName/img/$file";
  211. } elseif (!empty($appName) and (!file_exists(\OC::$SERVERROOT . "/themes/$theme/$appName/img/$basename.svg")
  212. && file_exists(\OC::$SERVERROOT . "/themes/$theme/$appName/img/$basename.png"))) {
  213. $path = \OC::$WEBROOT . "/themes/$theme/$appName/img/$basename.png";
  214. } elseif (file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$file")) {
  215. $path = \OC::$WEBROOT . "/themes/$theme/core/img/$file";
  216. } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg")
  217. && file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) {
  218. $path = \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
  219. } elseif ($themingEnabled && $themingImagePath) {
  220. $path = $themingImagePath;
  221. } elseif ($appPath && file_exists($appPath . "/img/$file")) {
  222. $path = $this->getAppManager()->getAppWebPath($appName) . "/img/$file";
  223. } elseif ($appPath && !file_exists($appPath . "/img/$basename.svg")
  224. && file_exists($appPath . "/img/$basename.png")) {
  225. $path = $this->getAppManager()->getAppWebPath($appName) . "/img/$basename.png";
  226. } elseif (!empty($appName) and file_exists(\OC::$SERVERROOT . "/$appName/img/$file")) {
  227. $path = \OC::$WEBROOT . "/$appName/img/$file";
  228. } elseif (!empty($appName) and (!file_exists(\OC::$SERVERROOT . "/$appName/img/$basename.svg")
  229. && file_exists(\OC::$SERVERROOT . "/$appName/img/$basename.png"))) {
  230. $path = \OC::$WEBROOT . "/$appName/img/$basename.png";
  231. } elseif (file_exists(\OC::$SERVERROOT . "/core/img/$file")) {
  232. $path = \OC::$WEBROOT . "/core/img/$file";
  233. } elseif (!file_exists(\OC::$SERVERROOT . "/core/img/$basename.svg")
  234. && file_exists(\OC::$SERVERROOT . "/core/img/$basename.png")) {
  235. $path = \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
  236. }
  237. if ($path !== '') {
  238. $cache->set($cacheKey, $path);
  239. return $path;
  240. }
  241. throw new RuntimeException('image not found: image:' . $file . ' webroot:' . \OC::$WEBROOT . ' serverroot:' . \OC::$SERVERROOT);
  242. }
  243. /**
  244. * Makes an URL absolute
  245. * @param string $url the url in the ownCloud host
  246. * @return string the absolute version of the url
  247. */
  248. public function getAbsoluteURL(string $url): string {
  249. $separator = strpos($url, '/') === 0 ? '' : '/';
  250. if (\OC::$CLI && !\defined('PHPUNIT_RUN')) {
  251. return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/');
  252. }
  253. // The ownCloud web root can already be prepended.
  254. if (\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
  255. $url = substr($url, \strlen(\OC::$WEBROOT));
  256. }
  257. return $this->getBaseUrl() . $separator . $url;
  258. }
  259. /**
  260. * @param string $key
  261. * @return string url to the online documentation
  262. */
  263. public function linkToDocs(string $key): string {
  264. $theme = \OC::$server->getThemingDefaults();
  265. return $theme->buildDocLinkToKey($key);
  266. }
  267. /**
  268. * Returns the URL of the default page based on the system configuration
  269. * and the apps visible for the current user
  270. * @return string
  271. */
  272. public function linkToDefaultPageUrl(): string {
  273. // Deny the redirect if the URL contains a @
  274. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  275. if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
  276. return $this->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
  277. }
  278. $defaultPage = $this->config->getAppValue('core', 'defaultpage');
  279. if ($defaultPage) {
  280. return $this->getAbsoluteURL($defaultPage);
  281. }
  282. $appId = 'files';
  283. $defaultApps = explode(',', $this->config->getSystemValue('defaultapp', 'dashboard,files'));
  284. $userId = $this->userSession->isLoggedIn() ? $this->userSession->getUser()->getUID() : null;
  285. if ($userId !== null) {
  286. $userDefaultApps = explode(',', $this->config->getUserValue($userId, 'core', 'defaultapp'));
  287. $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
  288. }
  289. // find the first app that is enabled for the current user
  290. foreach ($defaultApps as $defaultApp) {
  291. $defaultApp = \OC_App::cleanAppId(strip_tags($defaultApp));
  292. if (\OC::$server->getAppManager()->isEnabledForUser($defaultApp)) {
  293. $appId = $defaultApp;
  294. break;
  295. }
  296. }
  297. if ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true
  298. || getenv('front_controller_active') === 'true') {
  299. return $this->getAbsoluteURL('/apps/' . $appId . '/');
  300. }
  301. return $this->getAbsoluteURL('/index.php/apps/' . $appId . '/');
  302. }
  303. /**
  304. * @return string base url of the current request
  305. */
  306. public function getBaseUrl(): string {
  307. // BaseUrl can be equal to 'http(s)://' during the first steps of the initial setup.
  308. if ($this->baseUrl === null || $this->baseUrl === "http://" || $this->baseUrl === "https://") {
  309. $this->baseUrl = $this->request->getServerProtocol() . '://' . $this->request->getServerHost() . \OC::$WEBROOT;
  310. }
  311. return $this->baseUrl;
  312. }
  313. /**
  314. * @return string webroot part of the base url
  315. */
  316. public function getWebroot(): string {
  317. return \OC::$WEBROOT;
  318. }
  319. }