TemplateLayout.php 12 KB

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