Merge pull request #4199 from dokuwiki/issue4198
[dokuwiki.git] / lib / exe / css.php
blobf1e967dd8d2cc43ea3e488a64a69266c9bf5650f
1 <?php
3 /**
4 * DokuWiki StyleSheet creator
6 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author Andreas Gohr <andi@splitbrain.org>
8 */
10 use LesserPHP\Lessc;
11 use dokuwiki\StyleUtils;
12 use dokuwiki\Cache\Cache;
13 use dokuwiki\Extension\Event;
15 if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../');
16 if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching)
17 if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here
18 if (!defined('NL')) define('NL', "\n");
19 require_once(DOKU_INC . 'inc/init.php');
21 // Main (don't run when UNIT test)
22 if (!defined('SIMPLE_TEST')) {
23 header('Content-Type: text/css; charset=utf-8');
24 css_out();
28 // ---------------------- functions ------------------------------
30 /**
31 * Output all needed Styles
33 * @author Andreas Gohr <andi@splitbrain.org>
35 function css_out()
37 global $conf;
38 global $lang;
39 global $config_cascade;
40 global $INPUT;
42 if ($INPUT->str('s') == 'feed') {
43 $mediatypes = ['feed'];
44 $type = 'feed';
45 } else {
46 $mediatypes = ['screen', 'all', 'print', 'speech'];
47 $type = '';
50 // decide from where to get the template
51 $tpl = trim(preg_replace('/[^\w-]+/', '', $INPUT->str('t')));
52 if (!$tpl) {
53 $tpl = $conf['template'];
56 // load style.ini
57 $styleUtil = new StyleUtils($tpl, $INPUT->bool('preview'));
58 $styleini = $styleUtil->cssStyleini();
60 // cache influencers
61 $tplinc = tpl_incdir($tpl);
62 $cache_files = getConfigFiles('main');
63 $cache_files[] = $tplinc . 'style.ini';
64 $cache_files[] = DOKU_CONF . "tpl/$tpl/style.ini";
65 $cache_files[] = __FILE__;
66 if ($INPUT->bool('preview')) {
67 $cache_files[] = $conf['cachedir'] . '/preview.ini';
70 // Array of needed files and their web locations, the latter ones
71 // are needed to fix relative paths in the stylesheets
72 $media_files = [];
73 foreach ($mediatypes as $mediatype) {
74 $files = [];
76 // load core styles
77 $files[DOKU_INC . 'lib/styles/' . $mediatype . '.css'] = DOKU_BASE . 'lib/styles/';
79 // load jQuery-UI theme
80 if ($mediatype == 'screen') {
81 $files[DOKU_INC . 'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] =
82 DOKU_BASE . 'lib/scripts/jquery/jquery-ui-theme/';
84 // load plugin styles
85 $files = array_merge($files, css_pluginstyles($mediatype));
86 // load template styles
87 if (isset($styleini['stylesheets'][$mediatype])) {
88 $files = array_merge($files, $styleini['stylesheets'][$mediatype]);
90 // load user styles
91 if (isset($config_cascade['userstyle'][$mediatype]) && is_array($config_cascade['userstyle'][$mediatype])) {
92 foreach ($config_cascade['userstyle'][$mediatype] as $userstyle) {
93 $files[$userstyle] = DOKU_BASE;
97 // Let plugins decide to either put more styles here or to remove some
98 $media_files[$mediatype] = css_filewrapper($mediatype, $files);
99 $CSSEvt = new Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]);
101 // Make it preventable.
102 if ($CSSEvt->advise_before()) {
103 $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files']));
104 } else {
105 // unset if prevented. Nothing will be printed for this mediatype.
106 unset($media_files[$mediatype]);
109 // finish event.
110 $CSSEvt->advise_after();
113 // The generated script depends on some dynamic options
114 $cache = new Cache(
115 'styles' .
116 $_SERVER['HTTP_HOST'] .
117 $_SERVER['SERVER_PORT'] .
118 $INPUT->bool('preview') .
119 DOKU_BASE .
120 $tpl .
121 $type,
122 '.css'
124 $cache->setEvent('CSS_CACHE_USE');
126 // check cache age & handle conditional request
127 // This may exit if a cache can be used
128 $cache_ok = $cache->useCache(['files' => $cache_files]);
129 http_cached($cache->cache, $cache_ok);
131 // start output buffering
132 ob_start();
134 // Fire CSS_STYLES_INCLUDED for one last time to let the
135 // plugins decide whether to include the DW default styles.
136 // This can be done by preventing the Default.
137 $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT');
138 Event::createAndTrigger('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles');
140 // build the stylesheet
141 foreach ($mediatypes as $mediatype) {
142 // Check if there is a wrapper set for this type.
143 if (!isset($media_files[$mediatype])) {
144 continue;
147 $cssData = $media_files[$mediatype];
149 // Print the styles.
150 echo NL;
151 if ($cssData['encapsulate'] === true) {
152 echo $cssData['encapsulationPrefix'] . ' {';
154 echo '/* START ' . $cssData['mediatype'] . ' styles */' . NL;
156 // load files
157 foreach ($cssData['files'] as $file => $location) {
158 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
159 echo "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
160 echo css_loadfile($file, $location);
163 echo NL;
164 if ($cssData['encapsulate'] === true) {
165 echo '} /* /@media ';
166 } else {
167 echo '/*';
169 echo ' END ' . $cssData['mediatype'] . ' styles */' . NL;
172 // end output buffering and get contents
173 $css = ob_get_contents();
174 ob_end_clean();
176 // strip any source maps
177 stripsourcemaps($css);
179 // apply style replacements
180 $css = css_applystyle($css, $styleini['replacements']);
182 // parse less
183 $css = css_parseless($css);
185 // compress whitespace and comments
186 if ($conf['compress']) {
187 $css = css_compress($css);
190 // embed small images right into the stylesheet
191 if ($conf['cssdatauri']) {
192 $base = preg_quote(DOKU_BASE, '#');
193 $css = preg_replace_callback('#(url\([ \'"]*)(' . $base . ')(.*?(?:\.(png|gif)))#i', 'css_datauri', $css);
196 http_cached_finish($cache->cache, $css);
200 * Uses phpless to parse LESS in our CSS
202 * most of this function is error handling to show a nice useful error when
203 * LESS compilation fails
205 * @param string $css
206 * @return string
208 function css_parseless($css)
210 global $conf;
212 $less = new Lessc();
213 $less->setImportDir([DOKU_INC]);
214 $less->setPreserveComments(!$conf['compress']);
216 if (defined('DOKU_UNITTEST')) {
217 $less->addImportDir(TMP_DIR);
220 try {
221 return $less->compile($css);
222 } catch (Exception $e) {
223 // get exception message
224 $msg = str_replace(["\n", "\r", "'"], [], $e->getMessage());
226 // try to use line number to find affected file
227 if (preg_match('/line: (\d+)$/', $msg, $m)) {
228 $msg = substr($msg, 0, -1 * strlen($m[0])); //remove useless linenumber
229 $lno = $m[1];
231 // walk upwards to last include
232 $lines = explode("\n", $css);
233 for ($i = $lno - 1; $i >= 0; $i--) {
234 if (preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)) {
235 // we found it, add info to message
236 $msg .= ' in ' . $m[2] . ' at line ' . ($lno - $i);
237 break;
242 // something went wrong
243 $error = 'A fatal error occured during compilation of the CSS files. ' .
244 'If you recently installed a new plugin or template it ' .
245 'might be broken and you should try disabling it again. [' . $msg . ']';
247 echo ".dokuwiki:before {
248 content: '$error';
249 background-color: red;
250 display: block;
251 background-color: #fcc;
252 border-color: #ebb;
253 color: #000;
254 padding: 0.5em;
257 exit;
262 * Does placeholder replacements in the style according to
263 * the ones defined in a templates style.ini file
265 * This also adds the ini defined placeholders as less variables
266 * (sans the surrounding __ and with a ini_ prefix)
268 * @param string $css
269 * @param array $replacements array(placeholder => value)
270 * @return string
272 * @author Andreas Gohr <andi@splitbrain.org>
274 function css_applystyle($css, $replacements)
276 // we convert ini replacements to LESS variable names
277 // and build a list of variable: value; pairs
278 $less = '';
279 foreach ((array)$replacements as $key => $value) {
280 $lkey = trim($key, '_');
281 $lkey = '@ini_' . $lkey;
282 $less .= "$lkey: $value;\n";
284 $replacements[$key] = $lkey;
287 // we now replace all old ini replacements with LESS variables
288 $css = strtr($css, $replacements);
290 // now prepend the list of LESS variables as the very first thing
291 $css = $less . $css;
292 return $css;
296 * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED
298 * @param string $mediatype type ofthe current media files/content set
299 * @param array $files set of files that define the current mediatype
300 * @return array
302 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
304 function css_filewrapper($mediatype, $files = [])
306 return [
307 'files' => $files,
308 'mediatype' => $mediatype,
309 'encapsulate' => $mediatype != 'all',
310 'encapsulationPrefix' => '@media ' . $mediatype
315 * Prints the @media encapsulated default styles of DokuWiki
317 * This function is being called by a CSS_STYLES_INCLUDED event
318 * The event can be distinguished by the mediatype which is:
319 * DW_DEFAULT
321 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
323 function css_defaultstyles()
325 // print the default classes for interwiki links and file downloads
326 echo '@media screen {';
327 css_interwiki();
328 css_filetypes();
329 echo '}';
333 * Prints classes for interwikilinks
335 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
336 * $name is the identifier given in the config. All Interwiki links get
337 * an default style with a default icon. If a special icon is available
338 * for an interwiki URL it is set in it's own class. Both classes can be
339 * overwritten in the template or userstyles.
341 * @author Andreas Gohr <andi@splitbrain.org>
343 function css_interwiki()
346 // default style
347 echo 'a.interwiki {';
348 echo ' background: transparent url(' . DOKU_BASE . 'lib/images/interwiki.svg) 0 0 no-repeat;';
349 echo ' background-size: 1.2em;';
350 echo ' padding: 0 0 0 1.4em;';
351 echo '}';
353 // additional styles when icon available
354 $iwlinks = getInterwiki();
355 foreach (array_keys($iwlinks) as $iw) {
356 $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $iw);
357 foreach (['svg', 'png', 'gif'] as $ext) {
358 $file = 'lib/images/interwiki/' . $iw . '.' . $ext;
360 if (file_exists(DOKU_INC . $file)) {
361 echo "a.iw_$class {";
362 echo ' background-image: url(' . DOKU_BASE . $file . ')';
363 echo '}';
364 break;
371 * Prints classes for file download links
373 * @author Andreas Gohr <andi@splitbrain.org>
375 function css_filetypes()
378 // default style
379 echo '.mediafile {';
380 echo ' background: transparent url(' . DOKU_BASE . 'lib/images/fileicons/svg/file.svg) 0px 1px no-repeat;';
381 echo ' background-size: 1.2em;';
382 echo ' padding-left: 1.5em;';
383 echo '}';
385 // additional styles when icon available
386 // scan directory for all icons
387 $exts = [];
388 if ($dh = opendir(DOKU_INC . 'lib/images/fileicons/svg')) {
389 while (false !== ($file = readdir($dh))) {
390 if (preg_match('/(.*?)\.svg$/i', $file, $match)) {
391 $exts[] = strtolower($match[1]);
394 closedir($dh);
396 foreach ($exts as $ext) {
397 $class = preg_replace('/[^_\-a-z0-9]+/', '_', $ext);
398 echo ".mf_$class {";
399 echo ' background-image: url(' . DOKU_BASE . 'lib/images/fileicons/svg/' . $ext . '.svg)';
400 echo '}';
405 * Loads a given file and fixes relative URLs with the
406 * given location prefix
408 * @param string $file file system path
409 * @param string $location
410 * @return string
412 function css_loadfile($file, $location = '')
414 $css_file = new DokuCssFile($file);
415 return $css_file->load($location);
419 * Helper class to abstract loading of css/less files
421 * @author Chris Smith <chris@jalakai.co.uk>
423 class DokuCssFile
425 protected $filepath; // file system path to the CSS/Less file
426 protected $location; // base url location of the CSS/Less file
427 protected $relative_path;
429 public function __construct($file)
431 $this->filepath = $file;
435 * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
436 * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
437 * for less files.
439 * @param string $location base url for this file
440 * @return string the CSS/Less contents of the file
442 public function load($location = '')
444 if (!file_exists($this->filepath)) return '';
446 $css = io_readFile($this->filepath);
447 if (!$location) return $css;
449 $this->location = $location;
451 $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#', [$this, 'replacements'], $css);
452 $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#', [$this, 'replacements'], $css);
454 return $css;
458 * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
460 * @return string relative file system path
462 protected function getRelativePath()
465 if (is_null($this->relative_path)) {
466 $basedir = [DOKU_INC];
468 // during testing, files may be found relative to a second base dir, TMP_DIR
469 if (defined('DOKU_UNITTEST')) {
470 $basedir[] = realpath(TMP_DIR);
473 $basedir = array_map('preg_quote_cb', $basedir);
474 $regex = '/^(' . implode('|', $basedir) . ')/';
475 $this->relative_path = preg_replace($regex, '', dirname($this->filepath));
478 return $this->relative_path;
482 * preg_replace callback to adjust relative urls from relative to this file to relative
483 * to the appropriate dokuwiki root location as described in the code
485 * @param array $match see http://php.net/preg_replace_callback
486 * @return string see http://php.net/preg_replace_callback
488 public function replacements($match)
491 if (preg_match('#^(/|data:|https?://)#', $match[3])) { // not a relative url? - no adjustment required
492 return $match[0];
493 } elseif (str_ends_with($match[3], '.less')) { // a less file import? - requires a file system location
494 if ($match[3][0] != '/') {
495 $match[3] = $this->getRelativePath() . '/' . $match[3];
497 } else { // everything else requires a url adjustment
498 $match[3] = $this->location . $match[3];
501 return implode('', array_slice($match, 1));
506 * Convert local image URLs to data URLs if the filesize is small
508 * Callback for preg_replace_callback
510 * @param array $match
511 * @return string
513 function css_datauri($match)
515 global $conf;
517 $pre = unslash($match[1]);
518 $base = unslash($match[2]);
519 $url = unslash($match[3]);
520 $ext = unslash($match[4]);
522 $local = DOKU_INC . $url;
523 $size = @filesize($local);
524 if ($size && $size < $conf['cssdatauri']) {
525 $data = base64_encode(file_get_contents($local));
527 if (!empty($data)) {
528 $url = 'data:image/' . $ext . ';base64,' . $data;
529 } else {
530 $url = $base . $url;
532 return $pre . $url;
537 * Returns a list of possible Plugin Styles (no existance check here)
539 * @param string $mediatype
540 * @return array
541 * @author Andreas Gohr <andi@splitbrain.org>
544 function css_pluginstyles($mediatype = 'screen')
546 $list = [];
547 $plugins = plugin_list();
548 foreach ($plugins as $p) {
549 $list[DOKU_PLUGIN . "$p/$mediatype.css"] = DOKU_BASE . "lib/plugins/$p/";
550 $list[DOKU_PLUGIN . "$p/$mediatype.less"] = DOKU_BASE . "lib/plugins/$p/";
551 // alternative for screen.css
552 if ($mediatype == 'screen') {
553 $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
554 $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
557 return $list;
561 * Very simple CSS optimizer
563 * @param string $css
564 * @return string
565 * @author Andreas Gohr <andi@splitbrain.org>
568 function css_compress($css)
570 // replace quoted strings with placeholder
571 $quote_storage = [];
573 $quote_cb = function ($match) use (&$quote_storage) {
574 $quote_storage[] = $match[0];
575 return '"STR' . (count($quote_storage) - 1) . '"';
578 $css = preg_replace_callback('/(([\'"]).*?(?<!\\\\)\2)/', $quote_cb, $css);
580 // strip comments through a callback
581 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s', 'css_comment_cb', $css);
583 // strip (incorrect but common) one line comments
584 $css = preg_replace_callback('/^.*\/\/.*$/m', 'css_onelinecomment_cb', $css);
586 // strip whitespaces
587 $css = preg_replace('![\r\n\t ]+!', ' ', $css);
588 $css = preg_replace('/ ?([;,{}\/]) ?/', '\\1', $css);
589 $css = preg_replace('/ ?: /', ':', $css);
591 // number compression
592 $css = preg_replace(
593 '/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
594 '$1$2$3',
595 $css
596 ); // "0.1em" to ".1em", "1.10em" to "1.1em"
597 $css = preg_replace(
598 '/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
599 '$1$2',
600 $css
601 ); // ".0em" to "0"
602 $css = preg_replace(
603 '/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
604 '$1',
605 $css
606 ); // "0.0em" to "0"
607 $css = preg_replace(
608 '/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
609 '$1$3',
610 $css
611 ); // "1.0em" to "1em"
612 $css = preg_replace(
613 '/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
614 '$1$2$3',
615 $css
616 ); // "001em" to "1em"
618 // shorten attributes (1em 1em 1em 1em -> 1em)
619 $css = preg_replace(
620 '/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/',
621 '$1$2',
622 $css
623 ); // "1em 1em 1em 1em" to "1em"
624 $css = preg_replace(
625 '/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/',
626 '$1$2 $3',
627 $css
628 ); // "1em 2em 1em 2em" to "1em 2em"
630 // shorten colors
631 $css = preg_replace(
632 "/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/",
633 "#\\1\\2\\3",
634 $css
637 // replace back protected strings
638 $quote_back_cb = function ($match) use (&$quote_storage) {
639 return $quote_storage[$match[1]];
642 $css = preg_replace_callback('/"STR(\d+)"/', $quote_back_cb, $css);
643 $css = trim($css);
645 return $css;
649 * Callback for css_compress()
651 * Keeps short comments (< 5 chars) to maintain typical browser hacks
653 * @param array $matches
654 * @return string
656 * @author Andreas Gohr <andi@splitbrain.org>
659 function css_comment_cb($matches)
661 if (strlen($matches[2]) > 4) return '';
662 return $matches[0];
666 * Callback for css_compress()
668 * Strips one line comments but makes sure it will not destroy url() constructs with slashes
670 * @param array $matches
671 * @return string
673 function css_onelinecomment_cb($matches)
675 $line = $matches[0];
677 $i = 0;
678 $len = strlen($line);
680 while ($i < $len) {
681 $nextcom = strpos($line, '//', $i);
682 $nexturl = stripos($line, 'url(', $i);
684 if ($nextcom === false) {
685 // no more comments, we're done
686 $i = $len;
687 break;
690 if ($nexturl === false || $nextcom < $nexturl) {
691 // no url anymore, strip comment and be done
692 $i = $nextcom;
693 break;
696 // we have an upcoming url
697 $i = strpos($line, ')', $nexturl);
700 return substr($line, 0, $i);
703 //Setup VIM: ex: et ts=4 :