1
0

TemplateLayout.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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\AppFramework\Http\Request;
  10. use OC\Authentication\Token\IProvider;
  11. use OC\Files\FilenameValidator;
  12. use OC\Search\SearchQuery;
  13. use OC\Template\CSSResourceLocator;
  14. use OC\Template\JSConfigHelper;
  15. use OC\Template\JSResourceLocator;
  16. use OCP\App\IAppManager;
  17. use OCP\AppFramework\Http\TemplateResponse;
  18. use OCP\Defaults;
  19. use OCP\IConfig;
  20. use OCP\IInitialStateService;
  21. use OCP\INavigationManager;
  22. use OCP\IRequest;
  23. use OCP\IURLGenerator;
  24. use OCP\IUserSession;
  25. use OCP\L10N\IFactory;
  26. use OCP\Support\Subscription\IRegistry;
  27. use OCP\Util;
  28. class TemplateLayout extends \OC_Template {
  29. private static $versionHash = '';
  30. /** @var string[] */
  31. private static $cacheBusterCache = [];
  32. /** @var CSSResourceLocator|null */
  33. public static $cssLocator = null;
  34. /** @var JSResourceLocator|null */
  35. public static $jsLocator = null;
  36. private IConfig $config;
  37. private IAppManager $appManager;
  38. private InitialStateService $initialState;
  39. private INavigationManager $navigationManager;
  40. /**
  41. * @param string $renderAs
  42. * @param string $appId application id
  43. */
  44. public function __construct($renderAs, $appId = '') {
  45. $this->config = \OCP\Server::get(IConfig::class);
  46. $this->appManager = \OCP\Server::get(IAppManager::class);
  47. $this->initialState = \OCP\Server::get(InitialStateService::class);
  48. $this->navigationManager = \OCP\Server::get(INavigationManager::class);
  49. // Add fallback theming variables if not rendered as user
  50. if ($renderAs !== TemplateResponse::RENDER_AS_USER) {
  51. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  52. Util::addStyle('theming', 'default');
  53. }
  54. // Decide which page we show
  55. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  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', array_values($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 ($this->appManager->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 = $this->appManager->getDefaultAppForUser();
  84. $defaultAppInfo = $this->appManager->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. if ($this->appManager->isEnabledForUser('registration')) {
  155. $urlGenerator = \OCP\Server::get(IURLGenerator::class);
  156. $signUpLink = $urlGenerator->getAbsoluteURL('/index.php/apps/registration/');
  157. }
  158. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  159. $this->assign('signUpLink', $signUpLink);
  160. } else {
  161. parent::__construct('core', 'layout.base');
  162. }
  163. // Send the language and the locale to our layouts
  164. $lang = \OC::$server->get(IFactory::class)->findLanguage();
  165. $locale = \OC::$server->get(IFactory::class)->findLocale($lang);
  166. $lang = str_replace('_', '-', $lang);
  167. $this->assign('language', $lang);
  168. $this->assign('locale', $locale);
  169. if ($this->config->getSystemValueBool('installed', false)) {
  170. if (empty(self::$versionHash)) {
  171. $v = \OC_App::getAppVersions();
  172. $v['core'] = implode('.', \OCP\Util::getVersion());
  173. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  174. }
  175. } else {
  176. self::$versionHash = md5('not installed');
  177. }
  178. // Add the js files
  179. // TODO: remove deprecated OC_Util injection
  180. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  181. $this->assign('jsfiles', []);
  182. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  183. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  184. // see https://github.com/nextcloud/server/pull/22636 for details
  185. $jsConfigHelper = new JSConfigHelper(
  186. \OCP\Util::getL10N('lib'),
  187. \OCP\Server::get(Defaults::class),
  188. $this->appManager,
  189. \OC::$server->getSession(),
  190. \OC::$server->getUserSession()->getUser(),
  191. $this->config,
  192. \OC::$server->getGroupManager(),
  193. \OC::$server->get(IniGetWrapper::class),
  194. \OC::$server->getURLGenerator(),
  195. \OC::$server->get(CapabilitiesManager::class),
  196. \OCP\Server::get(IInitialStateService::class),
  197. \OCP\Server::get(IProvider::class),
  198. \OCP\Server::get(FilenameValidator::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. && $pathInfo !== false
  223. && !preg_match('/^\/login/', $pathInfo)
  224. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  225. ) {
  226. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  227. } else {
  228. // If we ignore the scss compiler,
  229. // we need to load the guest css fallback
  230. \OC_Util::addStyle('guest');
  231. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  232. }
  233. $this->assign('cssfiles', []);
  234. $this->assign('printcssfiles', []);
  235. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  236. foreach ($cssFiles as $info) {
  237. $web = $info[1];
  238. $file = $info[2];
  239. if (str_ends_with($file, 'print.css')) {
  240. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  241. } else {
  242. $suffix = $this->getVersionHashSuffix($web, $file);
  243. if (!str_contains($file, '?v=')) {
  244. $this->append('cssfiles', $web.'/'.$file . $suffix);
  245. } else {
  246. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  247. }
  248. }
  249. }
  250. $request = \OCP\Server::get(IRequest::class);
  251. if ($request->isUserAgent([Request::USER_AGENT_CLIENT_IOS, Request::USER_AGENT_SAFARI, Request::USER_AGENT_SAFARI_MOBILE])) {
  252. // Prevent auto zoom with iOS but still allow user zoom
  253. // On chrome (and others) this does not work (will also disable user zoom)
  254. $this->assign('viewport_maximum_scale', '1.0');
  255. }
  256. $this->assign('initialStates', $this->initialState->getInitialStates());
  257. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  258. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  259. }
  260. protected function getVersionHashSuffix(string $path = '', string $file = ''): string {
  261. if ($this->config->getSystemValueBool('debug', false)) {
  262. // allows chrome workspace mapping in debug mode
  263. return "";
  264. }
  265. if ($this->config->getSystemValueBool('installed', false) === false) {
  266. // if not installed just return the version hash
  267. return '?v=' . self::$versionHash;
  268. }
  269. $hash = false;
  270. // Try the web-root first
  271. if ($path !== '') {
  272. $hash = $this->getVersionHashByPath($path);
  273. }
  274. // If not found try the file
  275. if ($hash === false && $file !== '') {
  276. $hash = $this->getVersionHashByPath($file);
  277. }
  278. // As a last resort we use the server version hash
  279. if ($hash === false) {
  280. $hash = self::$versionHash;
  281. }
  282. // The theming app is force-enabled thus the cache buster is always available
  283. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  284. return '?v=' . $hash . $themingSuffix;
  285. }
  286. private function getVersionHashByPath(string $path): string|false {
  287. if (array_key_exists($path, self::$cacheBusterCache) === false) {
  288. // Not yet cached, so lets find the cache buster string
  289. $appId = $this->getAppNamefromPath($path);
  290. if ($appId === false) {
  291. // No app Id could be guessed
  292. return false;
  293. }
  294. $appVersion = $this->appManager->getAppVersion($appId);
  295. // For shipped apps the app version is not a single source of truth, we rather also need to consider the Nextcloud version
  296. if ($this->appManager->isShipped($appId)) {
  297. $appVersion .= '-' . self::$versionHash;
  298. }
  299. $hash = substr(md5($appVersion), 0, 8);
  300. self::$cacheBusterCache[$path] = $hash;
  301. }
  302. return self::$cacheBusterCache[$path];
  303. }
  304. /**
  305. * @param array $styles
  306. * @return array
  307. */
  308. public static function findStylesheetFiles($styles) {
  309. if (!self::$cssLocator) {
  310. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  311. }
  312. self::$cssLocator->find($styles);
  313. return self::$cssLocator->getResources();
  314. }
  315. /**
  316. * @return string|false
  317. */
  318. public function getAppNamefromPath(string $path) {
  319. if ($path !== '') {
  320. $pathParts = explode('/', $path);
  321. if ($pathParts[0] === 'css') {
  322. // This is a scss request
  323. return $pathParts[1];
  324. }
  325. return end($pathParts);
  326. }
  327. return false;
  328. }
  329. /**
  330. * @param array $scripts
  331. * @return array
  332. */
  333. public static function findJavascriptFiles($scripts) {
  334. if (!self::$jsLocator) {
  335. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  336. }
  337. self::$jsLocator->find($scripts);
  338. return self::$jsLocator->getResources();
  339. }
  340. /**
  341. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  342. * @param string $filePath Absolute path
  343. * @return string Relative path
  344. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  345. */
  346. public static function convertToRelativePath($filePath) {
  347. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  348. if (count($relativePath) !== 2) {
  349. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  350. }
  351. return $relativePath[1];
  352. }
  353. }