xref: /dokuwiki/lib/exe/css.php (revision dfc5e46cbee86f9c2f44b5bc5f72505dd8847352)
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 $css
166 * @return string
167 */
168function css_parseless($css) {
169    global $conf;
170
171    $less = new lessc();
172    $less->importDir[] = DOKU_INC;
173    $less->setPreserveComments(!$conf['compress']);
174
175    if (defined('DOKU_UNITTEST')){
176        $less->importDir[] = TMP_DIR;
177    }
178
179    try {
180        return $less->compile($css);
181    } catch(Exception $e) {
182        // get exception message
183        $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage());
184
185        // try to use line number to find affected file
186        if(preg_match('/line: (\d+)$/', $msg, $m)){
187            $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber
188            $lno = $m[1];
189
190            // walk upwards to last include
191            $lines = explode("\n", $css);
192            for($i=$lno-1; $i>=0; $i--){
193                if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){
194                    // we found it, add info to message
195                    $msg .= ' in '.$m[2].' at line '.($lno-$i);
196                    break;
197                }
198            }
199        }
200
201        // something went wrong
202        $error = 'A fatal error occured during compilation of the CSS files. '.
203            'If you recently installed a new plugin or template it '.
204            'might be broken and you should try disabling it again. ['.$msg.']';
205
206        echo ".dokuwiki:before {
207            content: '$error';
208            background-color: red;
209            display: block;
210            background-color: #fcc;
211            border-color: #ebb;
212            color: #000;
213            padding: 0.5em;
214        }";
215
216        exit;
217    }
218}
219
220/**
221 * Does placeholder replacements in the style according to
222 * the ones defined in a templates style.ini file
223 *
224 * This also adds the ini defined placeholders as less variables
225 * (sans the surrounding __ and with a ini_ prefix)
226 *
227 * @author Andreas Gohr <andi@splitbrain.org>
228 */
229function css_applystyle($css, $replacements) {
230    // we convert ini replacements to LESS variable names
231    // and build a list of variable: value; pairs
232    $less = '';
233    foreach((array) $replacements as $key => $value) {
234        $lkey = trim($key, '_');
235        $lkey = '@ini_'.$lkey;
236        $less .= "$lkey: $value;\n";
237
238        $replacements[$key] = $lkey;
239    }
240
241    // we now replace all old ini replacements with LESS variables
242    $css = strtr($css, $replacements);
243
244    // now prepend the list of LESS variables as the very first thing
245    $css = $less.$css;
246    return $css;
247}
248
249/**
250 * Load style ini contents
251 *
252 * Loads and merges style.ini files from template and config and prepares
253 * the stylesheet modes
254 *
255 * @author Andreas Gohr <andi@splitbrain.org>
256 * @param string $tpl the used template
257 * @return array with keys 'stylesheets' and 'replacements'
258 */
259function css_styleini($tpl) {
260    $stylesheets = array(); // mode, file => base
261    $replacements = array(); // placeholder => value
262
263    // load template's style.ini
264    $incbase = tpl_incdir($tpl);
265    $webbase = tpl_basedir($tpl);
266    $ini = $incbase.'style.ini';
267    if(file_exists($ini)){
268        $data = parse_ini_file($ini, true);
269
270        // stylesheets
271        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
272            $stylesheets[$mode][$incbase.$file] = $webbase;
273        }
274
275        // replacements
276        if(is_array($data['replacements'])){
277            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
278        }
279    }
280
281    // load template's style.local.ini
282    // @deprecated 2013-08-03
283    $ini = $incbase.'style.local.ini';
284    if(file_exists($ini)){
285        $data = parse_ini_file($ini, true);
286
287        // stylesheets
288        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
289            $stylesheets[$mode][$incbase.$file] = $webbase;
290        }
291
292        // replacements
293        if(is_array($data['replacements'])){
294            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
295        }
296    }
297
298    // load configs's style.ini
299    $webbase = DOKU_BASE;
300    $ini = DOKU_CONF."tpl/$tpl/style.ini";
301    $incbase = dirname($ini).'/';
302    if(file_exists($ini)){
303        $data = parse_ini_file($ini, true);
304
305        // stylesheets
306        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
307            $stylesheets[$mode][$incbase.$file] = $webbase;
308        }
309
310        // replacements
311        if(is_array($data['replacements'])){
312            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
313        }
314    }
315
316    return array(
317        'stylesheets' => $stylesheets,
318        'replacements' => $replacements
319    );
320}
321
322/**
323 * Amend paths used in replacement relative urls, refer FS#2879
324 *
325 * @author Chris Smith <chris@jalakai.co.uk>
326 */
327function css_fixreplacementurls($replacements, $location) {
328    foreach($replacements as $key => $value) {
329        $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value);
330    }
331    return $replacements;
332}
333
334/**
335 * Prints classes for interwikilinks
336 *
337 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
338 * $name is the identifier given in the config. All Interwiki links get
339 * an default style with a default icon. If a special icon is available
340 * for an interwiki URL it is set in it's own class. Both classes can be
341 * overwritten in the template or userstyles.
342 *
343 * @author Andreas Gohr <andi@splitbrain.org>
344 */
345function css_interwiki(){
346
347    // default style
348    echo 'a.interwiki {';
349    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
350    echo ' padding: 1px 0px 1px 16px;';
351    echo '}';
352
353    // additional styles when icon available
354    $iwlinks = getInterwiki();
355    foreach(array_keys($iwlinks) as $iw){
356        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
357        if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
358            echo "a.iw_$class {";
359            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
360            echo '}';
361        }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
362            echo "a.iw_$class {";
363            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
364            echo '}';
365        }
366    }
367}
368
369/**
370 * Prints classes for file download links
371 *
372 * @author Andreas Gohr <andi@splitbrain.org>
373 */
374function css_filetypes(){
375
376    // default style
377    echo '.mediafile {';
378    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
379    echo ' padding-left: 18px;';
380    echo ' padding-bottom: 1px;';
381    echo '}';
382
383    // additional styles when icon available
384    // scan directory for all icons
385    $exts = array();
386    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
387        while(false !== ($file = readdir($dh))){
388            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
389                $ext = strtolower($match[1]);
390                $type = '.'.strtolower($match[2]);
391                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
392                    $exts[$ext] = $type;
393                }
394            }
395        }
396        closedir($dh);
397    }
398    foreach($exts as $ext=>$type){
399        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
400        echo ".mf_$class {";
401        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
402        echo '}';
403    }
404}
405
406/**
407 * Loads a given file and fixes relative URLs with the
408 * given location prefix
409 */
410function css_loadfile($file,$location=''){
411    $css_file = new DokuCssFile($file);
412    return $css_file->load($location);
413}
414
415/**
416 *  Helper class to abstract loading of css/less files
417 *
418 *  @author Chris Smith <chris@jalakai.co.uk>
419 */
420class DokuCssFile {
421
422    protected $filepath;             // file system path to the CSS/Less file
423    protected $location;             // base url location of the CSS/Less file
424    private   $relative_path = null;
425
426    public function __construct($file) {
427        $this->filepath = $file;
428    }
429
430    /**
431     * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
432     * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
433     * for less files.
434     *
435     * @param   string   $location   base url for this file
436     * @return  string               the CSS/Less contents of the file
437     */
438    public function load($location='') {
439        if (!@file_exists($this->filepath)) return '';
440
441        $css = io_readFile($this->filepath);
442        if (!$location) return $css;
443
444        $this->location = $location;
445
446        $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css);
447        $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css);
448
449        return $css;
450    }
451
452    /**
453     * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
454     *
455     * @return string   relative file system path
456     */
457    private function getRelativePath(){
458
459        if (is_null($this->relative_path)) {
460            $basedir = array(DOKU_INC);
461
462            // during testing, files may be found relative to a second base dir, TMP_DIR
463            if (defined('DOKU_UNITTEST')) {
464                $basedir[] = realpath(TMP_DIR);
465            }
466
467            $basedir = array_map('preg_quote_cb', $basedir);
468            $regex = '/^('.join('|',$basedir).')/';
469            $this->relative_path = preg_replace($regex, '', dirname($this->filepath));
470        }
471
472        return $this->relative_path;
473    }
474
475    /**
476     * preg_replace callback to adjust relative urls from relative to this file to relative
477     * to the appropriate dokuwiki root location as described in the code
478     *
479     * @param  array    see http://php.net/preg_replace_callback
480     * @return string   see http://php.net/preg_replace_callback
481     */
482    public function replacements($match) {
483
484        // not a relative url? - no adjustment required
485        if (preg_match('#^(/|data:|https?://)#',$match[3])) {
486            return $match[0];
487        }
488        // a less file import? - requires a file system location
489        else if (substr($match[3],-5) == '.less') {
490            if ($match[3]{0} != '/') {
491                $match[3] = $this->getRelativePath() . '/' . $match[3];
492            }
493        }
494        // everything else requires a url adjustment
495        else {
496            $match[3] = $this->location . $match[3];
497        }
498
499        return join('',array_slice($match,1));
500    }
501}
502
503/**
504 * Convert local image URLs to data URLs if the filesize is small
505 *
506 * Callback for preg_replace_callback
507 */
508function css_datauri($match){
509    global $conf;
510
511    $pre   = unslash($match[1]);
512    $base  = unslash($match[2]);
513    $url   = unslash($match[3]);
514    $ext   = unslash($match[4]);
515
516    $local = DOKU_INC.$url;
517    $size  = @filesize($local);
518    if($size && $size < $conf['cssdatauri']){
519        $data = base64_encode(file_get_contents($local));
520    }
521    if($data){
522        $url = 'data:image/'.$ext.';base64,'.$data;
523    }else{
524        $url = $base.$url;
525    }
526    return $pre.$url;
527}
528
529
530/**
531 * Returns a list of possible Plugin Styles (no existance check here)
532 *
533 * @author Andreas Gohr <andi@splitbrain.org>
534 */
535function css_pluginstyles($mediatype='screen'){
536    global $lang;
537    $list = array();
538    $plugins = plugin_list();
539    foreach ($plugins as $p){
540        $list[DOKU_PLUGIN."$p/$mediatype.css"]  = DOKU_BASE."lib/plugins/$p/";
541        $list[DOKU_PLUGIN."$p/$mediatype.less"]  = DOKU_BASE."lib/plugins/$p/";
542        // alternative for screen.css
543        if ($mediatype=='screen') {
544            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
545            $list[DOKU_PLUGIN."$p/style.less"]  = DOKU_BASE."lib/plugins/$p/";
546        }
547    }
548    return $list;
549}
550
551/**
552 * Very simple CSS optimizer
553 *
554 * @author Andreas Gohr <andi@splitbrain.org>
555 */
556function css_compress($css){
557    //strip comments through a callback
558    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
559
560    //strip (incorrect but common) one line comments
561    $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css);
562
563    // strip whitespaces
564    $css = preg_replace('![\r\n\t ]+!',' ',$css);
565    $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css);
566    $css = preg_replace('/ ?: /',':',$css);
567
568    // number compression
569    $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"
570    $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0"
571    $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0"
572    $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em"
573    $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em"
574
575    // shorten attributes (1em 1em 1em 1em -> 1em)
576    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em"
577    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em"
578
579    // shorten colors
580    $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);
581
582    return $css;
583}
584
585/**
586 * Callback for css_compress()
587 *
588 * Keeps short comments (< 5 chars) to maintain typical browser hacks
589 *
590 * @author Andreas Gohr <andi@splitbrain.org>
591 */
592function css_comment_cb($matches){
593    if(strlen($matches[2]) > 4) return '';
594    return $matches[0];
595}
596
597/**
598 * Callback for css_compress()
599 *
600 * Strips one line comments but makes sure it will not destroy url() constructs with slashes
601 *
602 * @param $matches
603 * @return string
604 */
605function css_onelinecomment_cb($matches) {
606    $line = $matches[0];
607
608    $i = 0;
609    $len = strlen($line);
610
611    while ($i< $len){
612        $nextcom = strpos($line, '//', $i);
613        $nexturl = stripos($line, 'url(', $i);
614
615        if($nextcom === false) {
616            // no more comments, we're done
617            $i = $len;
618            break;
619        }
620
621        // keep any quoted string that starts before a comment
622        $nextsqt = strpos($line, "'", $i);
623        $nextdqt = strpos($line, '"', $i);
624        if(min($nextsqt, $nextdqt) < $nextcom) {
625            $skipto = false;
626            if($nextsqt !== false && ($nextdqt === false || $nextsqt < $nextdqt)) {
627                $skipto = strpos($line, "'", $nextsqt+1) +1;
628            } else if ($nextdqt !== false) {
629                $skipto = strpos($line, '"', $nextdqt+1) +1;
630            }
631
632            if($skipto !== false) {
633                $i = $skipto;
634                continue;
635            }
636        }
637
638        if($nexturl === false || $nextcom < $nexturl) {
639            // no url anymore, strip comment and be done
640            $i = $nextcom;
641            break;
642        }
643
644        // we have an upcoming url
645        $i = strpos($line, ')', $nexturl);
646    }
647
648    return substr($line, 0, $i);
649}
650
651//Setup VIM: ex: et ts=4 :
652