TemplateLayout.php 15 KB

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