TemplateLayout.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christopher Schäpers <kondou@ts.unde.re>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Clark Tomlinson <fallen013@gmail.com>
  9. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  10. * @author Guillaume COMPAGNON <gcompagnon@outlook.com>
  11. * @author Hendrik Leppelsack <hendrik@leppelsack.de>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ <skjnldsv@protonmail.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Julius Haertl <jus@bitgrid.net>
  16. * @author Julius Härtl <jus@bitgrid.net>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Nils <git@to.nilsschnabel.de>
  21. * @author Remco Brenninkmeijer <requist1@starmail.nl>
  22. * @author Robin Appelman <robin@icewind.nl>
  23. * @author Robin McCorkell <robin@mccorkell.me.uk>
  24. * @author Roeland Jago Douma <roeland@famdouma.nl>
  25. * @author Thomas Citharel <nextcloud@tcit.fr>
  26. * @author Thomas Müller <thomas.mueller@tmit.eu>
  27. *
  28. * @license AGPL-3.0
  29. *
  30. * This code is free software: you can redistribute it and/or modify
  31. * it under the terms of the GNU Affero General Public License, version 3,
  32. * as published by the Free Software Foundation.
  33. *
  34. * This program is distributed in the hope that it will be useful,
  35. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  36. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  37. * GNU Affero General Public License for more details.
  38. *
  39. * You should have received a copy of the GNU Affero General Public License, version 3,
  40. * along with this program. If not, see <http://www.gnu.org/licenses/>
  41. *
  42. */
  43. namespace OC;
  44. use bantu\IniGetWrapper\IniGetWrapper;
  45. use OC\Authentication\Token\IProvider;
  46. use OC\Search\SearchQuery;
  47. use OC\Template\CSSResourceLocator;
  48. use OC\Template\JSConfigHelper;
  49. use OC\Template\JSResourceLocator;
  50. use OCP\App\IAppManager;
  51. use OCP\AppFramework\Http\TemplateResponse;
  52. use OCP\Defaults;
  53. use OCP\IConfig;
  54. use OCP\IInitialStateService;
  55. use OCP\INavigationManager;
  56. use OCP\IURLGenerator;
  57. use OCP\IUserSession;
  58. use OCP\Support\Subscription\IRegistry;
  59. use OCP\Util;
  60. class TemplateLayout extends \OC_Template {
  61. private static $versionHash = '';
  62. /** @var CSSResourceLocator|null */
  63. public static $cssLocator = null;
  64. /** @var JSResourceLocator|null */
  65. public static $jsLocator = null;
  66. /** @var IConfig */
  67. private $config;
  68. /** @var IInitialStateService */
  69. private $initialState;
  70. /** @var INavigationManager */
  71. private $navigationManager;
  72. /**
  73. * @param string $renderAs
  74. * @param string $appId application id
  75. */
  76. public function __construct($renderAs, $appId = '') {
  77. /** @var IConfig */
  78. $this->config = \OC::$server->get(IConfig::class);
  79. /** @var IInitialStateService */
  80. $this->initialState = \OC::$server->get(IInitialStateService::class);
  81. // Add fallback theming variables if theming is disabled
  82. if ($renderAs !== TemplateResponse::RENDER_AS_USER
  83. || !\OC::$server->getAppManager()->isEnabledForUser('theming')) {
  84. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  85. Util::addStyle('theming', 'default');
  86. }
  87. // Decide which page we show
  88. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  89. /** @var INavigationManager */
  90. $this->navigationManager = \OC::$server->get(INavigationManager::class);
  91. parent::__construct('core', 'layout.user');
  92. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  93. $this->assign('bodyid', 'body-settings');
  94. } else {
  95. $this->assign('bodyid', 'body-user');
  96. }
  97. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  98. $this->initialState->provideInitialState('core', 'apps', $this->navigationManager->getAll());
  99. if ($this->config->getSystemValueBool('unified_search.enabled', false) || !$this->config->getSystemValueBool('enable_non-accessible_features', true)) {
  100. $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
  101. $this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
  102. $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
  103. Util::addScript('core', 'legacy-unified-search', 'core');
  104. } else {
  105. Util::addScript('core', 'unified-search', 'core');
  106. }
  107. // Set body data-theme
  108. $this->assign('enabledThemes', []);
  109. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
  110. /** @var \OCA\Theming\Service\ThemesService */
  111. $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
  112. $this->assign('enabledThemes', $themesService->getEnabledThemes());
  113. }
  114. // Set logo link target
  115. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  116. $this->assign('logoUrl', $logoUrl);
  117. // Set default app name
  118. $defaultApp = \OC::$server->getAppManager()->getDefaultAppForUser();
  119. $defaultAppInfo = \OC::$server->getAppManager()->getAppInfo($defaultApp);
  120. $l10n = \OC::$server->getL10NFactory()->get($defaultApp);
  121. $this->assign('defaultAppName', $l10n->t($defaultAppInfo['name']));
  122. // Add navigation entry
  123. $this->assign('application', '');
  124. $this->assign('appid', $appId);
  125. $navigation = $this->navigationManager->getAll();
  126. $this->assign('navigation', $navigation);
  127. $settingsNavigation = $this->navigationManager->getAll('settings');
  128. $this->initialState->provideInitialState('core', 'settingsNavEntries', $settingsNavigation);
  129. foreach ($navigation as $entry) {
  130. if ($entry['active']) {
  131. $this->assign('application', $entry['name']);
  132. break;
  133. }
  134. }
  135. foreach ($settingsNavigation as $entry) {
  136. if ($entry['active']) {
  137. $this->assign('application', $entry['name']);
  138. break;
  139. }
  140. }
  141. $userDisplayName = false;
  142. $user = \OC::$server->get(IUserSession::class)->getUser();
  143. if ($user) {
  144. $userDisplayName = $user->getDisplayName();
  145. }
  146. $this->assign('user_displayname', $userDisplayName);
  147. $this->assign('user_uid', \OC_User::getUser());
  148. if ($user === null) {
  149. $this->assign('userAvatarSet', false);
  150. $this->assign('userStatus', false);
  151. } else {
  152. $this->assign('userAvatarSet', true);
  153. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  154. }
  155. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  156. parent::__construct('core', 'layout.guest', '', false);
  157. $this->assign('bodyid', 'body-login');
  158. $this->assign('user_displayname', '');
  159. $this->assign('user_uid', '');
  160. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  161. parent::__construct('core', 'layout.guest');
  162. \OC_Util::addStyle('guest');
  163. $this->assign('bodyid', 'body-login');
  164. $userDisplayName = false;
  165. $user = \OC::$server->get(IUserSession::class)->getUser();
  166. if ($user) {
  167. $userDisplayName = $user->getDisplayName();
  168. }
  169. $this->assign('user_displayname', $userDisplayName);
  170. $this->assign('user_uid', \OC_User::getUser());
  171. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  172. parent::__construct('core', 'layout.public');
  173. $this->assign('appid', $appId);
  174. $this->assign('bodyid', 'body-public');
  175. // Set logo link target
  176. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  177. $this->assign('logoUrl', $logoUrl);
  178. /** @var IRegistry $subscription */
  179. $subscription = \OCP\Server::get(IRegistry::class);
  180. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  181. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  182. $showSimpleSignup = false;
  183. }
  184. $defaultSignUpLink = 'https://nextcloud.com/signup/';
  185. $signUpLink = $this->config->getSystemValueString('registration_link', $defaultSignUpLink);
  186. if ($signUpLink !== $defaultSignUpLink) {
  187. $showSimpleSignup = true;
  188. }
  189. $appManager = \OCP\Server::get(IAppManager::class);
  190. if ($appManager->isEnabledForUser('registration')) {
  191. $urlGenerator = \OCP\Server::get(IURLGenerator::class);
  192. $signUpLink = $urlGenerator->getAbsoluteURL('/index.php/apps/registration/');
  193. }
  194. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  195. $this->assign('signUpLink', $signUpLink);
  196. } else {
  197. parent::__construct('core', 'layout.base');
  198. }
  199. // Send the language and the locale to our layouts
  200. $lang = \OC::$server->getL10NFactory()->findLanguage();
  201. $locale = \OC::$server->getL10NFactory()->findLocale($lang);
  202. $lang = str_replace('_', '-', $lang);
  203. $this->assign('language', $lang);
  204. $this->assign('locale', $locale);
  205. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  206. if (empty(self::$versionHash)) {
  207. $v = \OC_App::getAppVersions();
  208. $v['core'] = implode('.', \OCP\Util::getVersion());
  209. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  210. }
  211. } else {
  212. self::$versionHash = md5('not installed');
  213. }
  214. // Add the js files
  215. // TODO: remove deprecated OC_Util injection
  216. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  217. $this->assign('jsfiles', []);
  218. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  219. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  220. // see https://github.com/nextcloud/server/pull/22636 for details
  221. $jsConfigHelper = new JSConfigHelper(
  222. \OCP\Util::getL10N('lib'),
  223. \OCP\Server::get(Defaults::class),
  224. \OC::$server->getAppManager(),
  225. \OC::$server->getSession(),
  226. \OC::$server->getUserSession()->getUser(),
  227. $this->config,
  228. \OC::$server->getGroupManager(),
  229. \OC::$server->get(IniGetWrapper::class),
  230. \OC::$server->getURLGenerator(),
  231. \OC::$server->get(CapabilitiesManager::class),
  232. \OCP\Server::get(IInitialStateService::class),
  233. \OCP\Server::get(IProvider::class),
  234. );
  235. $config = $jsConfigHelper->getConfig();
  236. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  237. $this->assign('inline_ocjs', $config);
  238. } else {
  239. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  240. }
  241. }
  242. foreach ($jsFiles as $info) {
  243. $web = $info[1];
  244. $file = $info[2];
  245. $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  246. }
  247. try {
  248. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  249. } catch (\Exception $e) {
  250. $pathInfo = '';
  251. }
  252. // Do not initialise scss appdata until we have a fully installed instance
  253. // Do not load scss for update, errors, installation or login page
  254. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  255. && !\OCP\Util::needUpgrade()
  256. && $pathInfo !== ''
  257. && !preg_match('/^\/login/', $pathInfo)
  258. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  259. ) {
  260. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  261. } else {
  262. // If we ignore the scss compiler,
  263. // we need to load the guest css fallback
  264. \OC_Util::addStyle('guest');
  265. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  266. }
  267. $this->assign('cssfiles', []);
  268. $this->assign('printcssfiles', []);
  269. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  270. foreach ($cssFiles as $info) {
  271. $web = $info[1];
  272. $file = $info[2];
  273. if (str_ends_with($file, 'print.css')) {
  274. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  275. } else {
  276. $suffix = $this->getVersionHashSuffix($web, $file);
  277. if (!str_contains($file, '?v=')) {
  278. $this->append('cssfiles', $web.'/'.$file . $suffix);
  279. } else {
  280. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  281. }
  282. }
  283. }
  284. $this->assign('initialStates', $this->initialState->getInitialStates());
  285. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  286. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  287. }
  288. /**
  289. * @param string $path
  290. * @param string $file
  291. * @return string
  292. */
  293. protected function getVersionHashSuffix($path = false, $file = false) {
  294. if ($this->config->getSystemValueBool('debug', false)) {
  295. // allows chrome workspace mapping in debug mode
  296. return "";
  297. }
  298. $themingSuffix = '';
  299. $v = [];
  300. if ($this->config->getSystemValueBool('installed', false)) {
  301. if (\OC::$server->getAppManager()->isInstalled('theming')) {
  302. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  303. }
  304. $v = \OC_App::getAppVersions();
  305. }
  306. // Try the webroot path for a match
  307. if ($path !== false && $path !== '') {
  308. $appName = $this->getAppNamefromPath($path);
  309. if (array_key_exists($appName, $v)) {
  310. $appVersion = $v[$appName];
  311. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  312. }
  313. }
  314. // fallback to the file path instead
  315. if ($file !== false && $file !== '') {
  316. $appName = $this->getAppNamefromPath($file);
  317. if (array_key_exists($appName, $v)) {
  318. $appVersion = $v[$appName];
  319. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  320. }
  321. }
  322. return '?v=' . self::$versionHash . $themingSuffix;
  323. }
  324. /**
  325. * @param array $styles
  326. * @return array
  327. */
  328. public static function findStylesheetFiles($styles, $compileScss = true) {
  329. if (!self::$cssLocator) {
  330. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  331. }
  332. self::$cssLocator->find($styles);
  333. return self::$cssLocator->getResources();
  334. }
  335. /**
  336. * @param string $path
  337. * @return string|boolean
  338. */
  339. public function getAppNamefromPath($path) {
  340. if ($path !== '' && is_string($path)) {
  341. $pathParts = explode('/', $path);
  342. if ($pathParts[0] === 'css') {
  343. // This is a scss request
  344. return $pathParts[1];
  345. }
  346. return end($pathParts);
  347. }
  348. return false;
  349. }
  350. /**
  351. * @param array $scripts
  352. * @return array
  353. */
  354. public static function findJavascriptFiles($scripts) {
  355. if (!self::$jsLocator) {
  356. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  357. }
  358. self::$jsLocator->find($scripts);
  359. return self::$jsLocator->getResources();
  360. }
  361. /**
  362. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  363. * @param string $filePath Absolute path
  364. * @return string Relative path
  365. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  366. */
  367. public static function convertToRelativePath($filePath) {
  368. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  369. if (count($relativePath) !== 2) {
  370. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  371. }
  372. return $relativePath[1];
  373. }
  374. }