TemplateLayout.php 15 KB

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