TemplateLayout.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. // Set logo link target
  169. $logoUrl = $this->config->getSystemValueString('logo_url', '');
  170. $this->assign('logoUrl', $logoUrl);
  171. /** @var IRegistry $subscription */
  172. $subscription = \OCP\Server::get(IRegistry::class);
  173. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  174. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  175. $showSimpleSignup = false;
  176. }
  177. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  178. } else {
  179. parent::__construct('core', 'layout.base');
  180. }
  181. // Send the language and the locale to our layouts
  182. $lang = \OC::$server->getL10NFactory()->findLanguage();
  183. $locale = \OC::$server->getL10NFactory()->findLocale($lang);
  184. $lang = str_replace('_', '-', $lang);
  185. $this->assign('language', $lang);
  186. $this->assign('locale', $locale);
  187. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  188. if (empty(self::$versionHash)) {
  189. $v = \OC_App::getAppVersions();
  190. $v['core'] = implode('.', \OCP\Util::getVersion());
  191. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  192. }
  193. } else {
  194. self::$versionHash = md5('not installed');
  195. }
  196. // Add the js files
  197. // TODO: remove deprecated OC_Util injection
  198. $jsFiles = self::findJavascriptFiles(array_merge(\OC_Util::$scripts, Util::getScripts()));
  199. $this->assign('jsfiles', []);
  200. if ($this->config->getSystemValueBool('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  201. // this is on purpose outside of the if statement below so that the initial state is prefilled (done in the getConfig() call)
  202. // see https://github.com/nextcloud/server/pull/22636 for details
  203. $jsConfigHelper = new JSConfigHelper(
  204. \OC::$server->getL10N('lib'),
  205. \OCP\Server::get(Defaults::class),
  206. \OC::$server->getAppManager(),
  207. \OC::$server->getSession(),
  208. \OC::$server->getUserSession()->getUser(),
  209. $this->config,
  210. \OC::$server->getGroupManager(),
  211. \OC::$server->get(IniGetWrapper::class),
  212. \OC::$server->getURLGenerator(),
  213. \OC::$server->getCapabilitiesManager(),
  214. \OCP\Server::get(IInitialStateService::class)
  215. );
  216. $config = $jsConfigHelper->getConfig();
  217. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  218. $this->assign('inline_ocjs', $config);
  219. } else {
  220. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  221. }
  222. }
  223. foreach ($jsFiles as $info) {
  224. $web = $info[1];
  225. $file = $info[2];
  226. $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  227. }
  228. try {
  229. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  230. } catch (\Exception $e) {
  231. $pathInfo = '';
  232. }
  233. // Do not initialise scss appdata until we have a fully installed instance
  234. // Do not load scss for update, errors, installation or login page
  235. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  236. && !\OCP\Util::needUpgrade()
  237. && $pathInfo !== ''
  238. && !preg_match('/^\/login/', $pathInfo)
  239. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  240. ) {
  241. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  242. } else {
  243. // If we ignore the scss compiler,
  244. // we need to load the guest css fallback
  245. \OC_Util::addStyle('guest');
  246. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  247. }
  248. $this->assign('cssfiles', []);
  249. $this->assign('printcssfiles', []);
  250. $this->initialState->provideInitialState('core', 'versionHash', self::$versionHash);
  251. foreach ($cssFiles as $info) {
  252. $web = $info[1];
  253. $file = $info[2];
  254. if (str_ends_with($file, 'print.css')) {
  255. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  256. } else {
  257. $suffix = $this->getVersionHashSuffix($web, $file);
  258. if (!str_contains($file, '?v=')) {
  259. $this->append('cssfiles', $web.'/'.$file . $suffix);
  260. } else {
  261. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  262. }
  263. }
  264. }
  265. $this->assign('initialStates', $this->initialState->getInitialStates());
  266. $this->assign('id-app-content', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-content' : '#content');
  267. $this->assign('id-app-navigation', $renderAs === TemplateResponse::RENDER_AS_USER ? '#app-navigation' : null);
  268. }
  269. /**
  270. * @param string $path
  271. * @param string $file
  272. * @return string
  273. */
  274. protected function getVersionHashSuffix($path = false, $file = false) {
  275. if ($this->config->getSystemValueBool('debug', false)) {
  276. // allows chrome workspace mapping in debug mode
  277. return "";
  278. }
  279. $themingSuffix = '';
  280. $v = [];
  281. if ($this->config->getSystemValueBool('installed', false)) {
  282. if (\OC::$server->getAppManager()->isInstalled('theming')) {
  283. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  284. }
  285. $v = \OC_App::getAppVersions();
  286. }
  287. // Try the webroot path for a match
  288. if ($path !== false && $path !== '') {
  289. $appName = $this->getAppNamefromPath($path);
  290. if (array_key_exists($appName, $v)) {
  291. $appVersion = $v[$appName];
  292. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  293. }
  294. }
  295. // fallback to the file path instead
  296. if ($file !== false && $file !== '') {
  297. $appName = $this->getAppNamefromPath($file);
  298. if (array_key_exists($appName, $v)) {
  299. $appVersion = $v[$appName];
  300. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  301. }
  302. }
  303. return '?v=' . self::$versionHash . $themingSuffix;
  304. }
  305. /**
  306. * @param array $styles
  307. * @return array
  308. */
  309. public static function findStylesheetFiles($styles, $compileScss = true) {
  310. if (!self::$cssLocator) {
  311. self::$cssLocator = \OCP\Server::get(CSSResourceLocator::class);
  312. }
  313. self::$cssLocator->find($styles);
  314. return self::$cssLocator->getResources();
  315. }
  316. /**
  317. * @param string $path
  318. * @return string|boolean
  319. */
  320. public function getAppNamefromPath($path) {
  321. if ($path !== '' && is_string($path)) {
  322. $pathParts = explode('/', $path);
  323. if ($pathParts[0] === 'css') {
  324. // This is a scss request
  325. return $pathParts[1];
  326. }
  327. return end($pathParts);
  328. }
  329. return false;
  330. }
  331. /**
  332. * @param array $scripts
  333. * @return array
  334. */
  335. public static function findJavascriptFiles($scripts) {
  336. if (!self::$jsLocator) {
  337. self::$jsLocator = \OCP\Server::get(JSResourceLocator::class);
  338. }
  339. self::$jsLocator->find($scripts);
  340. return self::$jsLocator->getResources();
  341. }
  342. /**
  343. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  344. * @param string $filePath Absolute path
  345. * @return string Relative path
  346. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  347. */
  348. public static function convertToRelativePath($filePath) {
  349. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  350. if (count($relativePath) !== 2) {
  351. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  352. }
  353. return $relativePath[1];
  354. }
  355. }