xref: /dokuwiki/lib/exe/css.php (revision f0a15b090f12df8667df748cdc0ba2bc8c6fca9d)
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'].$INPUT->int('preview').DOKU_BASE.$tpl.$type,'.css');
49
50    // load styl.ini
51    $styleini = css_styleini($tpl, $INPUT->bool('preview'));
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[] = DOKU_CONF."tpl/$tpl/style.ini";
63    $cache_files[] = __FILE__;
64    if($INPUT->bool('preview')) $cache_files[] = $conf['cachedir'].'/preview.ini';
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 * @param bool   $preview load preview replacements
265 * @return array with keys 'stylesheets' and 'replacements'
266 */
267function css_styleini($tpl, $preview=false) {
268    global $conf;
269
270    $stylesheets = array(); // mode, file => base
271    $replacements = array(); // placeholder => value
272
273    // load template's style.ini
274    $incbase = tpl_incdir($tpl);
275    $webbase = tpl_basedir($tpl);
276    $ini = $incbase.'style.ini';
277    if(file_exists($ini)){
278        $data = parse_ini_file($ini, true);
279
280        // stylesheets
281        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
282            $stylesheets[$mode][$incbase.$file] = $webbase;
283        }
284
285        // replacements
286        if(is_array($data['replacements'])){
287            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
288        }
289    }
290
291    // load configs's style.ini
292    $webbase = DOKU_BASE;
293    $ini = DOKU_CONF."tpl/$tpl/style.ini";
294    $incbase = dirname($ini).'/';
295    if(file_exists($ini)){
296        $data = parse_ini_file($ini, true);
297
298        // stylesheets
299        if(isset($data['stylesheets']) && is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
300            $stylesheets[$mode][$incbase.$file] = $webbase;
301        }
302
303        // replacements
304        if(isset($data['replacements']) && is_array($data['replacements'])){
305            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
306        }
307    }
308
309    // allow replacement overwrites in preview mode
310    if($preview) {
311        $webbase = DOKU_BASE;
312        $ini     = $conf['cachedir'].'/preview.ini';
313        if(file_exists($ini)) {
314            $data = parse_ini_file($ini, true);
315            // replacements
316            if(is_array($data['replacements'])) {
317                $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'], $webbase));
318            }
319        }
320    }
321
322    return array(
323        'stylesheets' => $stylesheets,
324        'replacements' => $replacements
325    );
326}
327
328/**
329 * Amend paths used in replacement relative urls, refer FS#2879
330 *
331 * @author Chris Smith <chris@jalakai.co.uk>
332 *
333 * @param array $replacements with key-value pairs
334 * @param string $location
335 * @return array
336 */
337function css_fixreplacementurls($replacements, $location) {
338    foreach($replacements as $key => $value) {
339        $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value);
340    }
341    return $replacements;
342}
343
344/**
345 * Prints classes for interwikilinks
346 *
347 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
348 * $name is the identifier given in the config. All Interwiki links get
349 * an default style with a default icon. If a special icon is available
350 * for an interwiki URL it is set in it's own class. Both classes can be
351 * overwritten in the template or userstyles.
352 *
353 * @author Andreas Gohr <andi@splitbrain.org>
354 */
355function css_interwiki(){
356
357    // default style
358    echo 'a.interwiki {';
359    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
360    echo ' padding: 1px 0px 1px 16px;';
361    echo '}';
362
363    // additional styles when icon available
364    $iwlinks = getInterwiki();
365    foreach(array_keys($iwlinks) as $iw){
366        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
367        if(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
368            echo "a.iw_$class {";
369            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
370            echo '}';
371        }elseif(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
372            echo "a.iw_$class {";
373            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
374            echo '}';
375        }
376    }
377}
378
379/**
380 * Prints classes for file download links
381 *
382 * @author Andreas Gohr <andi@splitbrain.org>
383 */
384function css_filetypes(){
385
386    // default style
387    echo '.mediafile {';
388    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
389    echo ' padding-left: 18px;';
390    echo ' padding-bottom: 1px;';
391    echo '}';
392
393    // additional styles when icon available
394    // scan directory for all icons
395    $exts = array();
396    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
397        while(false !== ($file = readdir($dh))){
398            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
399                $ext = strtolower($match[1]);
400                $type = '.'.strtolower($match[2]);
401                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
402                    $exts[$ext] = $type;
403                }
404            }
405        }
406        closedir($dh);
407    }
408    foreach($exts as $ext=>$type){
409        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
410        echo ".mf_$class {";
411        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
412        echo '}';
413    }
414}
415
416/**
417 * Loads a given file and fixes relative URLs with the
418 * given location prefix
419 *
420 * @param string $file file system path
421 * @param string $location
422 * @return string
423 */
424function css_loadfile($file,$location=''){
425    $css_file = new DokuCssFile($file);
426    return $css_file->load($location);
427}
428
429/**
430 *  Helper class to abstract loading of css/less files
431 *
432 *  @author Chris Smith <chris@jalakai.co.uk>
433 */
434class DokuCssFile {
435
436    protected $filepath;             // file system path to the CSS/Less file
437    protected $location;             // base url location of the CSS/Less file
438    protected $relative_path = null;
439
440    public function __construct($file) {
441        $this->filepath = $file;
442    }
443
444    /**
445     * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
446     * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
447     * for less files.
448     *
449     * @param   string   $location   base url for this file
450     * @return  string               the CSS/Less contents of the file
451     */
452    public function load($location='') {
453        if (!file_exists($this->filepath)) return '';
454
455        $css = io_readFile($this->filepath);
456        if (!$location) return $css;
457
458        $this->location = $location;
459
460        $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css);
461        $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css);
462
463        return $css;
464    }
465
466    /**
467     * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
468     *
469     * @return string   relative file system path
470     */
471    protected function getRelativePath(){
472
473        if (is_null($this->relative_path)) {
474            $basedir = array(DOKU_INC);
475
476            // during testing, files may be found relative to a second base dir, TMP_DIR
477            if (defined('DOKU_UNITTEST')) {
478                $basedir[] = realpath(TMP_DIR);
479            }
480
481            $basedir = array_map('preg_quote_cb', $basedir);
482            $regex = '/^('.join('|',$basedir).')/';
483            $this->relative_path = preg_replace($regex, '', dirname($this->filepath));
484        }
485
486        return $this->relative_path;
487    }
488
489    /**
490     * preg_replace callback to adjust relative urls from relative to this file to relative
491     * to the appropriate dokuwiki root location as described in the code
492     *
493     * @param  array    see http://php.net/preg_replace_callback
494     * @return string   see http://php.net/preg_replace_callback
495     */
496    public function replacements($match) {
497
498        // not a relative url? - no adjustment required
499        if (preg_match('#^(/|data:|https?://)#',$match[3])) {
500            return $match[0];
501        }
502        // a less file import? - requires a file system location
503        else if (substr($match[3],-5) == '.less') {
504            if ($match[3]{0} != '/') {
505                $match[3] = $this->getRelativePath() . '/' . $match[3];
506            }
507        }
508        // everything else requires a url adjustment
509        else {
510            $match[3] = $this->location . $match[3];
511        }
512
513        return join('',array_slice($match,1));
514    }
515}
516
517/**
518 * Convert local image URLs to data URLs if the filesize is small
519 *
520 * Callback for preg_replace_callback
521 *
522 * @param array $match
523 * @return string
524 */
525function css_datauri($match){
526    global $conf;
527
528    $pre   = unslash($match[1]);
529    $base  = unslash($match[2]);
530    $url   = unslash($match[3]);
531    $ext   = unslash($match[4]);
532
533    $local = DOKU_INC.$url;
534    $size  = @filesize($local);
535    if($size && $size < $conf['cssdatauri']){
536        $data = base64_encode(file_get_contents($local));
537    }
538    if($data){
539        $url = 'data:image/'.$ext.';base64,'.$data;
540    }else{
541        $url = $base.$url;
542    }
543    return $pre.$url;
544}
545
546
547/**
548 * Returns a list of possible Plugin Styles (no existance check here)
549 *
550 * @author Andreas Gohr <andi@splitbrain.org>
551 *
552 * @param string $mediatype
553 * @return array
554 */
555function css_pluginstyles($mediatype='screen'){
556    $list = array();
557    $plugins = plugin_list();
558    foreach ($plugins as $p){
559        $list[DOKU_PLUGIN."$p/$mediatype.css"]  = DOKU_BASE."lib/plugins/$p/";
560        $list[DOKU_PLUGIN."$p/$mediatype.less"]  = DOKU_BASE."lib/plugins/$p/";
561        // alternative for screen.css
562        if ($mediatype=='screen') {
563            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
564            $list[DOKU_PLUGIN."$p/style.less"]  = DOKU_BASE."lib/plugins/$p/";
565        }
566    }
567    return $list;
568}
569
570/**
571 * Very simple CSS optimizer
572 *
573 * @author Andreas Gohr <andi@splitbrain.org>
574 *
575 * @param string $css
576 * @return string
577 */
578function css_compress($css){
579    //strip comments through a callback
580    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
581
582    //strip (incorrect but common) one line comments
583    $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css);
584
585    // strip whitespaces
586    $css = preg_replace('![\r\n\t ]+!',' ',$css);
587    $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css);
588    $css = preg_replace('/ ?: /',':',$css);
589
590    // number compression
591    $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"
592    $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0"
593    $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0"
594    $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em"
595    $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em"
596
597    // shorten attributes (1em 1em 1em 1em -> 1em)
598    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em"
599    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em"
600
601    // shorten colors
602    $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);
603
604    return $css;
605}
606
607/**
608 * Callback for css_compress()
609 *
610 * Keeps short comments (< 5 chars) to maintain typical browser hacks
611 *
612 * @author Andreas Gohr <andi@splitbrain.org>
613 *
614 * @param array $matches
615 * @return string
616 */
617function css_comment_cb($matches){
618    if(strlen($matches[2]) > 4) return '';
619    return $matches[0];
620}
621
622/**
623 * Callback for css_compress()
624 *
625 * Strips one line comments but makes sure it will not destroy url() constructs with slashes
626 *
627 * @param array $matches
628 * @return string
629 */
630function css_onelinecomment_cb($matches) {
631    $line = $matches[0];
632
633    $i = 0;
634    $len = strlen($line);
635
636    while ($i< $len){
637        $nextcom = strpos($line, '//', $i);
638        $nexturl = stripos($line, 'url(', $i);
639
640        if($nextcom === false) {
641            // no more comments, we're done
642            $i = $len;
643            break;
644        }
645
646        // keep any quoted string that starts before a comment
647        $nextsqt = strpos($line, "'", $i);
648        $nextdqt = strpos($line, '"', $i);
649        if(min($nextsqt, $nextdqt) < $nextcom) {
650            $skipto = false;
651            if($nextsqt !== false && ($nextdqt === false || $nextsqt < $nextdqt)) {
652                $skipto = strpos($line, "'", $nextsqt+1) +1;
653            } else if ($nextdqt !== false) {
654                $skipto = strpos($line, '"', $nextdqt+1) +1;
655            }
656
657            if($skipto !== false) {
658                $i = $skipto;
659                continue;
660            }
661        }
662
663        if($nexturl === false || $nextcom < $nexturl) {
664            // no url anymore, strip comment and be done
665            $i = $nextcom;
666            break;
667        }
668
669        // we have an upcoming url
670        $i = strpos($line, ')', $nexturl);
671    }
672
673    return substr($line, 0, $i);
674}
675
676//Setup VIM: ex: et ts=4 :
677