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