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