TemplateLayout.php 13 KB

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