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