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.

TemplateLayout.php 13KB

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