TemplateLayout.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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\AppFramework\Http\TemplateResponse;
  50. use OCP\Defaults;
  51. use OCP\IConfig;
  52. use OCP\IInitialStateService;
  53. use OCP\INavigationManager;
  54. use OCP\IUserSession;
  55. use OCP\Support\Subscription\IRegistry;
  56. use OCP\Util;
  57. class TemplateLayout extends \OC_Template {
  58. private static $versionHash = '';
  59. /** @var CSSResourceLocator|null */
  60. public static $cssLocator = null;
  61. /** @var JSResourceLocator|null */
  62. public static $jsLocator = null;
  63. /** @var IConfig */
  64. private $config;
  65. /** @var IInitialStateService */
  66. private $initialState;
  67. /** @var INavigationManager */
  68. private $navigationManager;
  69. /**
  70. * @param string $renderAs
  71. * @param string $appId application id
  72. */
  73. public function __construct($renderAs, $appId = '') {
  74. /** @var IConfig */
  75. $this->config = \OC::$server->get(IConfig::class);
  76. /** @var IInitialStateService */
  77. $this->initialState = \OC::$server->get(IInitialStateService::class);
  78. // Add fallback theming variables if theming is disabled
  79. if ($renderAs !== TemplateResponse::RENDER_AS_USER
  80. || !\OC::$server->getAppManager()->isEnabledForUser('theming')) {
  81. // TODO cache generated default theme if enabled for fallback if server is erroring ?
  82. Util::addStyle('theming', 'default');
  83. }
  84. // Decide which page we show
  85. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  86. /** @var INavigationManager */
  87. $this->navigationManager = \OC::$server->get(INavigationManager::class);
  88. parent::__construct('core', 'layout.user');
  89. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  90. $this->assign('bodyid', 'body-settings');
  91. } else {
  92. $this->assign('bodyid', 'body-user');
  93. }
  94. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  95. $this->initialState->provideInitialState('core', 'apps', $this->navigationManager->getAll());
  96. $this->initialState->provideInitialState('unified-search', 'limit-default', (int)$this->config->getAppValue('core', 'unified-search.limit-default', (string)SearchQuery::LIMIT_DEFAULT));
  97. $this->initialState->provideInitialState('unified-search', 'min-search-length', (int)$this->config->getAppValue('core', 'unified-search.min-search-length', (string)1));
  98. $this->initialState->provideInitialState('unified-search', 'live-search', $this->config->getAppValue('core', 'unified-search.live-search', 'yes') === 'yes');
  99. Util::addScript('core', 'unified-search', 'core');
  100. // Set body data-theme
  101. $this->assign('enabledThemes', []);
  102. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && class_exists('\OCA\Theming\Service\ThemesService')) {
  103. /** @var \OCA\Theming\Service\ThemesService */
  104. $themesService = \OC::$server->get(\OCA\Theming\Service\ThemesService::class);
  105. $this->assign('enabledThemes', $themesService->getEnabledThemes());
  106. }
  107. // Set logo link target
  108. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  109. $this->assign('logoUrl', $logoUrl);
  110. // Set default app name
  111. $defaultApp = \OC::$server->getAppManager()->getDefaultAppForUser();
  112. $defaultAppInfo = \OC::$server->getAppManager()->getAppInfo($defaultApp);
  113. $l10n = \OC::$server->getL10NFactory()->get($defaultApp);
  114. $this->assign('defaultAppName', $l10n->t($defaultAppInfo['name']));
  115. // Add navigation entry
  116. $this->assign('application', '');
  117. $this->assign('appid', $appId);
  118. $navigation = $this->navigationManager->getAll();
  119. $this->assign('navigation', $navigation);
  120. $settingsNavigation = $this->navigationManager->getAll('settings');
  121. $this->initialState->provideInitialState('core', 'settingsNavEntries', $settingsNavigation);
  122. foreach ($navigation as $entry) {
  123. if ($entry['active']) {
  124. $this->assign('application', $entry['name']);
  125. break;
  126. }
  127. }
  128. foreach ($settingsNavigation as $entry) {
  129. if ($entry['active']) {
  130. $this->assign('application', $entry['name']);
  131. break;
  132. }
  133. }
  134. $userDisplayName = false;
  135. $user = \OC::$server->get(IUserSession::class)->getUser();
  136. if ($user) {
  137. $userDisplayName = $user->getDisplayName();
  138. }
  139. $this->assign('user_displayname', $userDisplayName);
  140. $this->assign('user_uid', \OC_User::getUser());
  141. if ($user === null) {
  142. $this->assign('userAvatarSet', false);
  143. $this->assign('userStatus', false);
  144. } else {
  145. $this->assign('userAvatarSet', true);
  146. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  147. }
  148. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  149. parent::__construct('core', 'layout.guest', '', false);
  150. $this->assign('bodyid', 'body-login');
  151. $this->assign('user_displayname', '');
  152. $this->assign('user_uid', '');
  153. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  154. parent::__construct('core', 'layout.guest');
  155. \OC_Util::addStyle('guest');
  156. $this->assign('bodyid', 'body-login');
  157. $userDisplayName = false;
  158. $user = \OC::$server->get(IUserSession::class)->getUser();
  159. if ($user) {
  160. $userDisplayName = $user->getDisplayName();
  161. }
  162. $this->assign('user_displayname', $userDisplayName);
  163. $this->assign('user_uid', \OC_User::getUser());
  164. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  165. parent::__construct('core', 'layout.public');
  166. $this->assign('appid', $appId);
  167. $this->assign('bodyid', 'body-public');
  168. /** @var IRegistry $subscription */
  169. $subscription = \OC::$server->query(IRegistry::class);
  170. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  171. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  172. $showSimpleSignup = false;
  173. }
  174. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  175. } else {
  176. parent::__construct('core', 'layout.base');
  177. }
  178. // Send the language and the locale to our layouts
  179. $lang = \OC::$server->getL10NFactory()->findLanguage();
  180. $locale = \OC::$server->getL10NFactory()->findLocale($lang);
  181. $lang = str_replace('_', '-', $lang);
  182. $this->assign('language', $lang);
  183. $this->assign('locale', $locale);
  184. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  185. if (empty(self::$versionHash)) {
  186. $v = \OC_App::getAppVersions();
  187. $v['core'] = implode('.', \OCP\Util::getVersion());
  188. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  189. }
  190. } else {
  191. self::$versionHash = md5('not installed');
  192. }
  193. // Add the js files
  194. // TODO: remove deprecated OC_Util injection
  195. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  196. $this->assign('jsfiles', []);
  197. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  198. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  199. // see https://github.com/nextcloud/server/pull/22636 for details
  200. $jsConfigHelper = new JSConfigHelper(
  201. \OC::$server->getL10N('lib'),
  202. \OC::$server->query(Defaults::class),
  203. \OC::$server->getAppManager(),
  204. \OC::$server->getSession(),
  205. \OC::$server->getUserSession()->getUser(),
  206. $this->config,
  207. \OC::$server->getGroupManager(),
  208. \OC::$server->get(IniGetWrapper::class),
  209. \OC::$server->getURLGenerator(),
  210. \OC::$server->getCapabilitiesManager(),
  211. \OC::$server->query(IInitialStateService::class)
  212. );
  213. $config = $jsConfigHelper->getConfig();
  214. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  215. $this->assign('inline_ocjs', $config);
  216. } else {
  217. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  218. }
  219. }
  220. foreach ($jsFiles as $info) {
  221. $web = $info[1];
  222. $file = $info[2];
  223. $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  224. }
  225. try {
  226. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  227. } catch (\Exception $e) {
  228. $pathInfo = '';
  229. }
  230. // Do not initialise scss appdata until we have a fully installed instance
  231. // Do not load scss for update, errors, installation or login page
  232. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  233. && !\OCP\Util::needUpgrade()
  234. && $pathInfo !== ''
  235. && !preg_match('/^\/login/', $pathInfo)
  236. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  237. ) {
  238. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  239. } else {
  240. // If we ignore the scss compiler,
  241. // we need to load the guest css fallback
  242. \OC_Util::addStyle('guest');
  243. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  244. }
  245. $this->assign('cssfiles', []);
  246. $this->assign('printcssfiles', []);
  247. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  248. foreach ($cssFiles as $info) {
  249. $web = $info[1];
  250. $file = $info[2];
  251. if (substr($file, -strlen('print.css')) === 'print.css') {
  252. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  253. } else {
  254. $suffix = $this->getVersionHashSuffix($web, $file);
  255. if (!str_contains($file, '?v=')) {
  256. $this->append('cssfiles', $web.'/'.$file . $suffix);
  257. } else {
  258. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  259. }
  260. }
  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. }