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