xref: /dokuwiki/lib/exe/css.php (revision 10287e994a20d03356a34541b59ed0d513bbacaf)
1<?php
2
3/**
4 * DokuWiki StyleSheet creator
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 */
9
10use LesserPHP\Lessc;
11use dokuwiki\StyleUtils;
12use dokuwiki\Cache\Cache;
13use dokuwiki\Extension\Event;
14
15if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../');
16if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching)
17if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here
18if (!defined('NL')) define('NL', "\n");
19require_once(DOKU_INC . 'inc/init.php');
20
21// Main (don't run when UNIT test)
22if (!defined('SIMPLE_TEST')) {
23    header('Content-Type: text/css; charset=utf-8');
24    css_out();
25}
26
27
28// ---------------------- functions ------------------------------
29
30/**
31 * Output all needed Styles
32 *
33 * @author Andreas Gohr <andi@splitbrain.org>
34 */
35function css_out()
36{
37    global $conf;
38    global $lang;
39    global $config_cascade;
40    global $INPUT;
41
42    if ($INPUT->str('s') == 'feed') {
43        $mediatypes = ['feed'];
44        $type = 'feed';
45    } else {
46        $mediatypes = ['screen', 'all', 'print', 'speech'];
47        $type = '';
48    }
49
50    // decide from where to get the template
51    $tpl = trim(preg_replace('/[^\w-]+/', '', $INPUT->str('t')));
52    if (!$tpl) {
53        $tpl = $conf['template'];
54    }
55
56    // load style.ini
57    $styleUtil = new StyleUtils($tpl, $INPUT->bool('preview'));
58    $styleini = $styleUtil->cssStyleini();
59
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';
68    }
69
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 = [];
75
76        // load core styles
77        $files[DOKU_INC . 'lib/styles/' . $mediatype . '.css'] = DOKU_BASE . 'lib/styles/';
78
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/';
83        }
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]);
89        }
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;
94            }
95        }
96
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]);
100
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]);
107        }
108
109        // finish event.
110        $CSSEvt->advise_after();
111    }
112
113    // The generated script depends on some dynamic options
114    $cache = new Cache(
115        'styles' .
116        $INPUT->bool('preview') .
117        DOKU_BASE .
118        $tpl .
119        $type,
120        '.css'
121    );
122    $cache->setEvent('CSS_CACHE_USE');
123
124    // check cache age & handle conditional request
125    // This may exit if a cache can be used
126    $cache_ok = $cache->useCache(['files' => $cache_files]);
127    http_cached($cache->cache, $cache_ok);
128
129    // start output buffering
130    ob_start();
131
132    // Fire CSS_STYLES_INCLUDED for one last time to let the
133    // plugins decide whether to include the DW default styles.
134    // This can be done by preventing the Default.
135    $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT');
136    Event::createAndTrigger('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles');
137
138    // build the stylesheet
139    foreach ($mediatypes as $mediatype) {
140        // Check if there is a wrapper set for this type.
141        if (!isset($media_files[$mediatype])) {
142            continue;
143        }
144
145        $cssData = $media_files[$mediatype];
146
147        // Print the styles.
148        echo NL;
149        if ($cssData['encapsulate'] === true) {
150            echo $cssData['encapsulationPrefix'] . ' {';
151        }
152        echo '/* START ' . $cssData['mediatype'] . ' styles */' . NL;
153
154        // load files
155        foreach ($cssData['files'] as $file => $location) {
156            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
157            echo "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
158            echo css_loadfile($file, $location);
159        }
160
161        echo NL;
162        if ($cssData['encapsulate'] === true) {
163            echo '} /* /@media ';
164        } else {
165            echo '/*';
166        }
167        echo ' END ' . $cssData['mediatype'] . ' styles */' . NL;
168    }
169
170    // end output buffering and get contents
171    $css = ob_get_contents();
172    ob_end_clean();
173
174    // strip any source maps
175    stripsourcemaps($css);
176
177    // apply style replacements
178    $css = css_applystyle($css, $styleini['replacements']);
179
180    // parse less
181    $css = css_parseless($css);
182
183    // compress whitespace and comments
184    if ($conf['compress']) {
185        $css = css_compress($css);
186    }
187
188    // embed small images right into the stylesheet
189    if ($conf['cssdatauri']) {
190        $base = preg_quote(DOKU_BASE, '#');
191        $css = preg_replace_callback('#(url\([ \'"]*)(' . $base . ')(.*?(?:\.(png|gif)))#i', css_datauri(...), $css);
192    }
193
194    http_cached_finish($cache->cache, $css);
195}
196
197/**
198 * Uses phpless to parse LESS in our CSS
199 *
200 * most of this function is error handling to show a nice useful error when
201 * LESS compilation fails
202 *
203 * @param string $css
204 * @return string
205 */
206function css_parseless($css)
207{
208    global $conf;
209
210    $less = new Lessc();
211    $less->setImportDir([DOKU_INC]);
212    $less->setPreserveComments(!$conf['compress']);
213
214    if (defined('DOKU_UNITTEST')) {
215        $less->addImportDir(TMP_DIR);
216    }
217
218    try {
219        return $less->compile($css);
220    } catch (Exception $e) {
221        // get exception message
222        $msg = str_replace(["\n", "\r", "'"], [], $e->getMessage());
223
224        // try to use line number to find affected file
225        if (preg_match('/line: (\d+)$/', $msg, $m)) {
226            $msg = substr($msg, 0, -1 * strlen($m[0])); //remove useless linenumber
227            $lno = $m[1];
228
229            // walk upwards to last include
230            $lines = explode("\n", $css);
231            for ($i = $lno - 1; $i >= 0; $i--) {
232                if (preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)) {
233                    // we found it, add info to message
234                    $msg .= ' in ' . $m[2] . ' at line ' . ($lno - $i);
235                    break;
236                }
237            }
238        }
239
240        // something went wrong
241        $error = 'A fatal error occured during compilation of the CSS files. ' .
242            'If you recently installed a new plugin or template it ' .
243            'might be broken and you should try disabling it again. [' . $msg . ']';
244
245        echo ".dokuwiki:before {
246            content: '$error';
247            background-color: red;
248            display: block;
249            background-color: #fcc;
250            border-color: #ebb;
251            color: #000;
252            padding: 0.5em;
253        }";
254
255        exit;
256    }
257}
258
259/**
260 * Does placeholder replacements in the style according to
261 * the ones defined in a templates style.ini file
262 *
263 * This also adds the ini defined placeholders as less variables
264 * (sans the surrounding __ and with a ini_ prefix)
265 *
266 * @param string $css
267 * @param array $replacements array(placeholder => value)
268 * @return string
269 *
270 * @author Andreas Gohr <andi@splitbrain.org>
271 */
272function css_applystyle($css, $replacements)
273{
274    // we convert ini replacements to LESS variable names
275    // and build a list of variable: value; pairs
276    $less = '';
277    foreach ((array)$replacements as $key => $value) {
278        $lkey = trim($key, '_');
279        $lkey = '@ini_' . $lkey;
280        $less .= "$lkey: $value;\n";
281
282        $replacements[$key] = $lkey;
283    }
284
285    // we now replace all old ini replacements with LESS variables
286    $css = strtr($css, $replacements);
287
288    // now prepend the list of LESS variables as the very first thing
289    $css = $less . $css;
290    return $css;
291}
292
293/**
294 * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED
295 *
296 * @param string $mediatype type ofthe current media files/content set
297 * @param array $files set of files that define the current mediatype
298 * @return array
299 *
300 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
301 */
302function css_filewrapper($mediatype, $files = [])
303{
304    return [
305        'files' => $files,
306        'mediatype' => $mediatype,
307        'encapsulate' => $mediatype != 'all',
308        'encapsulationPrefix' => '@media ' . $mediatype
309    ];
310}
311
312/**
313 * Prints the @media encapsulated default styles of DokuWiki
314 *
315 * This function is being called by a CSS_STYLES_INCLUDED event
316 * The event can be distinguished by the mediatype which is:
317 *   DW_DEFAULT
318 *
319 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
320 */
321function css_defaultstyles()
322{
323    // print the default classes for interwiki links and file downloads
324    echo '@media screen {';
325    css_interwiki();
326    css_filetypes();
327    echo '}';
328}
329
330/**
331 * Prints classes for interwikilinks
332 *
333 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
334 * $name is the identifier given in the config. All Interwiki links get
335 * an default style with a default icon. If a special icon is available
336 * for an interwiki URL it is set in it's own class. Both classes can be
337 * overwritten in the template or userstyles.
338 *
339 * @author Andreas Gohr <andi@splitbrain.org>
340 */
341function css_interwiki()
342{
343
344    // default style
345    echo 'a.interwiki {';
346    echo ' background: transparent url(' . DOKU_BASE . 'lib/images/interwiki.svg) 0 0 no-repeat;';
347    echo ' background-size: 1.2em;';
348    echo ' padding: 0 0 0 1.4em;';
349    echo '}';
350
351    // additional styles when icon available
352    $iwlinks = getInterwiki();
353    foreach (array_keys($iwlinks) as $iw) {
354        $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $iw);
355        foreach (['svg', 'png', 'gif'] as $ext) {
356            $file = 'lib/images/interwiki/' . $iw . '.' . $ext;
357
358            if (file_exists(DOKU_INC . $file)) {
359                echo "a.iw_$class {";
360                echo '  background-image: url(' . DOKU_BASE . $file . ')';
361                echo '}';
362                break;
363            }
364        }
365    }
366}
367
368/**
369 * Prints classes for file download links
370 *
371 * @author Andreas Gohr <andi@splitbrain.org>
372 */
373function css_filetypes()
374{
375
376    // default style
377    echo '.mediafile {';
378    echo ' background: transparent url(' . DOKU_BASE . 'lib/images/fileicons/svg/file.svg) 0px 1px no-repeat;';
379    echo ' background-size: 1.2em;';
380    echo ' padding-left: 1.5em;';
381    echo '}';
382
383    // additional styles when icon available
384    // scan directory for all icons
385    $exts = [];
386    if ($dh = opendir(DOKU_INC . 'lib/images/fileicons/svg')) {
387        while (false !== ($file = readdir($dh))) {
388            if (preg_match('/(.*?)\.svg$/i', $file, $match)) {
389                $exts[] = strtolower($match[1]);
390            }
391        }
392        closedir($dh);
393    }
394    foreach ($exts as $ext) {
395        $class = preg_replace('/[^_\-a-z0-9]+/', '_', $ext);
396        echo ".mf_$class {";
397        echo '  background-image: url(' . DOKU_BASE . 'lib/images/fileicons/svg/' . $ext . '.svg)';
398        echo '}';
399    }
400}
401
402/**
403 * Loads a given file and fixes relative URLs with the
404 * given location prefix
405 *
406 * @param string $file file system path
407 * @param string $location
408 * @return string
409 */
410function css_loadfile($file, $location = '')
411{
412    $css_file = new DokuCssFile($file);
413    return $css_file->load($location);
414}
415
416/**
417 * Helper class to abstract loading of css/less files
418 *
419 * @author Chris Smith <chris@jalakai.co.uk>
420 */
421class DokuCssFile
422{
423    protected $filepath;             // file system path to the CSS/Less file
424    protected $location;             // base url location of the CSS/Less file
425    protected $relative_path;
426
427    public function __construct($file)
428    {
429        $this->filepath = $file;
430    }
431
432    /**
433     * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
434     * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
435     * for less files.
436     *
437     * @param string $location base url for this file
438     * @return string the CSS/Less contents of the file
439     */
440    public function load($location = '')
441    {
442        if (!file_exists($this->filepath)) return '';
443
444        $css = io_readFile($this->filepath);
445        if (!$location) return $css;
446
447        $this->location = $location;
448
449        $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#', $this->replacements(...), $css);
450        $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#', $this->replacements(...), $css);
451
452        return $css;
453    }
454
455    /**
456     * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
457     *
458     * @return string   relative file system path
459     */
460    protected function getRelativePath()
461    {
462
463        if (is_null($this->relative_path)) {
464            $basedir = [DOKU_INC];
465
466            // during testing, files may be found relative to a second base dir, TMP_DIR
467            if (defined('DOKU_UNITTEST')) {
468                $basedir[] = realpath(TMP_DIR);
469            }
470
471            $basedir = array_map(preg_quote_cb(...), $basedir);
472            $regex = '/^(' . implode('|', $basedir) . ')/';
473            $this->relative_path = preg_replace($regex, '', dirname($this->filepath));
474        }
475
476        return $this->relative_path;
477    }
478
479    /**
480     * preg_replace callback to adjust relative urls from relative to this file to relative
481     * to the appropriate dokuwiki root location as described in the code
482     *
483     * @param array $match see http://php.net/preg_replace_callback
484     * @return string   see http://php.net/preg_replace_callback
485     */
486    public function replacements($match)
487    {
488
489        if (preg_match('#^(/|data:|https?://)#', $match[3])) { // not a relative url? - no adjustment required
490            return $match[0];
491        } elseif (str_ends_with($match[3], '.less')) { // a less file import? - requires a file system location
492            if ($match[3][0] != '/') {
493                $match[3] = $this->getRelativePath() . '/' . $match[3];
494            }
495        } else { // everything else requires a url adjustment
496            $match[3] = $this->location . $match[3];
497        }
498
499        return implode('', array_slice($match, 1));
500    }
501}
502
503/**
504 * Convert local image URLs to data URLs if the filesize is small
505 *
506 * Callback for preg_replace_callback
507 *
508 * @param array $match
509 * @return string
510 */
511function css_datauri($match)
512{
513    global $conf;
514
515    $pre = unslash($match[1]);
516    $base = unslash($match[2]);
517    $url = unslash($match[3]);
518    $ext = unslash($match[4]);
519
520    $local = DOKU_INC . $url;
521    $size = @filesize($local);
522    if ($size && $size < $conf['cssdatauri']) {
523        $data = base64_encode(file_get_contents($local));
524    }
525    if (!empty($data)) {
526        $url = 'data:image/' . $ext . ';base64,' . $data;
527    } else {
528        $url = $base . $url;
529    }
530    return $pre . $url;
531}
532
533
534/**
535 * Returns a list of possible Plugin Styles (no existance check here)
536 *
537 * @param string $mediatype
538 * @return array
539 * @author Andreas Gohr <andi@splitbrain.org>
540 *
541 */
542function css_pluginstyles($mediatype = 'screen')
543{
544    $list = [];
545    $plugins = plugin_list();
546    foreach ($plugins as $p) {
547        $list[DOKU_PLUGIN . "$p/$mediatype.css"] = DOKU_BASE . "lib/plugins/$p/";
548        $list[DOKU_PLUGIN . "$p/$mediatype.less"] = DOKU_BASE . "lib/plugins/$p/";
549        // alternative for screen.css
550        if ($mediatype == 'screen') {
551            $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
552            $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
553        }
554    }
555    return $list;
556}
557
558/**
559 * Very simple CSS optimizer
560 *
561 * @param string $css
562 * @return string
563 * @author Andreas Gohr <andi@splitbrain.org>
564 *
565 */
566function css_compress($css)
567{
568    // replace quoted strings with placeholder
569    $quote_storage = [];
570
571    $quote_cb = function ($match) use (&$quote_storage) {
572        $quote_storage[] = $match[0];
573        return '"STR' . (count($quote_storage) - 1) . '"';
574    };
575
576    $css = preg_replace_callback('/(([\'"]).*?(?<!\\\\)\2)/', $quote_cb, $css);
577
578    // strip comments through a callback
579    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s', css_comment_cb(...), $css);
580
581    // strip (incorrect but common) one line comments
582    $css = preg_replace_callback('/^.*\/\/.*$/m', css_onelinecomment_cb(...), $css);
583
584    // strip whitespaces
585    $css = preg_replace('![\r\n\t ]+!', ' ', $css);
586    $css = preg_replace('/ ?([;,{}\/]) ?/', '\\1', $css);
587    $css = preg_replace('/ ?: /', ':', $css);
588
589    // number compression
590    $css = preg_replace(
591        '/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
592        '$1$2$3',
593        $css
594    ); // "0.1em" to ".1em", "1.10em" to "1.1em"
595    $css = preg_replace(
596        '/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
597        '$1$2',
598        $css
599    ); // ".0em" to "0"
600    $css = preg_replace(
601        '/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
602        '$1',
603        $css
604    ); // "0.0em" to "0"
605    $css = preg_replace(
606        '/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
607        '$1$3',
608        $css
609    ); // "1.0em" to "1em"
610    $css = preg_replace(
611        '/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
612        '$1$2$3',
613        $css
614    ); // "001em" to "1em"
615
616    // shorten attributes (1em 1em 1em 1em -> 1em)
617    $css = preg_replace(
618        '/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/',
619        '$1$2',
620        $css
621    ); // "1em 1em 1em 1em" to "1em"
622    $css = preg_replace(
623        '/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/',
624        '$1$2 $3',
625        $css
626    ); // "1em 2em 1em 2em" to "1em 2em"
627
628    // shorten colors
629    $css = preg_replace(
630        "/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/",
631        "#\\1\\2\\3",
632        $css
633    );
634
635    // replace back protected strings
636    $quote_back_cb = function ($match) use (&$quote_storage) {
637        return $quote_storage[$match[1]];
638    };
639
640    $css = preg_replace_callback('/"STR(\d+)"/', $quote_back_cb, $css);
641    $css = trim($css);
642
643    return $css;
644}
645
646/**
647 * Callback for css_compress()
648 *
649 * Keeps short comments (< 5 chars) to maintain typical browser hacks
650 *
651 * @param array $matches
652 * @return string
653 *
654 * @author Andreas Gohr <andi@splitbrain.org>
655 *
656 */
657function css_comment_cb($matches)
658{
659    if (strlen($matches[2]) > 4) return '';
660    return $matches[0];
661}
662
663/**
664 * Callback for css_compress()
665 *
666 * Strips one line comments but makes sure it will not destroy url() constructs with slashes
667 *
668 * @param array $matches
669 * @return string
670 */
671function css_onelinecomment_cb($matches)
672{
673    $line = $matches[0];
674
675    $i = 0;
676    $len = strlen($line);
677
678    while ($i < $len) {
679        $nextcom = strpos($line, '//', $i);
680        $nexturl = stripos($line, 'url(', $i);
681
682        if ($nextcom === false) {
683            // no more comments, we're done
684            $i = $len;
685            break;
686        }
687
688        if ($nexturl === false || $nextcom < $nexturl) {
689            // no url anymore, strip comment and be done
690            $i = $nextcom;
691            break;
692        }
693
694        // we have an upcoming url
695        $i = strpos($line, ')', $nexturl);
696    }
697
698    return substr($line, 0, $i);
699}
700
701//Setup VIM: ex: et ts=4 :
702