TemplateLayout.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christopher Schäpers <kondou@ts.unde.re>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Clark Tomlinson <fallen013@gmail.com>
  9. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  10. * @author Guillaume COMPAGNON <gcompagnon@outlook.com>
  11. * @author Hendrik Leppelsack <hendrik@leppelsack.de>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ <skjnldsv@protonmail.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Julius Haertl <jus@bitgrid.net>
  16. * @author Julius Härtl <jus@bitgrid.net>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Nils <git@to.nilsschnabel.de>
  21. * @author Remco Brenninkmeijer <requist1@starmail.nl>
  22. * @author Robin Appelman <robin@icewind.nl>
  23. * @author Robin McCorkell <robin@mccorkell.me.uk>
  24. * @author Roeland Jago Douma <roeland@famdouma.nl>
  25. * @author Thomas Citharel <nextcloud@tcit.fr>
  26. * @author Thomas Müller <thomas.mueller@tmit.eu>
  27. *
  28. * @license AGPL-3.0
  29. *
  30. * This code is free software: you can redistribute it and/or modify
  31. * it under the terms of the GNU Affero General Public License, version 3,
  32. * as published by the Free Software Foundation.
  33. *
  34. * This program is distributed in the hope that it will be useful,
  35. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  36. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  37. * GNU Affero General Public License for more details.
  38. *
  39. * You should have received a copy of the GNU Affero General Public License, version 3,
  40. * along with this program. If not, see <http://www.gnu.org/licenses/>
  41. *
  42. */
  43. namespace OC;
  44. use bantu\IniGetWrapper\IniGetWrapper;
  45. use OC\Search\SearchQuery;
  46. use OC\Template\CSSResourceLocator;
  47. use OC\Template\JSConfigHelper;
  48. use OC\Template\JSResourceLocator;
  49. use OCP\AppFramework\Http\TemplateResponse;
  50. use OCP\Defaults;
  51. use OCP\IConfig;
  52. use OCP\IInitialStateService;
  53. use OCP\INavigationManager;
  54. use OCP\IUserSession;
  55. use OCP\Support\Subscription\IRegistry;
  56. use OCP\Util;
  57. class TemplateLayout extends \OC_Template {
  58. private static $versionHash = '';
  59. /** @var CSSResourceLocator|null */
  60. public static $cssLocator = null;
  61. /** @var JSResourceLocator|null */
  62. public static $jsLocator = null;
  63. /** @var IConfig */
  64. private $config;
  65. /** @var IInitialStateService */
  66. private $initialState;
  67. /** @var INavigationManager */
  68. private $navigationManager;
  69. /**
  70. * @param string $renderAs
  71. * @param string $appId application id
  72. */
  73. public function __construct($renderAs, $appId = '') {
  74. /** @var IConfig */
  75. $this->config = \OC::$server->get(IConfig::class);
  76. /** @var IInitialStateService */
  77. $this->initialState = \OC::$server->get(IInitialStateService::class);
  78. // Add fallback theming variables if theming is disabled
  79. if ($renderAs !== TemplateResponse::RENDER_AS_USER
  80. || !\OC::$server->getAppManager()->isEnabledForUser('theming')) {
  81. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  82. Util::addStyle('theming', 'default');
  83. }
  84. // Decide which page we show
  85. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  86. /** @var INavigationManager */
  87. $this->navigationManager = \OC::$server->get(INavigationManager::class);
  88. parent::__construct('core', 'layout.user');
  89. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  90. $this->assign('bodyid', 'body-settings');
  91. } else {
  92. $this->assign('bodyid', 'body-user');
  93. }
  94. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  95. $this->initialState->provideInitialState('core', 'apps', $this->navigationManager->getAll());
  96. $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
  97. $this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
  98. $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
  99. Util::addScript('core', 'unified-search', 'core');
  100. // Set body data-theme
  101. $this->assign('enabledThemes', []);
  102. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
  103. /** @var \OCA\Theming\Service\ThemesService */
  104. $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
  105. $this->assign('enabledThemes', $themesService->getEnabledThemes());
  106. }
  107. // Add navigation entry
  108. $this->assign('application', '');
  109. $this->assign('appid', $appId);
  110. $navigation = $this->navigationManager->getAll();
  111. $this->assign('navigation', $navigation);
  112. $settingsNavigation = $this->navigationManager->getAll('settings');
  113. $this->assign('settingsnavigation', $settingsNavigation);
  114. foreach ($navigation as $entry) {
  115. if ($entry['active']) {
  116. $this->assign('application', $entry['name']);
  117. break;
  118. }
  119. }
  120. foreach ($settingsNavigation as $entry) {
  121. if ($entry['active']) {
  122. $this->assign('application', $entry['name']);
  123. break;
  124. }
  125. }
  126. $userDisplayName = false;
  127. $user = \OC::$server->get(IUserSession::class)->getUser();
  128. if ($user) {
  129. $userDisplayName = $user->getDisplayName();
  130. }
  131. $this->assign('user_displayname', $userDisplayName);
  132. $this->assign('user_uid', \OC_User::getUser());
  133. if ($user === null) {
  134. $this->assign('userAvatarSet', false);
  135. $this->assign('userStatus', false);
  136. } else {
  137. $this->assign('userAvatarSet', true);
  138. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  139. }
  140. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  141. parent::__construct('core', 'layout.guest', '', false);
  142. $this->assign('bodyid', 'body-login');
  143. $this->assign('user_displayname', '');
  144. $this->assign('user_uid', '');
  145. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  146. parent::__construct('core', 'layout.guest');
  147. \OC_Util::addStyle('guest');
  148. $this->assign('bodyid', 'body-login');
  149. $userDisplayName = false;
  150. $user = \OC::$server->get(IUserSession::class)->getUser();
  151. if ($user) {
  152. $userDisplayName = $user->getDisplayName();
  153. }
  154. $this->assign('user_displayname', $userDisplayName);
  155. $this->assign('user_uid', \OC_User::getUser());
  156. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  157. parent::__construct('core', 'layout.public');
  158. $this->assign('appid', $appId);
  159. $this->assign('bodyid', 'body-public');
  160. /** @var IRegistry $subscription */
  161. $subscription = \OC::$server->query(IRegistry::class);
  162. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  163. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  164. $showSimpleSignup = false;
  165. }
  166. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  167. } else {
  168. parent::__construct('core', 'layout.base');
  169. }
  170. // set logo link target
  171. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  172. $this->assign('logoUrl', $logoUrl);
  173. // Send the language and the locale to our layouts
  174. $lang = \OC::$server->getL10NFactory()->findLanguage();
  175. $locale = \OC::$server->getL10NFactory()->findLocale($lang);
  176. $lang = str_replace('_', '-', $lang);
  177. $this->assign('language', $lang);
  178. $this->assign('locale', $locale);
  179. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  180. if (empty(self::$versionHash)) {
  181. $v = \OC_App::getAppVersions();
  182. $v['core'] = implode('.', \OCP\Util::getVersion());
  183. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  184. }
  185. } else {
  186. self::$versionHash = md5('not installed');
  187. }
  188. // Add the js files
  189. // TODO: remove deprecated OC_Util injection
  190. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  191. $this->assign('jsfiles', []);
  192. if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  193. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  194. // see https://github.com/nextcloud/server/pull/22636 for details
  195. $jsConfigHelper = new JSConfigHelper(
  196. \OC::$server->getL10N('lib'),
  197. \OC::$server->query(Defaults::class),
  198. \OC::$server->getAppManager(),
  199. \OC::$server->getSession(),
  200. \OC::$server->getUserSession()->getUser(),
  201. $this->config,
  202. \OC::$server->getGroupManager(),
  203. \OC::$server->get(IniGetWrapper::class),
  204. \OC::$server->getURLGenerator(),
  205. \OC::$server->getCapabilitiesManager(),
  206. \OC::$server->query(IInitialStateService::class)
  207. );
  208. $config = $jsConfigHelper->getConfig();
  209. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  210. $this->assign('inline_ocjs', $config);
  211. } else {
  212. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  213. }
  214. }
  215. foreach ($jsFiles as $info) {
  216. $web = $info[1];
  217. $file = $info[2];
  218. $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  219. }
  220. try {
  221. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  222. } catch (\Exception $e) {
  223. $pathInfo = '';
  224. }
  225. // Do not initialise scss appdata until we have a fully installed instance
  226. // Do not load scss for update, errors, installation or login page
  227. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  228. && !\OCP\Util::needUpgrade()
  229. && $pathInfo !== ''
  230. && !preg_match('/^\/login/', $pathInfo)
  231. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  232. ) {
  233. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  234. } else {
  235. // If we ignore the scss compiler,
  236. // we need to load the guest css fallback
  237. \OC_Util::addStyle('guest');
  238. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  239. }
  240. $this->assign('cssfiles', []);
  241. $this->assign('printcssfiles', []);
  242. $this->assign('versionHash', self::$versionHash);
  243. foreach ($cssFiles as $info) {
  244. $web = $info[1];
  245. $file = $info[2];
  246. if (substr($file, -strlen('print.css')) === 'print.css') {
  247. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  248. } else {
  249. $suffix = $this->getVersionHashSuffix($web, $file);
  250. if (strpos($file, '?v=') == false) {
  251. $this->append('cssfiles', $web.'/'.$file . $suffix);
  252. } else {
  253. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  254. }
  255. }
  256. }
  257. $this->assign('initialStates', $this->initialState->getInitialStates());
  258. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  259. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  260. }
  261. /**
  262. * @param string $path
  263. * @param string $file
  264. * @return string
  265. */
  266. protected function getVersionHashSuffix($path = false, $file = false) {
  267. if ($this->config->getSystemValue('debug', false)) {
  268. // allows chrome workspace mapping in debug mode
  269. return "";
  270. }
  271. $themingSuffix = '';
  272. $v = [];
  273. if ($this->config->getSystemValue('installed', false)) {
  274. if (\OC::$server->getAppManager()->isInstalled('theming')) {
  275. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  276. }
  277. $v = \OC_App::getAppVersions();
  278. }
  279. // Try the webroot path for a match
  280. if ($path !== false && $path !== '') {
  281. $appName = $this->getAppNamefromPath($path);
  282. if (array_key_exists($appName, $v)) {
  283. $appVersion = $v[$appName];
  284. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  285. }
  286. }
  287. // fallback to the file path instead
  288. if ($file !== false && $file !== '') {
  289. $appName = $this->getAppNamefromPath($file);
  290. if (array_key_exists($appName, $v)) {
  291. $appVersion = $v[$appName];
  292. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  293. }
  294. }
  295. return '?v=' . self::$versionHash . $themingSuffix;
  296. }
  297. /**
  298. * @param array $styles
  299. * @return array
  300. */
  301. public static function findStylesheetFiles($styles, $compileScss = true) {
  302. if (!self::$cssLocator) {
  303. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  304. }
  305. self::$cssLocator->find($styles);
  306. return self::$cssLocator->getResources();
  307. }
  308. /**
  309. * @param string $path
  310. * @return string|boolean
  311. */
  312. public function getAppNamefromPath($path) {
  313. if ($path !== '' && is_string($path)) {
  314. $pathParts = explode('/', $path);
  315. if ($pathParts[0] === 'css') {
  316. // This is a scss request
  317. return $pathParts[1];
  318. }
  319. return end($pathParts);
  320. }
  321. return false;
  322. }
  323. /**
  324. * @param array $scripts
  325. * @return array
  326. */
  327. public static function findJavascriptFiles($scripts) {
  328. if (!self::$jsLocator) {
  329. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  330. }
  331. self::$jsLocator->find($scripts);
  332. return self::$jsLocator->getResources();
  333. }
  334. /**
  335. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  336. * @param string $filePath Absolute path
  337. * @return string Relative path
  338. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  339. */
  340. public static function convertToRelativePath($filePath) {
  341. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  342. if (count($relativePath) !== 2) {
  343. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  344. }
  345. return $relativePath[1];
  346. }
  347. }