1
0

TemplateLayout.php 13 KB

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