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