SCSSCacher.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, John Molakvoæ (skjnldsv@protonmail.com)
  4. *
  5. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  6. * @author Julius Haertl <jus@bitgrid.net>
  7. * @author Julius Härtl <jus@bitgrid.net>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. *
  12. * @license GNU AGPL version 3 or any later version
  13. *
  14. * This program is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License as
  16. * published by the Free Software Foundation, either version 3 of the
  17. * License, or (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. *
  27. */
  28. namespace OC\Template;
  29. use Leafo\ScssPhp\Compiler;
  30. use Leafo\ScssPhp\Exception\ParserException;
  31. use Leafo\ScssPhp\Formatter\Crunched;
  32. use Leafo\ScssPhp\Formatter\Expanded;
  33. use OCP\AppFramework\Utility\ITimeFactory;
  34. use OCP\Files\IAppData;
  35. use OCP\Files\NotFoundException;
  36. use OCP\Files\NotPermittedException;
  37. use OCP\Files\SimpleFS\ISimpleFile;
  38. use OCP\Files\SimpleFS\ISimpleFolder;
  39. use OCP\ICache;
  40. use OCP\ICacheFactory;
  41. use OCP\IConfig;
  42. use OCP\ILogger;
  43. use OCP\IURLGenerator;
  44. use OC\Files\AppData\Factory;
  45. use OC\Template\IconsCacher;
  46. class SCSSCacher {
  47. /** @var ILogger */
  48. protected $logger;
  49. /** @var IAppData */
  50. protected $appData;
  51. /** @var IURLGenerator */
  52. protected $urlGenerator;
  53. /** @var IConfig */
  54. protected $config;
  55. /** @var \OC_Defaults */
  56. private $defaults;
  57. /** @var string */
  58. protected $serverRoot;
  59. /** @var ICache */
  60. protected $depsCache;
  61. /** @var null|string */
  62. private $injectedVariables;
  63. /** @var ICacheFactory */
  64. private $cacheFactory;
  65. /** @var IconsCacher */
  66. private $iconsCacher;
  67. /** @var ICache */
  68. private $isCachedCache;
  69. /** @var ITimeFactory */
  70. private $timeFactory;
  71. /**
  72. * @param ILogger $logger
  73. * @param Factory $appDataFactory
  74. * @param IURLGenerator $urlGenerator
  75. * @param IConfig $config
  76. * @param \OC_Defaults $defaults
  77. * @param string $serverRoot
  78. * @param ICacheFactory $cacheFactory
  79. * @param IconsCacher $iconsCacher
  80. * @param ITimeFactory $timeFactory
  81. */
  82. public function __construct(ILogger $logger,
  83. Factory $appDataFactory,
  84. IURLGenerator $urlGenerator,
  85. IConfig $config,
  86. \OC_Defaults $defaults,
  87. $serverRoot,
  88. ICacheFactory $cacheFactory,
  89. IconsCacher $iconsCacher,
  90. ITimeFactory $timeFactory) {
  91. $this->logger = $logger;
  92. $this->appData = $appDataFactory->get('css');
  93. $this->urlGenerator = $urlGenerator;
  94. $this->config = $config;
  95. $this->defaults = $defaults;
  96. $this->serverRoot = $serverRoot;
  97. $this->cacheFactory = $cacheFactory;
  98. $this->depsCache = $cacheFactory->createDistributed('SCSS-' . md5($this->urlGenerator->getBaseUrl()));
  99. $this->isCachedCache = $cacheFactory->createLocal('SCSS-cached-' . md5($this->urlGenerator->getBaseUrl()));
  100. $this->iconsCacher = $iconsCacher;
  101. $this->timeFactory = $timeFactory;
  102. }
  103. /**
  104. * Process the caching process if needed
  105. *
  106. * @param string $root Root path to the nextcloud installation
  107. * @param string $file
  108. * @param string $app The app name
  109. * @return boolean
  110. * @throws NotPermittedException
  111. */
  112. public function process(string $root, string $file, string $app): bool {
  113. $path = explode('/', $root . '/' . $file);
  114. $fileNameSCSS = array_pop($path);
  115. $fileNameCSS = $this->prependVersionPrefix($this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileNameSCSS)), $app);
  116. $path = implode('/', $path);
  117. $webDir = $this->getWebDir($path, $app, $this->serverRoot, \OC::$WEBROOT);
  118. if (!$this->variablesChanged() && $this->isCached($fileNameCSS, $app)) {
  119. // Inject icons vars css if any
  120. if ($this->iconsCacher->getCachedCSS() && $this->iconsCacher->getCachedCSS()->getSize() > 0) {
  121. $this->iconsCacher->injectCss();
  122. }
  123. return true;
  124. }
  125. try {
  126. $folder = $this->appData->getFolder($app);
  127. } catch (NotFoundException $e) {
  128. // creating css appdata folder
  129. $folder = $this->appData->newFolder($app);
  130. }
  131. $cached = $this->cache($path, $fileNameCSS, $fileNameSCSS, $folder, $webDir);
  132. // Inject icons vars css if any
  133. if ($this->iconsCacher->getCachedCSS() && $this->iconsCacher->getCachedCSS()->getSize() > 0) {
  134. $this->iconsCacher->injectCss();
  135. }
  136. return $cached;
  137. }
  138. /**
  139. * @param $appName
  140. * @param $fileName
  141. * @return ISimpleFile
  142. */
  143. public function getCachedCSS(string $appName, string $fileName): ISimpleFile {
  144. $folder = $this->appData->getFolder($appName);
  145. $cachedFileName = $this->prependVersionPrefix($this->prependBaseurlPrefix($fileName), $appName);
  146. return $folder->getFile($cachedFileName);
  147. }
  148. /**
  149. * Check if the file is cached or not
  150. * @param string $fileNameCSS
  151. * @param string $app
  152. * @return boolean
  153. */
  154. private function isCached(string $fileNameCSS, string $app) {
  155. $key = $this->config->getSystemValue('version') . '/' . $app . '/' . $fileNameCSS;
  156. if (!$this->config->getSystemValue('debug') && $cacheValue = $this->isCachedCache->get($key)) {
  157. if ($cacheValue > $this->timeFactory->getTime()) {
  158. return true;
  159. }
  160. }
  161. try {
  162. $folder = $this->appData->getFolder($app);
  163. } catch (NotFoundException $e) {
  164. // creating css appdata folder
  165. $folder = $this->appData->newFolder($app);
  166. }
  167. try {
  168. $cachedFile = $folder->getFile($fileNameCSS);
  169. if ($cachedFile->getSize() > 0) {
  170. $depFileName = $fileNameCSS . '.deps';
  171. $deps = $this->depsCache->get($folder->getName() . '-' . $depFileName);
  172. if ($deps === null) {
  173. $depFile = $folder->getFile($depFileName);
  174. $deps = $depFile->getContent();
  175. //Set to memcache for next run
  176. $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
  177. }
  178. $deps = json_decode($deps, true);
  179. foreach ((array) $deps as $file => $mtime) {
  180. if (!file_exists($file) || filemtime($file) > $mtime) {
  181. return false;
  182. }
  183. }
  184. $this->isCachedCache->set($key, $this->timeFactory->getTime() + 5 * 60);
  185. return true;
  186. }
  187. return false;
  188. } catch (NotFoundException $e) {
  189. return false;
  190. }
  191. }
  192. /**
  193. * Check if the variables file has changed
  194. * @return bool
  195. */
  196. private function variablesChanged(): bool {
  197. $injectedVariables = $this->getInjectedVariables();
  198. if ($this->config->getAppValue('core', 'scss.variables') !== md5($injectedVariables)) {
  199. $this->resetCache();
  200. $this->config->setAppValue('core', 'scss.variables', md5($injectedVariables));
  201. return true;
  202. }
  203. return false;
  204. }
  205. /**
  206. * Cache the file with AppData
  207. *
  208. * @param string $path
  209. * @param string $fileNameCSS
  210. * @param string $fileNameSCSS
  211. * @param ISimpleFolder $folder
  212. * @param string $webDir
  213. * @return boolean
  214. * @throws NotPermittedException
  215. */
  216. private function cache(string $path, string $fileNameCSS, string $fileNameSCSS, ISimpleFolder $folder, string $webDir) {
  217. $scss = new Compiler();
  218. $scss->setImportPaths([
  219. $path,
  220. $this->serverRoot . '/core/css/'
  221. ]);
  222. // Continue after throw
  223. $scss->setIgnoreErrors(true);
  224. if ($this->config->getSystemValue('debug')) {
  225. // Debug mode
  226. $scss->setFormatter(Expanded::class);
  227. $scss->setLineNumberStyle(Compiler::LINE_COMMENTS);
  228. } else {
  229. // Compression
  230. $scss->setFormatter(Crunched::class);
  231. }
  232. try {
  233. $cachedfile = $folder->getFile($fileNameCSS);
  234. } catch (NotFoundException $e) {
  235. $cachedfile = $folder->newFile($fileNameCSS);
  236. }
  237. $depFileName = $fileNameCSS . '.deps';
  238. try {
  239. $depFile = $folder->getFile($depFileName);
  240. } catch (NotFoundException $e) {
  241. $depFile = $folder->newFile($depFileName);
  242. }
  243. // Compile
  244. try {
  245. $compiledScss = $scss->compile(
  246. '$webroot: \'' . $this->getRoutePrefix() . '\';' .
  247. $this->getInjectedVariables() .
  248. '@import "variables.scss";' .
  249. '@import "functions.scss";' .
  250. '@import "' . $fileNameSCSS . '";');
  251. } catch (ParserException $e) {
  252. $this->logger->error($e, ['app' => 'core']);
  253. return false;
  254. }
  255. // Parse Icons and create related css variables
  256. $compiledScss = $this->iconsCacher->setIconsCss($compiledScss);
  257. // Gzip file
  258. try {
  259. $gzipFile = $folder->getFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
  260. } catch (NotFoundException $e) {
  261. $gzipFile = $folder->newFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
  262. }
  263. try {
  264. $data = $this->rebaseUrls($compiledScss, $webDir);
  265. $cachedfile->putContent($data);
  266. $deps = json_encode($scss->getParsedFiles());
  267. $depFile->putContent($deps);
  268. $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
  269. $gzipFile->putContent(gzencode($data, 9));
  270. $this->logger->debug('SCSSCacher: ' . $webDir . '/' . $fileNameSCSS . ' compiled and successfully cached', ['app' => 'core']);
  271. return true;
  272. } catch (NotPermittedException $e) {
  273. $this->logger->error('SCSSCacher: unable to cache: ' . $fileNameSCSS);
  274. return false;
  275. }
  276. }
  277. /**
  278. * Reset scss cache by deleting all generated css files
  279. * We need to regenerate all files when variables change
  280. */
  281. public function resetCache() {
  282. $this->injectedVariables = null;
  283. $this->cacheFactory->createDistributed('SCSS-')->clear();
  284. $appDirectory = $this->appData->getDirectoryListing();
  285. foreach ($appDirectory as $folder) {
  286. foreach ($folder->getDirectoryListing() as $file) {
  287. try {
  288. $file->delete();
  289. } catch (NotPermittedException $e) {
  290. $this->logger->logException($e, ['message' => 'SCSSCacher: unable to delete file: ' . $file->getName()]);
  291. }
  292. }
  293. }
  294. }
  295. /**
  296. * @return string SCSS code for variables from OC_Defaults
  297. */
  298. private function getInjectedVariables(): string {
  299. if ($this->injectedVariables !== null) {
  300. return $this->injectedVariables;
  301. }
  302. $variables = '';
  303. foreach ($this->defaults->getScssVariables() as $key => $value) {
  304. $variables .= '$' . $key . ': ' . $value . ' !default;';
  305. }
  306. // check for valid variables / otherwise fall back to defaults
  307. try {
  308. $scss = new Compiler();
  309. $scss->compile($variables);
  310. $this->injectedVariables = $variables;
  311. } catch (ParserException $e) {
  312. $this->logger->error($e, ['app' => 'core']);
  313. }
  314. return $variables;
  315. }
  316. /**
  317. * Add the correct uri prefix to make uri valid again
  318. * @param string $css
  319. * @param string $webDir
  320. * @return string
  321. */
  322. private function rebaseUrls(string $css, string $webDir): string {
  323. $re = '/url\([\'"]([^\/][\.\w?=\/-]*)[\'"]\)/x';
  324. $subst = 'url(\'' . $webDir . '/$1\')';
  325. return preg_replace($re, $subst, $css);
  326. }
  327. /**
  328. * Return the cached css file uri
  329. * @param string $appName the app name
  330. * @param string $fileName
  331. * @return string
  332. */
  333. public function getCachedSCSS(string $appName, string $fileName): string {
  334. $tmpfileLoc = explode('/', $fileName);
  335. $fileName = array_pop($tmpfileLoc);
  336. $fileName = $this->prependVersionPrefix($this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileName)), $appName);
  337. return substr($this->urlGenerator->linkToRoute('core.Css.getCss', [
  338. 'fileName' => $fileName,
  339. 'appName' => $appName,
  340. 'v' => $this->config->getAppValue('core', 'scss.variables', '0')
  341. ]), \strlen(\OC::$WEBROOT) + 1);
  342. }
  343. /**
  344. * Prepend hashed base url to the css file
  345. * @param string $cssFile
  346. * @return string
  347. */
  348. private function prependBaseurlPrefix(string $cssFile): string {
  349. return substr(md5($this->urlGenerator->getBaseUrl() . $this->getRoutePrefix()), 0, 4) . '-' . $cssFile;
  350. }
  351. private function getRoutePrefix() {
  352. $frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
  353. $prefix = \OC::$WEBROOT . '/index.php';
  354. if ($frontControllerActive) {
  355. $prefix = \OC::$WEBROOT;
  356. }
  357. return $prefix;
  358. }
  359. /**
  360. * Prepend hashed app version hash
  361. * @param string $cssFile
  362. * @param string $appId
  363. * @return string
  364. */
  365. private function prependVersionPrefix(string $cssFile, string $appId): string {
  366. $appVersion = \OC_App::getAppVersion($appId);
  367. if ($appVersion !== '0') {
  368. return substr(md5($appVersion), 0, 4) . '-' . $cssFile;
  369. }
  370. $coreVersion = \OC_Util::getVersionString();
  371. return substr(md5($coreVersion), 0, 4) . '-' . $cssFile;
  372. }
  373. /**
  374. * Get WebDir root
  375. * @param string $path the css file path
  376. * @param string $appName the app name
  377. * @param string $serverRoot the server root path
  378. * @param string $webRoot the nextcloud installation root path
  379. * @return string the webDir
  380. */
  381. private function getWebDir(string $path, string $appName, string $serverRoot, string $webRoot): string {
  382. // Detect if path is within server root AND if path is within an app path
  383. if (strpos($path, $serverRoot) === false && $appWebPath = \OC_App::getAppWebPath($appName)) {
  384. // Get the file path within the app directory
  385. $appDirectoryPath = explode($appName, $path)[1];
  386. // Remove the webroot
  387. return str_replace($webRoot, '', $appWebPath . $appDirectoryPath);
  388. }
  389. return $webRoot . substr($path, strlen($serverRoot));
  390. }
  391. }