TemplateLayout.php 14 KB

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