TemplateLayout.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 entry name
  86. $defaultEntryId = \OCP\Server::get(INavigationManager::class)->getDefaultEntryIdForUser();
  87. $defaultEntry = \OCP\Server::get(INavigationManager::class)->get($defaultEntryId);
  88. $this->assign('defaultAppName', $defaultEntry['name']);
  89. // Add navigation entry
  90. $this->assign('application', '');
  91. $this->assign('appid', $appId);
  92. $navigation = $this->navigationManager->getAll();
  93. $this->assign('navigation', $navigation);
  94. $settingsNavigation = $this->navigationManager->getAll('settings');
  95. $this->initialState->provideInitialState('core', 'settingsNavEntries', $settingsNavigation);
  96. foreach ($navigation as $entry) {
  97. if ($entry['active']) {
  98. $this->assign('application', $entry['name']);
  99. break;
  100. }
  101. }
  102. foreach ($settingsNavigation as $entry) {
  103. if ($entry['active']) {
  104. $this->assign('application', $entry['name']);
  105. break;
  106. }
  107. }
  108. $userDisplayName = false;
  109. $user = \OC::$server->get(IUserSession::class)->getUser();
  110. if ($user) {
  111. $userDisplayName = $user->getDisplayName();
  112. }
  113. $this->assign('user_displayname', $userDisplayName);
  114. $this->assign('user_uid', \OC_User::getUser());
  115. if ($user === null) {
  116. $this->assign('userAvatarSet', false);
  117. $this->assign('userStatus', false);
  118. } else {
  119. $this->assign('userAvatarSet', true);
  120. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  121. }
  122. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  123. parent::__construct('core', 'layout.guest', '', false);
  124. $this->assign('bodyid', 'body-login');
  125. $this->assign('user_displayname', '');
  126. $this->assign('user_uid', '');
  127. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  128. parent::__construct('core', 'layout.guest');
  129. \OC_Util::addStyle('guest');
  130. $this->assign('bodyid', 'body-login');
  131. $userDisplayName = false;
  132. $user = \OC::$server->get(IUserSession::class)->getUser();
  133. if ($user) {
  134. $userDisplayName = $user->getDisplayName();
  135. }
  136. $this->assign('user_displayname', $userDisplayName);
  137. $this->assign('user_uid', \OC_User::getUser());
  138. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  139. parent::__construct('core', 'layout.public');
  140. $this->assign('appid', $appId);
  141. $this->assign('bodyid', 'body-public');
  142. // Set logo link target
  143. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  144. $this->assign('logoUrl', $logoUrl);
  145. /** @var IRegistry $subscription */
  146. $subscription = \OCP\Server::get(IRegistry::class);
  147. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  148. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  149. $showSimpleSignup = false;
  150. }
  151. $defaultSignUpLink = 'https://nextcloud.com/signup/';
  152. $signUpLink = $this->config->getSystemValueString('registration_link', $defaultSignUpLink);
  153. if ($signUpLink !== $defaultSignUpLink) {
  154. $showSimpleSignup = true;
  155. }
  156. $appManager = \OCP\Server::get(IAppManager::class);
  157. if ($appManager->isEnabledForUser('registration')) {
  158. $urlGenerator = \OCP\Server::get(IURLGenerator::class);
  159. $signUpLink = $urlGenerator->getAbsoluteURL('/index.php/apps/registration/');
  160. }
  161. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  162. $this->assign('signUpLink', $signUpLink);
  163. } else {
  164. parent::__construct('core', 'layout.base');
  165. }
  166. // Send the language and the locale to our layouts
  167. $lang = \OC::$server->get(IFactory::class)->findLanguage();
  168. $locale = \OC::$server->get(IFactory::class)->findLocale($lang);
  169. $lang = str_replace('_', '-', $lang);
  170. $this->assign('language', $lang);
  171. $this->assign('locale', $locale);
  172. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  173. if (empty(self::$versionHash)) {
  174. $v = \OC_App::getAppVersions();
  175. $v['core'] = implode('.', \OCP\Util::getVersion());
  176. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  177. }
  178. } else {
  179. self::$versionHash = md5('not installed');
  180. }
  181. // Add the js files
  182. // TODO: remove deprecated OC_Util injection
  183. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  184. $this->assign('jsfiles', []);
  185. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  186. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  187. // see https://github.com/nextcloud/server/pull/22636 for details
  188. $jsConfigHelper = new JSConfigHelper(
  189. \OCP\Util::getL10N('lib'),
  190. \OCP\Server::get(Defaults::class),
  191. \OC::$server->getAppManager(),
  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. $themingSuffix = '';
  273. $v = [];
  274. if ($this->config->getSystemValueBool('installed', false)) {
  275. if (\OC::$server->getAppManager()->isInstalled('theming')) {
  276. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  277. }
  278. $v = \OC_App::getAppVersions();
  279. }
  280. // Try the webroot path for a match
  281. if ($path !== false && $path !== '') {
  282. $appName = $this->getAppNamefromPath($path);
  283. if (array_key_exists($appName, $v)) {
  284. $appVersion = $v[$appName];
  285. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  286. }
  287. }
  288. // fallback to the file path instead
  289. if ($file !== false && $file !== '') {
  290. $appName = $this->getAppNamefromPath($file);
  291. if (array_key_exists($appName, $v)) {
  292. $appVersion = $v[$appName];
  293. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  294. }
  295. }
  296. return '?v=' . self::$versionHash . $themingSuffix;
  297. }
  298. /**
  299. * @param array $styles
  300. * @return array
  301. */
  302. public static function findStylesheetFiles($styles, $compileScss = true) {
  303. if (!self::$cssLocator) {
  304. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  305. }
  306. self::$cssLocator->find($styles);
  307. return self::$cssLocator->getResources();
  308. }
  309. /**
  310. * @param string $path
  311. * @return string|boolean
  312. */
  313. public function getAppNamefromPath($path) {
  314. if ($path !== '' && is_string($path)) {
  315. $pathParts = explode('/', $path);
  316. if ($pathParts[0] === 'css') {
  317. // This is a scss request
  318. return $pathParts[1];
  319. }
  320. return end($pathParts);
  321. }
  322. return false;
  323. }
  324. /**
  325. * @param array $scripts
  326. * @return array
  327. */
  328. public static function findJavascriptFiles($scripts) {
  329. if (!self::$jsLocator) {
  330. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  331. }
  332. self::$jsLocator->find($scripts);
  333. return self::$jsLocator->getResources();
  334. }
  335. /**
  336. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  337. * @param string $filePath Absolute path
  338. * @return string Relative path
  339. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  340. */
  341. public static function convertToRelativePath($filePath) {
  342. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  343. if (count($relativePath) !== 2) {
  344. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  345. }
  346. return $relativePath[1];
  347. }
  348. }