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