TemplateLayout.php 14 KB

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