TemplateLayout.php 14 KB

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