You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

382 lines
12 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Christopher Schäpers <kondou@ts.unde.re>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Clark Tomlinson <fallen013@gmail.com>
  10. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  11. * @author Guillaume COMPAGNON <gcompagnon@outlook.com>
  12. * @author Hendrik Leppelsack <hendrik@leppelsack.de>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  15. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Julius Haertl <jus@bitgrid.net>
  17. * @author Julius Härtl <jus@bitgrid.net>
  18. * @author Lukas Reschke <lukas@statuscode.ch>
  19. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  20. * @author Morris Jobke <hey@morrisjobke.de>
  21. * @author Nils <git@to.nilsschnabel.de>
  22. * @author Remco Brenninkmeijer <requist1@starmail.nl>
  23. * @author Robin Appelman <robin@icewind.nl>
  24. * @author Robin McCorkell <robin@mccorkell.me.uk>
  25. * @author Roeland Jago Douma <roeland@famdouma.nl>
  26. * @author Thomas Citharel <nextcloud@tcit.fr>
  27. * @author Thomas Müller <thomas.mueller@tmit.eu>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. namespace OC;
  45. use bantu\IniGetWrapper\IniGetWrapper;
  46. use OC\Search\SearchQuery;
  47. use OC\Template\JSCombiner;
  48. use OC\Template\JSConfigHelper;
  49. use OC\Template\SCSSCacher;
  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\Support\Subscription\IRegistry;
  56. use OCP\Util;
  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. if (Util::isIE()) {
  75. Util::addStyle('ie');
  76. }
  77. // Decide which page we show
  78. if ($renderAs === TemplateResponse::RENDER_AS_USER) {
  79. /** @var INavigationManager */
  80. $this->navigationManager = \OC::$server->get(INavigationManager::class);
  81. parent::__construct('core', 'layout.user');
  82. if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
  83. $this->assign('bodyid', 'body-settings');
  84. } else {
  85. $this->assign('bodyid', 'body-user');
  86. }
  87. $this->initialState->provideInitialState('core', 'active-app', $this->navigationManager->getActiveEntry());
  88. $this->initialState->provideInitialState('unified-search', 'limit-default', SearchQuery::LIMIT_DEFAULT);
  89. Util::addScript('dist/unified-search', null, true);
  90. // Add navigation entry
  91. $this->assign('application', '');
  92. $this->assign('appid', $appId);
  93. $navigation = $this->navigationManager->getAll();
  94. $this->assign('navigation', $navigation);
  95. $settingsNavigation = $this->navigationManager->getAll('settings');
  96. $this->assign('settingsnavigation', $settingsNavigation);
  97. foreach ($navigation as $entry) {
  98. if ($entry['active']) {
  99. $this->assign('application', $entry['name']);
  100. break;
  101. }
  102. }
  103. foreach ($settingsNavigation as $entry) {
  104. if ($entry['active']) {
  105. $this->assign('application', $entry['name']);
  106. break;
  107. }
  108. }
  109. $userDisplayName = \OC_User::getDisplayName();
  110. $this->assign('user_displayname', $userDisplayName);
  111. $this->assign('user_uid', \OC_User::getUser());
  112. if (\OC_User::getUser() === false) {
  113. $this->assign('userAvatarSet', false);
  114. } else {
  115. $this->assign('userAvatarSet', \OC::$server->getAvatarManager()->getAvatar(\OC_User::getUser())->exists());
  116. $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
  117. }
  118. // check if app menu icons should be inverted
  119. try {
  120. /** @var \OCA\Theming\Util $util */
  121. $util = \OC::$server->query(\OCA\Theming\Util::class);
  122. $this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
  123. } catch (\OCP\AppFramework\QueryException $e) {
  124. $this->assign('themingInvertMenu', false);
  125. } catch (\OCP\AutoloadNotAllowedException $e) {
  126. $this->assign('themingInvertMenu', false);
  127. }
  128. } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
  129. parent::__construct('core', 'layout.guest', '', false);
  130. $this->assign('bodyid', 'body-login');
  131. $this->assign('user_displayname', '');
  132. $this->assign('user_uid', '');
  133. } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
  134. parent::__construct('core', 'layout.guest');
  135. \OC_Util::addStyle('guest');
  136. $this->assign('bodyid', 'body-login');
  137. $userDisplayName = \OC_User::getDisplayName();
  138. $this->assign('user_displayname', $userDisplayName);
  139. $this->assign('user_uid', \OC_User::getUser());
  140. } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
  141. parent::__construct('core', 'layout.public');
  142. $this->assign('appid', $appId);
  143. $this->assign('bodyid', 'body-public');
  144. /** @var IRegistry $subscription */
  145. $subscription = \OC::$server->query(IRegistry::class);
  146. $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
  147. if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
  148. $showSimpleSignup = false;
  149. }
  150. $this->assign('showSimpleSignUpLink', $showSimpleSignup);
  151. } else {
  152. parent::__construct('core', 'layout.base');
  153. }
  154. // Send the language and the locale to our layouts
  155. $lang = \OC::$server->getL10NFactory()->findLanguage();
  156. $locale = \OC::$server->getL10NFactory()->findLocale($lang);
  157. $lang = str_replace('_', '-', $lang);
  158. $this->assign('language', $lang);
  159. $this->assign('locale', $locale);
  160. if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
  161. if (empty(self::$versionHash)) {
  162. $v = \OC_App::getAppVersions();
  163. $v['core'] = implode('.', \OCP\Util::getVersion());
  164. self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
  165. }
  166. } else {
  167. self::$versionHash = md5('not installed');
  168. }
  169. // Add the js files
  170. $jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
  171. $this->assign('jsfiles', []);
  172. if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
  173. $jsConfigHelper = new JSConfigHelper(
  174. \OC::$server->getL10N('lib'),
  175. \OC::$server->query(Defaults::class),
  176. \OC::$server->getAppManager(),
  177. \OC::$server->getSession(),
  178. \OC::$server->getUserSession()->getUser(),
  179. $this->config,
  180. \OC::$server->getGroupManager(),
  181. \OC::$server->get(IniGetWrapper::class),
  182. \OC::$server->getURLGenerator(),
  183. \OC::$server->getCapabilitiesManager(),
  184. \OC::$server->query(IInitialStateService::class)
  185. );
  186. $config = $jsConfigHelper->getConfig();
  187. if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
  188. $this->assign('inline_ocjs', $config);
  189. } else {
  190. $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
  191. }
  192. }
  193. foreach ($jsFiles as $info) {
  194. $web = $info[1];
  195. $file = $info[2];
  196. $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  197. }
  198. try {
  199. $pathInfo = \OC::$server->getRequest()->getPathInfo();
  200. } catch (\Exception $e) {
  201. $pathInfo = '';
  202. }
  203. // Do not initialise scss appdata until we have a fully installed instance
  204. // Do not load scss for update, errors, installation or login page
  205. if (\OC::$server->getSystemConfig()->getValue('installed', false)
  206. && !\OCP\Util::needUpgrade()
  207. && $pathInfo !== ''
  208. && !preg_match('/^\/login/', $pathInfo)
  209. && $renderAs !== TemplateResponse::RENDER_AS_ERROR
  210. ) {
  211. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
  212. } else {
  213. // If we ignore the scss compiler,
  214. // we need to load the guest css fallback
  215. \OC_Util::addStyle('guest');
  216. $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
  217. }
  218. $this->assign('cssfiles', []);
  219. $this->assign('printcssfiles', []);
  220. $this->assign('versionHash', self::$versionHash);
  221. foreach ($cssFiles as $info) {
  222. $web = $info[1];
  223. $file = $info[2];
  224. if (substr($file, -strlen('print.css')) === 'print.css') {
  225. $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
  226. } else {
  227. $suffix = $this->getVersionHashSuffix($web, $file);
  228. if (strpos($file, '?v=') == false) {
  229. $this->append('cssfiles', $web.'/'.$file . $suffix);
  230. } else {
  231. $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
  232. }
  233. }
  234. }
  235. $this->assign('initialStates', $this->initialState->getInitialStates());
  236. }
  237. /**
  238. * @param string $path
  239. * @param string $file
  240. * @return string
  241. */
  242. protected function getVersionHashSuffix($path = false, $file = false) {
  243. if ($this->config->getSystemValue('debug', false)) {
  244. // allows chrome workspace mapping in debug mode
  245. return "";
  246. }
  247. $themingSuffix = '';
  248. $v = [];
  249. if ($this->config->getSystemValue('installed', false)) {
  250. if (\OC::$server->getAppManager()->isInstalled('theming')) {
  251. $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
  252. }
  253. $v = \OC_App::getAppVersions();
  254. }
  255. // Try the webroot path for a match
  256. if ($path !== false && $path !== '') {
  257. $appName = $this->getAppNamefromPath($path);
  258. if (array_key_exists($appName, $v)) {
  259. $appVersion = $v[$appName];
  260. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  261. }
  262. }
  263. // fallback to the file path instead
  264. if ($file !== false && $file !== '') {
  265. $appName = $this->getAppNamefromPath($file);
  266. if (array_key_exists($appName, $v)) {
  267. $appVersion = $v[$appName];
  268. return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
  269. }
  270. }
  271. return '?v=' . self::$versionHash . $themingSuffix;
  272. }
  273. /**
  274. * @param array $styles
  275. * @return array
  276. */
  277. public static function findStylesheetFiles($styles, $compileScss = true) {
  278. // Read the selected theme from the config file
  279. $theme = \OC_Util::getTheme();
  280. if ($compileScss) {
  281. $SCSSCacher = \OC::$server->query(SCSSCacher::class);
  282. } else {
  283. $SCSSCacher = null;
  284. }
  285. $locator = new \OC\Template\CSSResourceLocator(
  286. \OC::$server->getLogger(),
  287. $theme,
  288. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  289. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  290. $SCSSCacher
  291. );
  292. $locator->find($styles);
  293. return $locator->getResources();
  294. }
  295. /**
  296. * @param string $path
  297. * @return string|boolean
  298. */
  299. public function getAppNamefromPath($path) {
  300. if ($path !== '' && is_string($path)) {
  301. $pathParts = explode('/', $path);
  302. if ($pathParts[0] === 'css') {
  303. // This is a scss request
  304. return $pathParts[1];
  305. }
  306. return end($pathParts);
  307. }
  308. return false;
  309. }
  310. /**
  311. * @param array $scripts
  312. * @return array
  313. */
  314. public static function findJavascriptFiles($scripts) {
  315. // Read the selected theme from the config file
  316. $theme = \OC_Util::getTheme();
  317. $locator = new \OC\Template\JSResourceLocator(
  318. \OC::$server->getLogger(),
  319. $theme,
  320. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  321. [ \OC::$SERVERROOT => \OC::$WEBROOT ],
  322. \OC::$server->query(JSCombiner::class)
  323. );
  324. $locator->find($scripts);
  325. return $locator->getResources();
  326. }
  327. /**
  328. * Converts the absolute file path to a relative path from \OC::$SERVERROOT
  329. * @param string $filePath Absolute path
  330. * @return string Relative path
  331. * @throws \Exception If $filePath is not under \OC::$SERVERROOT
  332. */
  333. public static function convertToRelativePath($filePath) {
  334. $relativePath = explode(\OC::$SERVERROOT, $filePath);
  335. if (count($relativePath) !== 2) {
  336. throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
  337. }
  338. return $relativePath[1];
  339. }
  340. }