SCSSCacher.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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\Files\IAppData;
  34. use OCP\Files\NotFoundException;
  35. use OCP\Files\NotPermittedException;
  36. use OCP\Files\SimpleFS\ISimpleFile;
  37. use OCP\Files\SimpleFS\ISimpleFolder;
  38. use OCP\ICache;
  39. use OCP\ICacheFactory;
  40. use OCP\IConfig;
  41. use OCP\ILogger;
  42. use OCP\IURLGenerator;
  43. use OC\Files\AppData\Factory;
  44. use OC\Template\IconsCacher;
  45. class SCSSCacher {
  46. /** @var ILogger */
  47. protected $logger;
  48. /** @var IAppData */
  49. protected $appData;
  50. /** @var IURLGenerator */
  51. protected $urlGenerator;
  52. /** @var IConfig */
  53. protected $config;
  54. /** @var \OC_Defaults */
  55. private $defaults;
  56. /** @var string */
  57. protected $serverRoot;
  58. /** @var ICache */
  59. protected $depsCache;
  60. /** @var null|string */
  61. private $injectedVariables;
  62. /** @var ICacheFactory */
  63. private $cacheFactory;
  64. /** @var IconsCacher */
  65. private $iconsCacher;
  66. /**
  67. * @param ILogger $logger
  68. * @param Factory $appDataFactory
  69. * @param IURLGenerator $urlGenerator
  70. * @param IConfig $config
  71. * @param \OC_Defaults $defaults
  72. * @param string $serverRoot
  73. * @param ICacheFactory $cacheFactory
  74. * @param IconsCacher $iconsCacher
  75. */
  76. public function __construct(ILogger $logger,
  77. Factory $appDataFactory,
  78. IURLGenerator $urlGenerator,
  79. IConfig $config,
  80. \OC_Defaults $defaults,
  81. $serverRoot,
  82. ICacheFactory $cacheFactory,
  83. IconsCacher $iconsCacher) {
  84. $this->logger = $logger;
  85. $this->appData = $appDataFactory->get('css');
  86. $this->urlGenerator = $urlGenerator;
  87. $this->config = $config;
  88. $this->defaults = $defaults;
  89. $this->serverRoot = $serverRoot;
  90. $this->cacheFactory = $cacheFactory;
  91. $this->depsCache = $cacheFactory->createDistributed('SCSS-' . md5($this->urlGenerator->getBaseUrl()));
  92. $this->iconsCacher = $iconsCacher;
  93. }
  94. /**
  95. * Process the caching process if needed
  96. *
  97. * @param string $root Root path to the nextcloud installation
  98. * @param string $file
  99. * @param string $app The app name
  100. * @return boolean
  101. * @throws NotPermittedException
  102. */
  103. public function process(string $root, string $file, string $app): bool {
  104. $path = explode('/', $root . '/' . $file);
  105. $fileNameSCSS = array_pop($path);
  106. $fileNameCSS = $this->prependVersionPrefix($this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileNameSCSS)), $app);
  107. $path = implode('/', $path);
  108. $webDir = $this->getWebDir($path, $app, $this->serverRoot, \OC::$WEBROOT);
  109. try {
  110. $folder = $this->appData->getFolder($app);
  111. } catch (NotFoundException $e) {
  112. // creating css appdata folder
  113. $folder = $this->appData->newFolder($app);
  114. }
  115. if (!$this->variablesChanged() && $this->isCached($fileNameCSS, $folder)) {
  116. // Inject icons vars css if any
  117. if ($this->iconsCacher->getCachedCSS() && $this->iconsCacher->getCachedCSS()->getSize() > 0) {
  118. $this->iconsCacher->injectCss();
  119. }
  120. return true;
  121. }
  122. $cached = $this->cache($path, $fileNameCSS, $fileNameSCSS, $folder, $webDir);
  123. // Inject icons vars css if any
  124. if ($this->iconsCacher->getCachedCSS() && $this->iconsCacher->getCachedCSS()->getSize() > 0) {
  125. $this->iconsCacher->injectCss();
  126. }
  127. return $cached;
  128. }
  129. /**
  130. * @param $appName
  131. * @param $fileName
  132. * @return ISimpleFile
  133. */
  134. public function getCachedCSS(string $appName, string $fileName): ISimpleFile {
  135. $folder = $this->appData->getFolder($appName);
  136. $cachedFileName = $this->prependVersionPrefix($this->prependBaseurlPrefix($fileName), $appName);
  137. return $folder->getFile($cachedFileName);
  138. }
  139. /**
  140. * Check if the file is cached or not
  141. * @param string $fileNameCSS
  142. * @param ISimpleFolder $folder
  143. * @return boolean
  144. */
  145. private function isCached(string $fileNameCSS, ISimpleFolder $folder) {
  146. try {
  147. $cachedFile = $folder->getFile($fileNameCSS);
  148. if ($cachedFile->getSize() > 0) {
  149. $depFileName = $fileNameCSS . '.deps';
  150. $deps = $this->depsCache->get($folder->getName() . '-' . $depFileName);
  151. if ($deps === null) {
  152. $depFile = $folder->getFile($depFileName);
  153. $deps = $depFile->getContent();
  154. //Set to memcache for next run
  155. $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
  156. }
  157. $deps = json_decode($deps, true);
  158. foreach ((array) $deps as $file => $mtime) {
  159. if (!file_exists($file) || filemtime($file) > $mtime) {
  160. return false;
  161. }
  162. }
  163. return true;
  164. }
  165. return false;
  166. } catch (NotFoundException $e) {
  167. return false;
  168. }
  169. }
  170. /**
  171. * Check if the variables file has changed
  172. * @return bool
  173. */
  174. private function variablesChanged(): bool {
  175. $injectedVariables = $this->getInjectedVariables();
  176. if ($this->config->getAppValue('core', 'scss.variables') !== md5($injectedVariables)) {
  177. $this->resetCache();
  178. $this->config->setAppValue('core', 'scss.variables', md5($injectedVariables));
  179. return true;
  180. }
  181. return false;
  182. }
  183. /**
  184. * Cache the file with AppData
  185. *
  186. * @param string $path
  187. * @param string $fileNameCSS
  188. * @param string $fileNameSCSS
  189. * @param ISimpleFolder $folder
  190. * @param string $webDir
  191. * @return boolean
  192. * @throws NotPermittedException
  193. */
  194. private function cache(string $path, string $fileNameCSS, string $fileNameSCSS, ISimpleFolder $folder, string $webDir) {
  195. $scss = new Compiler();
  196. $scss->setImportPaths([
  197. $path,
  198. $this->serverRoot . '/core/css/'
  199. ]);
  200. // Continue after throw
  201. $scss->setIgnoreErrors(true);
  202. if ($this->config->getSystemValue('debug')) {
  203. // Debug mode
  204. $scss->setFormatter(Expanded::class);
  205. $scss->setLineNumberStyle(Compiler::LINE_COMMENTS);
  206. } else {
  207. // Compression
  208. $scss->setFormatter(Crunched::class);
  209. }
  210. try {
  211. $cachedfile = $folder->getFile($fileNameCSS);
  212. } catch (NotFoundException $e) {
  213. $cachedfile = $folder->newFile($fileNameCSS);
  214. }
  215. $depFileName = $fileNameCSS . '.deps';
  216. try {
  217. $depFile = $folder->getFile($depFileName);
  218. } catch (NotFoundException $e) {
  219. $depFile = $folder->newFile($depFileName);
  220. }
  221. // Compile
  222. try {
  223. $compiledScss = $scss->compile(
  224. '$webroot: \'' . \OC::$WEBROOT . '\';' .
  225. '@import "variables.scss";' .
  226. '@import "functions.scss";' .
  227. $this->getInjectedVariables() .
  228. '@import "' . $fileNameSCSS . '";');
  229. } catch (ParserException $e) {
  230. $this->logger->error($e, ['app' => 'core']);
  231. return false;
  232. }
  233. // Parse Icons and create related css variables
  234. $compiledScss = $this->iconsCacher->setIconsCss($compiledScss);
  235. // Gzip file
  236. try {
  237. $gzipFile = $folder->getFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
  238. } catch (NotFoundException $e) {
  239. $gzipFile = $folder->newFile($fileNameCSS . '.gzip'); # Safari doesn't like .gz
  240. }
  241. try {
  242. $data = $this->rebaseUrls($compiledScss, $webDir);
  243. $cachedfile->putContent($data);
  244. $deps = json_encode($scss->getParsedFiles());
  245. $depFile->putContent($deps);
  246. $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
  247. $gzipFile->putContent(gzencode($data, 9));
  248. $this->logger->debug('SCSSCacher: ' . $webDir . '/' . $fileNameSCSS . ' compiled and successfully cached', ['app' => 'core']);
  249. return true;
  250. } catch (NotPermittedException $e) {
  251. $this->logger->error('SCSSCacher: unable to cache: ' . $fileNameSCSS);
  252. return false;
  253. }
  254. }
  255. /**
  256. * Reset scss cache by deleting all generated css files
  257. * We need to regenerate all files when variables change
  258. */
  259. public function resetCache() {
  260. $this->injectedVariables = null;
  261. $this->cacheFactory->createDistributed('SCSS-')->clear();
  262. $appDirectory = $this->appData->getDirectoryListing();
  263. foreach ($appDirectory as $folder) {
  264. foreach ($folder->getDirectoryListing() as $file) {
  265. try {
  266. $file->delete();
  267. } catch (NotPermittedException $e) {
  268. $this->logger->logException($e, ['message' => 'SCSSCacher: unable to delete file: ' . $file->getName()]);
  269. }
  270. }
  271. }
  272. }
  273. /**
  274. * @return string SCSS code for variables from OC_Defaults
  275. */
  276. private function getInjectedVariables(): string {
  277. if ($this->injectedVariables !== null) {
  278. return $this->injectedVariables;
  279. }
  280. $variables = '';
  281. foreach ($this->defaults->getScssVariables() as $key => $value) {
  282. $variables .= '$' . $key . ': ' . $value . ';';
  283. }
  284. // check for valid variables / otherwise fall back to defaults
  285. try {
  286. $scss = new Compiler();
  287. $scss->compile($variables);
  288. $this->injectedVariables = $variables;
  289. } catch (ParserException $e) {
  290. $this->logger->error($e, ['app' => 'core']);
  291. }
  292. return $variables;
  293. }
  294. /**
  295. * Add the correct uri prefix to make uri valid again
  296. * @param string $css
  297. * @param string $webDir
  298. * @return string
  299. */
  300. private function rebaseUrls(string $css, string $webDir): string {
  301. $re = '/url\([\'"]([^\/][\.\w?=\/-]*)[\'"]\)/x';
  302. $subst = 'url(\'' . $webDir . '/$1\')';
  303. return preg_replace($re, $subst, $css);
  304. }
  305. /**
  306. * Return the cached css file uri
  307. * @param string $appName the app name
  308. * @param string $fileName
  309. * @return string
  310. */
  311. public function getCachedSCSS(string $appName, string $fileName): string {
  312. $tmpfileLoc = explode('/', $fileName);
  313. $fileName = array_pop($tmpfileLoc);
  314. $fileName = $this->prependVersionPrefix($this->prependBaseurlPrefix(str_replace('.scss', '.css', $fileName)), $appName);
  315. return substr($this->urlGenerator->linkToRoute('core.Css.getCss', ['fileName' => $fileName, 'appName' => $appName]), strlen(\OC::$WEBROOT) + 1);
  316. }
  317. /**
  318. * Prepend hashed base url to the css file
  319. * @param string $cssFile
  320. * @return string
  321. */
  322. private function prependBaseurlPrefix(string $cssFile): string {
  323. $frontendController = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
  324. return substr(md5($this->urlGenerator->getBaseUrl() . $frontendController), 0, 4) . '-' . $cssFile;
  325. }
  326. /**
  327. * Prepend hashed app version hash
  328. * @param string $cssFile
  329. * @param string $appId
  330. * @return string
  331. */
  332. private function prependVersionPrefix(string $cssFile, string $appId): string {
  333. $appVersion = \OC_App::getAppVersion($appId);
  334. if ($appVersion !== '0') {
  335. return substr(md5($appVersion), 0, 4) . '-' . $cssFile;
  336. }
  337. $coreVersion = \OC_Util::getVersionString();
  338. return substr(md5($coreVersion), 0, 4) . '-' . $cssFile;
  339. }
  340. /**
  341. * Get WebDir root
  342. * @param string $path the css file path
  343. * @param string $appName the app name
  344. * @param string $serverRoot the server root path
  345. * @param string $webRoot the nextcloud installation root path
  346. * @return string the webDir
  347. */
  348. private function getWebDir(string $path, string $appName, string $serverRoot, string $webRoot): string {
  349. // Detect if path is within server root AND if path is within an app path
  350. if (strpos($path, $serverRoot) === false && $appWebPath = \OC_App::getAppWebPath($appName)) {
  351. // Get the file path within the app directory
  352. $appDirectoryPath = explode($appName, $path)[1];
  353. // Remove the webroot
  354. return str_replace($webRoot, '', $appWebPath . $appDirectoryPath);
  355. }
  356. return $webRoot . substr($path, strlen($serverRoot));
  357. }
  358. }