TemplateLayout.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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\Authentication\Token\IProvider;
  46. use OC\Search\SearchQuery;
  47. use OC\Template\CSSResourceLocator;
  48. use OC\Template\JSConfigHelper;
  49. use OC\Template\JSResourceLocator;
  50. use OCP\App\IAppManager;
  51. use OCP\AppFramework\Http\TemplateResponse;
  52. use OCP\Defaults;
  53. use OCP\IConfig;
  54. use OCP\IInitialStateService;
  55. use OCP\INavigationManager;
  56. use OCP\IURLGenerator;
  57. use OCP\IUserSession;
  58. use OCP\L10N\IFactory;
  59. use OCP\Support\Subscription\IRegistry;
  60. use OCP\Util;
  61. class TemplateLayout extends \OC_Template {
  62. private static $versionHash = '';
  63. /** @var string[] */
  64. private static $cacheBusterCache = [];
  65. /** @var CSSResourceLocator|null */
  66. public static $cssLocator = null;
  67. /** @var JSResourceLocator|null */
  68. public static $jsLocator = null;
  69. private IConfig $config;
  70. private IAppManager $appManager;
  71. private InitialStateService $initialState;
  72. private INavigationManager $navigationManager;
  73. /**
  74. * @param string $renderAs
  75. * @param string $appId application id
  76. */
  77. public function __construct($renderAs, $appId = '') {
  78. $this->config = \OCP\Server::get(IConfig::class);
  79. $this->appManager = \OCP\Server::get(IAppManager::class);
  80. $this->initialState = \OCP\Server::get(InitialStateService::class);
  81. $this->navigationManager = \OCP\Server::get(INavigationManager::class);
  82. // Add fallback theming variables if not rendered as user
  83. if ($renderAs !== TemplateResponse::RENDER_AS_USER) {
  84. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  85. Util::addStyle('theming', 'default');
  86. }
  87. // Decide which page we show
  88. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  89. parent::__construct('core', 'layout.user');
  90. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  91. $this->assign('bodyid', 'body-settings');
  92. } else {
  93. $this->assign('bodyid', 'body-user');
  94. }
  95. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  96. $this->initialState->provideInitialState('core', 'apps', $this->navigationManager->getAll());
  97. if ($this->config->getSystemValueBool('unified_search.enabled', false) || !$this->config->getSystemValueBool('enable_non-accessible_features', true)) {
  98. $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
  99. $this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
  100. $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
  101. Util::addScript('core', 'legacy-unified-search', 'core');
  102. } else {
  103. Util::addScript('core', 'unified-search', 'core');
  104. }
  105. // Set body data-theme
  106. $this->assign('enabledThemes', []);
  107. if ($this->appManager->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
  108. /** @var \OCA\Theming\Service\ThemesService */
  109. $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
  110. $this->assign('enabledThemes', $themesService->getEnabledThemes());
  111. }
  112. // Set logo link target
  113. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  114. $this->assign('logoUrl', $logoUrl);
  115. // Set default app name
  116. $defaultApp = $this->appManager->getDefaultAppForUser();
  117. $defaultAppInfo = $this->appManager->getAppInfo($defaultApp);
  118. $l10n = \OC::$server->get(IFactory::class)->get($defaultApp);
  119. $this->assign('defaultAppName', $l10n->t($defaultAppInfo['name']));
  120. // Add navigation entry
  121. $this->assign('application', '');
  122. $this->assign('appid', $appId);
  123. $navigation = $this->navigationManager->getAll();
  124. $this->assign('navigation', $navigation);
  125. $settingsNavigation = $this->navigationManager->getAll('settings');
  126. $this->initialState->provideInitialState('core', 'settingsNavEntries', $settingsNavigation);
  127. foreach ($navigation as $entry) {
  128. if ($entry['active']) {
  129. $this->assign('application', $entry['name']);
  130. break;
  131. }
  132. }
  133. foreach ($settingsNavigation as $entry) {
  134. if ($entry['active']) {
  135. $this->assign('application', $entry['name']);
  136. break;
  137. }
  138. }
  139. $userDisplayName = false;
  140. $user = \OC::$server->get(IUserSession::class)->getUser();
  141. if ($user) {
  142. $userDisplayName = $user->getDisplayName();
  143. }
  144. $this->assign('user_displayname', $userDisplayName);
  145. $this->assign('user_uid', \OC_User::getUser());
  146. if ($user === null) {
  147. $this->assign('userAvatarSet', false);
  148. $this->assign('userStatus', false);
  149. } else {
  150. $this->assign('userAvatarSet', true);
  151. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  152. }
  153. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  154. parent::__construct('core', 'layout.guest', '', false);
  155. $this->assign('bodyid', 'body-login');
  156. $this->assign('user_displayname', '');
  157. $this->assign('user_uid', '');
  158. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  159. parent::__construct('core', 'layout.guest');
  160. \OC_Util::addStyle('guest');
  161. $this->assign('bodyid', 'body-login');
  162. $userDisplayName = false;
  163. $user = \OC::$server->get(IUserSession::class)->getUser();
  164. if ($user) {
  165. $userDisplayName = $user->getDisplayName();
  166. }
  167. $this->assign('user_displayname', $userDisplayName);
  168. $this->assign('user_uid', \OC_User::getUser());
  169. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  170. parent::__construct('core', 'layout.public');
  171. $this->assign('appid', $appId);
  172. $this->assign('bodyid', 'body-public');
  173. // Set logo link target
  174. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  175. $this->assign('logoUrl', $logoUrl);
  176. /** @var IRegistry $subscription */
  177. $subscription = \OCP\Server::get(IRegistry::class);
  178. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  179. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  180. $showSimpleSignup = false;
  181. }
  182. $defaultSignUpLink = 'https://nextcloud.com/signup/';
  183. $signUpLink = $this->config->getSystemValueString('registration_link', $defaultSignUpLink);
  184. if ($signUpLink !== $defaultSignUpLink) {
  185. $showSimpleSignup = true;
  186. }
  187. if ($this->appManager->isEnabledForUser('registration')) {
  188. $urlGenerator = \OCP\Server::get(IURLGenerator::class);
  189. $signUpLink = $urlGenerator->getAbsoluteURL('/index.php/apps/registration/');
  190. }
  191. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  192. $this->assign('signUpLink', $signUpLink);
  193. } else {
  194. parent::__construct('core', 'layout.base');
  195. }
  196. // Send the language and the locale to our layouts
  197. $lang = \OC::$server->getL10NFactory()->findLanguage();
  198. $locale = \OC::$server->getL10NFactory()->findLocale($lang);
  199. $lang = str_replace('_', '-', $lang);
  200. $this->assign('language', $lang);
  201. $this->assign('locale', $locale);
  202. if ($this->config->getSystemValueBool('installed', false)) {
  203. if (empty(self::$versionHash)) {
  204. $v = \OC_App::getAppVersions();
  205. $v['core'] = implode('.', \OCP\Util::getVersion());
  206. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  207. }
  208. } else {
  209. self::$versionHash = md5('not installed');
  210. }
  211. // Add the js files
  212. // TODO: remove deprecated OC_Util injection
  213. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  214. $this->assign('jsfiles', []);
  215. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  216. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  217. // see https://github.com/nextcloud/server/pull/22636 for details
  218. $jsConfigHelper = new JSConfigHelper(
  219. \OCP\Util::getL10N('lib'),
  220. \OCP\Server::get(Defaults::class),
  221. $this->appManager,
  222. \OC::$server->getSession(),
  223. \OC::$server->getUserSession()->getUser(),
  224. $this->config,
  225. \OC::$server->getGroupManager(),
  226. \OC::$server->get(IniGetWrapper::class),
  227. \OC::$server->getURLGenerator(),
  228. \OC::$server->get(CapabilitiesManager::class),
  229. \OCP\Server::get(IInitialStateService::class),
  230. \OCP\Server::get(IProvider::class),
  231. );
  232. $config = $jsConfigHelper->getConfig();
  233. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  234. $this->assign('inline_ocjs', $config);
  235. } else {
  236. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  237. }
  238. }
  239. foreach ($jsFiles as $info) {
  240. $web = $info[1];
  241. $file = $info[2];
  242. $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  243. }
  244. try {
  245. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  246. } catch (\Exception $e) {
  247. $pathInfo = '';
  248. }
  249. // Do not initialise scss appdata until we have a fully installed instance
  250. // Do not load scss for update, errors, installation or login page
  251. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  252. && !\OCP\Util::needUpgrade()
  253. && $pathInfo !== ''
  254. && $pathInfo !== false
  255. && !preg_match('/^\/login/', $pathInfo)
  256. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  257. ) {
  258. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  259. } else {
  260. // If we ignore the scss compiler,
  261. // we need to load the guest css fallback
  262. \OC_Util::addStyle('guest');
  263. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  264. }
  265. $this->assign('cssfiles', []);
  266. $this->assign('printcssfiles', []);
  267. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  268. foreach ($cssFiles as $info) {
  269. $web = $info[1];
  270. $file = $info[2];
  271. if (str_ends_with($file, 'print.css')) {
  272. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  273. } else {
  274. $suffix = $this->getVersionHashSuffix($web, $file);
  275. if (!str_contains($file, '?v=')) {
  276. $this->append('cssfiles', $web.'/'.$file . $suffix);
  277. } else {
  278. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  279. }
  280. }
  281. }
  282. $this->assign('initialStates', $this->initialState->getInitialStates());
  283. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  284. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  285. }
  286. protected function getVersionHashSuffix(string $path = '', string $file = ''): string {
  287. if ($this->config->getSystemValueBool('debug', false)) {
  288. // allows chrome workspace mapping in debug mode
  289. return "";
  290. }
  291. if ($this->config->getSystemValueBool('installed', false) === false) {
  292. // if not installed just return the version hash
  293. return '?v=' . self::$versionHash;
  294. }
  295. $hash = false;
  296. // Try the web-root first
  297. if ($path !== '') {
  298. $hash = $this->getVersionHashByPath($path);
  299. }
  300. // If not found try the file
  301. if ($hash === false && $file !== '') {
  302. $hash = $this->getVersionHashByPath($file);
  303. }
  304. // As a last resort we use the server version hash
  305. if ($hash === false) {
  306. $hash = self::$versionHash;
  307. }
  308. // The theming app is force-enabled thus the cache buster is always available
  309. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  310. return '?v=' . $hash . $themingSuffix;
  311. }
  312. private function getVersionHashByPath(string $path): string|false {
  313. if (array_key_exists($path, self::$cacheBusterCache) === false) {
  314. // Not yet cached, so lets find the cache buster string
  315. $appId = $this->getAppNamefromPath($path);
  316. if ($appId === false) {
  317. // No app Id could be guessed
  318. return false;
  319. }
  320. $appVersion = $this->appManager->getAppVersion($appId);
  321. // For shipped apps the app version is not a single source of truth, we rather also need to consider the Nextcloud version
  322. if ($this->appManager->isShipped($appId)) {
  323. $appVersion .= '-' . self::$versionHash;
  324. }
  325. $hash = substr(md5($appVersion), 0, 8);
  326. self::$cacheBusterCache[$path] = $hash;
  327. }
  328. return self::$cacheBusterCache[$path];
  329. }
  330. /**
  331. * @param array $styles
  332. * @return array
  333. */
  334. public static function findStylesheetFiles($styles) {
  335. if (!self::$cssLocator) {
  336. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  337. }
  338. self::$cssLocator->find($styles);
  339. return self::$cssLocator->getResources();
  340. }
  341. /**
  342. * @return string|false
  343. */
  344. public function getAppNamefromPath(string $path) {
  345. if ($path !== '') {
  346. $pathParts = explode('/', $path);
  347. if ($pathParts[0] === 'css') {
  348. // This is a scss request
  349. return $pathParts[1];
  350. }
  351. return end($pathParts);
  352. }
  353. return false;
  354. }
  355. /**
  356. * @param array $scripts
  357. * @return array
  358. */
  359. public static function findJavascriptFiles($scripts) {
  360. if (!self::$jsLocator) {
  361. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  362. }
  363. self::$jsLocator->find($scripts);
  364. return self::$jsLocator->getResources();
  365. }
  366. /**
  367. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  368. * @param string $filePath Absolute path
  369. * @return string Relative path
  370. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  371. */
  372. public static function convertToRelativePath($filePath) {
  373. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  374. if (count($relativePath) !== 2) {
  375. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  376. }
  377. return $relativePath[1];
  378. }
  379. }