1
0

TemplateLayout.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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\ServerVersion;
  27. use OCP\Support\Subscription\IRegistry;
  28. use OCP\Util;
  29. class TemplateLayout extends \OC_Template {
  30. private static $versionHash = '';
  31. /** @var string[] */
  32. private static $cacheBusterCache = [];
  33. /** @var CSSResourceLocator|null */
  34. public static $cssLocator = null;
  35. /** @var JSResourceLocator|null */
  36. public static $jsLocator = null;
  37. private IConfig $config;
  38. private IAppManager $appManager;
  39. private InitialStateService $initialState;
  40. private INavigationManager $navigationManager;
  41. /**
  42. * @param string $renderAs
  43. * @param string $appId application id
  44. */
  45. public function __construct($renderAs, $appId = '') {
  46. $this->config = \OCP\Server::get(IConfig::class);
  47. $this->appManager = \OCP\Server::get(IAppManager::class);
  48. $this->initialState = \OCP\Server::get(InitialStateService::class);
  49. $this->navigationManager = \OCP\Server::get(INavigationManager::class);
  50. // Add fallback theming variables if not rendered as user
  51. if ($renderAs !== TemplateResponse::RENDER_AS_USER) {
  52. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  53. Util::addStyle('theming', 'default');
  54. }
  55. // Decide which page we show
  56. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  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 ($this->appManager->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 entry name
  84. $defaultEntryId = $this->navigationManager->getDefaultEntryIdForUser();
  85. $defaultEntry = $this->navigationManager->get($defaultEntryId);
  86. $this->assign('defaultAppName', $defaultEntry['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, locale, and direction to our layouts
  164. $lang = \OC::$server->get(IFactory::class)->findLanguage();
  165. $locale = \OC::$server->get(IFactory::class)->findLocale($lang);
  166. $direction = \OC::$server->getL10NFactory()->getLanguageDirection($lang);
  167. $lang = str_replace('_', '-', $lang);
  168. $this->assign('language', $lang);
  169. $this->assign('locale', $locale);
  170. $this->assign('direction', $direction);
  171. if ($this->config->getSystemValueBool('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\Server::get(ServerVersion::class),
  189. \OCP\Util::getL10N('lib'),
  190. \OCP\Server::get(Defaults::class),
  191. $this->appManager,
  192. \OC::$server->getSession(),
  193. \OC::$server->getUserSession()->getUser(),
  194. $this->config,
  195. \OC::$server->getGroupManager(),
  196. \OC::$server->get(IniGetWrapper::class),
  197. \OC::$server->getURLGenerator(),
  198. \OC::$server->get(CapabilitiesManager::class),
  199. \OCP\Server::get(IInitialStateService::class),
  200. \OCP\Server::get(IProvider::class),
  201. \OCP\Server::get(FilenameValidator::class),
  202. );
  203. $config = $jsConfigHelper->getConfig();
  204. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  205. $this->assign('inline_ocjs', $config);
  206. } else {
  207. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  208. }
  209. }
  210. foreach ($jsFiles as $info) {
  211. $web = $info[1];
  212. $file = $info[2];
  213. $this->append('jsfiles', $web . '/' . $file . $this->getVersionHashSuffix());
  214. }
  215. try {
  216. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  217. } catch (\Exception $e) {
  218. $pathInfo = '';
  219. }
  220. // Do not initialise scss appdata until we have a fully installed instance
  221. // Do not load scss for update, errors, installation or login page
  222. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  223. && !\OCP\Util::needUpgrade()
  224. && $pathInfo !== ''
  225. && !preg_match('/^\/login/', $pathInfo)
  226. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  227. ) {
  228. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  229. } else {
  230. // If we ignore the scss compiler,
  231. // we need to load the guest css fallback
  232. \OC_Util::addStyle('guest');
  233. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  234. }
  235. $this->assign('cssfiles', []);
  236. $this->assign('printcssfiles', []);
  237. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  238. foreach ($cssFiles as $info) {
  239. $web = $info[1];
  240. $file = $info[2];
  241. if (str_ends_with($file, 'print.css')) {
  242. $this->append('printcssfiles', $web . '/' . $file . $this->getVersionHashSuffix());
  243. } else {
  244. $suffix = $this->getVersionHashSuffix($web, $file);
  245. if (!str_contains($file, '?v=')) {
  246. $this->append('cssfiles', $web . '/' . $file . $suffix);
  247. } else {
  248. $this->append('cssfiles', $web . '/' . $file . '-' . substr($suffix, 3));
  249. }
  250. }
  251. }
  252. $request = \OCP\Server::get(IRequest::class);
  253. if ($request->isUserAgent([Request::USER_AGENT_CLIENT_IOS, Request::USER_AGENT_SAFARI, Request::USER_AGENT_SAFARI_MOBILE])) {
  254. // Prevent auto zoom with iOS but still allow user zoom
  255. // On chrome (and others) this does not work (will also disable user zoom)
  256. $this->assign('viewport_maximum_scale', '1.0');
  257. }
  258. $this->assign('initialStates', $this->initialState->getInitialStates());
  259. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  260. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  261. }
  262. /**
  263. * @param string $path
  264. * @param string $file
  265. * @return string
  266. */
  267. protected function getVersionHashSuffix($path = false, $file = false) {
  268. if ($this->config->getSystemValueBool('debug', false)) {
  269. // allows chrome workspace mapping in debug mode
  270. return '';
  271. }
  272. if ($this->config->getSystemValueBool('installed', false) === false) {
  273. // if not installed just return the version hash
  274. return '?v=' . self::$versionHash;
  275. }
  276. $hash = false;
  277. // Try the web-root first
  278. if (is_string($path) && $path !== '') {
  279. $hash = $this->getVersionHashByPath($path);
  280. }
  281. // If not found try the file
  282. if ($hash === false && is_string($file) && $file !== '') {
  283. $hash = $this->getVersionHashByPath($file);
  284. }
  285. // As a last resort we use the server version hash
  286. if ($hash === false) {
  287. $hash = self::$versionHash;
  288. }
  289. // The theming app is force-enabled thus the cache buster is always available
  290. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  291. return '?v=' . $hash . $themingSuffix;
  292. }
  293. private function getVersionHashByPath(string $path): string|false {
  294. if (array_key_exists($path, self::$cacheBusterCache) === false) {
  295. // Not yet cached, so lets find the cache buster string
  296. $appId = $this->getAppNamefromPath($path);
  297. if ($appId === false || $appId === null) {
  298. // No app Id could be guessed
  299. return false;
  300. }
  301. $appVersion = $this->appManager->getAppVersion($appId);
  302. // For shipped apps the app version is not a single source of truth, we rather also need to consider the Nextcloud version
  303. if ($this->appManager->isShipped($appId)) {
  304. $appVersion .= '-' . self::$versionHash;
  305. }
  306. $hash = substr(md5($appVersion), 0, 8);
  307. self::$cacheBusterCache[$path] = $hash;
  308. }
  309. return self::$cacheBusterCache[$path];
  310. }
  311. /**
  312. * @param array $styles
  313. * @return array
  314. */
  315. public static function findStylesheetFiles($styles, $compileScss = true) {
  316. if (!self::$cssLocator) {
  317. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  318. }
  319. self::$cssLocator->find($styles);
  320. return self::$cssLocator->getResources();
  321. }
  322. /**
  323. * @param string $path
  324. * @return string|boolean
  325. */
  326. public function getAppNamefromPath($path) {
  327. if ($path !== '' && is_string($path)) {
  328. $pathParts = explode('/', $path);
  329. if ($pathParts[0] === 'css') {
  330. // This is a scss request
  331. return $pathParts[1];
  332. }
  333. return end($pathParts);
  334. }
  335. return false;
  336. }
  337. /**
  338. * @param array $scripts
  339. * @return array
  340. */
  341. public static function findJavascriptFiles($scripts) {
  342. if (!self::$jsLocator) {
  343. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  344. }
  345. self::$jsLocator->find($scripts);
  346. return self::$jsLocator->getResources();
  347. }
  348. /**
  349. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  350. * @param string $filePath Absolute path
  351. * @return string Relative path
  352. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  353. */
  354. public static function convertToRelativePath($filePath) {
  355. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  356. if (count($relativePath) !== 2) {
  357. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  358. }
  359. return $relativePath[1];
  360. }
  361. }