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