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