TemplateLayout.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 CSSResourceLocator|null */
  32. public static $cssLocator = null;
  33. /** @var JSResourceLocator|null */
  34. public static $jsLocator = null;
  35. /** @var IConfig */
  36. private $config;
  37. /** @var IInitialStateService */
  38. private $initialState;
  39. /** @var INavigationManager */
  40. private $navigationManager;
  41. /**
  42. * @param string $renderAs
  43. * @param string $appId application id
  44. */
  45. public function __construct($renderAs, $appId = '') {
  46. /** @var IConfig */
  47. $this->config = \OC::$server->get(IConfig::class);
  48. /** @var IInitialStateService */
  49. $this->initialState = \OC::$server->get(IInitialStateService::class);
  50. // Add fallback theming variables if theming is disabled
  51. if ($renderAs !== TemplateResponse::RENDER_AS_USER
  52. || !\OC::$server->getAppManager()->isEnabledForUser('theming')) {
  53. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  54. Util::addStyle('theming', 'default');
  55. }
  56. // Decide which page we show
  57. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  58. /** @var INavigationManager */
  59. $this->navigationManager = \OC::$server->get(INavigationManager::class);
  60. parent::__construct('core', 'layout.user');
  61. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  62. $this->assign('bodyid', 'body-settings');
  63. } else {
  64. $this->assign('bodyid', 'body-user');
  65. }
  66. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  67. $this->initialState->provideInitialState('core', 'apps', array_values($this->navigationManager->getAll()));
  68. if ($this->config->getSystemValueBool('unified_search.enabled', false) || !$this->config->getSystemValueBool('enable_non-accessible_features', true)) {
  69. $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
  70. $this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
  71. $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
  72. Util::addScript('core', 'legacy-unified-search', 'core');
  73. } else {
  74. Util::addScript('core', 'unified-search', 'core');
  75. }
  76. // Set body data-theme
  77. $this->assign('enabledThemes', []);
  78. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
  79. /** @var \OCA\Theming\Service\ThemesService */
  80. $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
  81. $this->assign('enabledThemes', $themesService->getEnabledThemes());
  82. }
  83. // Set logo link target
  84. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  85. $this->assign('logoUrl', $logoUrl);
  86. // Set default entry name
  87. $defaultEntryId = \OCP\Server::get(INavigationManager::class)->getDefaultEntryIdForUser();
  88. $defaultEntry = \OCP\Server::get(INavigationManager::class)->get($defaultEntryId);
  89. $this->assign('defaultAppName', $defaultEntry['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, locale, and direction to our layouts
  168. $lang = \OC::$server->get(IFactory::class)->findLanguage();
  169. $locale = \OC::$server->get(IFactory::class)->findLocale($lang);
  170. $direction = \OC::$server->getL10NFactory()->getLanguageDirection($lang);
  171. $lang = str_replace('_', '-', $lang);
  172. $this->assign('language', $lang);
  173. $this->assign('locale', $locale);
  174. $this->assign('direction', $direction);
  175. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  176. if (empty(self::$versionHash)) {
  177. $v = \OC_App::getAppVersions();
  178. $v['core'] = implode('.', \OCP\Util::getVersion());
  179. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  180. }
  181. } else {
  182. self::$versionHash = md5('not installed');
  183. }
  184. // Add the js files
  185. // TODO: remove deprecated OC_Util injection
  186. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  187. $this->assign('jsfiles', []);
  188. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  189. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  190. // see https://github.com/nextcloud/server/pull/22636 for details
  191. $jsConfigHelper = new JSConfigHelper(
  192. \OCP\Server::get(ServerVersion::class),
  193. \OCP\Util::getL10N('lib'),
  194. \OCP\Server::get(Defaults::class),
  195. \OC::$server->getAppManager(),
  196. \OC::$server->getSession(),
  197. \OC::$server->getUserSession()->getUser(),
  198. $this->config,
  199. \OC::$server->getGroupManager(),
  200. \OC::$server->get(IniGetWrapper::class),
  201. \OC::$server->getURLGenerator(),
  202. \OC::$server->get(CapabilitiesManager::class),
  203. \OCP\Server::get(IInitialStateService::class),
  204. \OCP\Server::get(IProvider::class),
  205. \OCP\Server::get(FilenameValidator::class),
  206. );
  207. $config = $jsConfigHelper->getConfig();
  208. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  209. $this->assign('inline_ocjs', $config);
  210. } else {
  211. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  212. }
  213. }
  214. foreach ($jsFiles as $info) {
  215. $web = $info[1];
  216. $file = $info[2];
  217. $this->append('jsfiles', $web . '/' . $file . $this->getVersionHashSuffix());
  218. }
  219. try {
  220. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  221. } catch (\Exception $e) {
  222. $pathInfo = '';
  223. }
  224. // Do not initialise scss appdata until we have a fully installed instance
  225. // Do not load scss for update, errors, installation or login page
  226. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  227. && !\OCP\Util::needUpgrade()
  228. && $pathInfo !== ''
  229. && !preg_match('/^\/login/', $pathInfo)
  230. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  231. ) {
  232. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  233. } else {
  234. // If we ignore the scss compiler,
  235. // we need to load the guest css fallback
  236. \OC_Util::addStyle('guest');
  237. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  238. }
  239. $this->assign('cssfiles', []);
  240. $this->assign('printcssfiles', []);
  241. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  242. foreach ($cssFiles as $info) {
  243. $web = $info[1];
  244. $file = $info[2];
  245. if (str_ends_with($file, 'print.css')) {
  246. $this->append('printcssfiles', $web . '/' . $file . $this->getVersionHashSuffix());
  247. } else {
  248. $suffix = $this->getVersionHashSuffix($web, $file);
  249. if (!str_contains($file, '?v=')) {
  250. $this->append('cssfiles', $web . '/' . $file . $suffix);
  251. } else {
  252. $this->append('cssfiles', $web . '/' . $file . '-' . substr($suffix, 3));
  253. }
  254. }
  255. }
  256. $request = \OCP\Server::get(IRequest::class);
  257. if ($request->isUserAgent([Request::USER_AGENT_CLIENT_IOS, Request::USER_AGENT_SAFARI, Request::USER_AGENT_SAFARI_MOBILE])) {
  258. // Prevent auto zoom with iOS but still allow user zoom
  259. // On chrome (and others) this does not work (will also disable user zoom)
  260. $this->assign('viewport_maximum_scale', '1.0');
  261. }
  262. $this->assign('initialStates', $this->initialState->getInitialStates());
  263. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  264. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  265. }
  266. /**
  267. * @param string $path
  268. * @param string $file
  269. * @return string
  270. */
  271. protected function getVersionHashSuffix($path = false, $file = false) {
  272. if ($this->config->getSystemValueBool('debug', false)) {
  273. // allows chrome workspace mapping in debug mode
  274. return '';
  275. }
  276. $themingSuffix = '';
  277. $v = [];
  278. if ($this->config->getSystemValueBool('installed', false)) {
  279. if (\OC::$server->getAppManager()->isInstalled('theming')) {
  280. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  281. }
  282. $v = \OC_App::getAppVersions();
  283. }
  284. // Try the webroot path for a match
  285. if ($path !== false && $path !== '') {
  286. $appName = $this->getAppNamefromPath($path);
  287. if (array_key_exists($appName, $v)) {
  288. $appVersion = $v[$appName];
  289. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  290. }
  291. }
  292. // fallback to the file path instead
  293. if ($file !== false && $file !== '') {
  294. $appName = $this->getAppNamefromPath($file);
  295. if (array_key_exists($appName, $v)) {
  296. $appVersion = $v[$appName];
  297. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  298. }
  299. }
  300. return '?v=' . self::$versionHash . $themingSuffix;
  301. }
  302. /**
  303. * @param array $styles
  304. * @return array
  305. */
  306. public static function findStylesheetFiles($styles, $compileScss = true) {
  307. if (!self::$cssLocator) {
  308. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  309. }
  310. self::$cssLocator->find($styles);
  311. return self::$cssLocator->getResources();
  312. }
  313. /**
  314. * @param string $path
  315. * @return string|boolean
  316. */
  317. public function getAppNamefromPath($path) {
  318. if ($path !== '' && is_string($path)) {
  319. $pathParts = explode('/', $path);
  320. if ($pathParts[0] === 'css') {
  321. // This is a scss request
  322. return $pathParts[1];
  323. }
  324. return end($pathParts);
  325. }
  326. return false;
  327. }
  328. /**
  329. * @param array $scripts
  330. * @return array
  331. */
  332. public static function findJavascriptFiles($scripts) {
  333. if (!self::$jsLocator) {
  334. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  335. }
  336. self::$jsLocator->find($scripts);
  337. return self::$jsLocator->getResources();
  338. }
  339. /**
  340. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  341. * @param string $filePath Absolute path
  342. * @return string Relative path
  343. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  344. */
  345. public static function convertToRelativePath($filePath) {
  346. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  347. if (count($relativePath) !== 2) {
  348. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  349. }
  350. return $relativePath[1];
  351. }
  352. }