xref: /dokuwiki/lib/exe/css.php (revision ab9346edc1621443d00551060b6db2d544ad3a71)
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    try {
177        return $less->compile($css);
178    } catch(Exception $e) {
179        // get exception message
180        $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage());
181
182        // try to use line number to find affected file
183        if(preg_match('/line: (\d+)$/', $msg, $m)){
184            $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber
185            $lno = $m[1];
186
187            // walk upwards to last include
188            $lines = explode("\n", $css);
189            for($i=$lno-1; $i>=0; $i--){
190                if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){
191                    // we found it, add info to message
192                    $msg .= ' in '.$m[2].' at line '.($lno-$i);
193                    break;
194                }
195            }
196        }
197
198        // something went wrong
199        $error = 'A fatal error occured during compilation of the CSS files. '.
200            'If you recently installed a new plugin or template it '.
201            'might be broken and you should try disabling it again. ['.$msg.']';
202
203        echo ".dokuwiki:before {
204            content: '$error';
205            background-color: red;
206            display: block;
207            background-color: #fcc;
208            border-color: #ebb;
209            color: #000;
210            padding: 0.5em;
211        }";
212
213        exit;
214    }
215}
216
217/**
218 * Does placeholder replacements in the style according to
219 * the ones defined in a templates style.ini file
220 *
221 * This also adds the ini defined placeholders as less variables
222 * (sans the surrounding __ and with a ini_ prefix)
223 *
224 * @author Andreas Gohr <andi@splitbrain.org>
225 */
226function css_applystyle($css, $replacements) {
227    // we convert ini replacements to LESS variable names
228    // and build a list of variable: value; pairs
229    $less = '';
230    foreach((array) $replacements as $key => $value) {
231        $lkey = trim($key, '_');
232        $lkey = '@ini_'.$lkey;
233        $less .= "$lkey: $value;\n";
234
235        $replacements[$key] = $lkey;
236    }
237
238    // we now replace all old ini replacements with LESS variables
239    $css = strtr($css, $replacements);
240
241    // now prepend the list of LESS variables as the very first thing
242    $css = $less.$css;
243    return $css;
244}
245
246/**
247 * Load style ini contents
248 *
249 * Loads and merges style.ini files from template and config and prepares
250 * the stylesheet modes
251 *
252 * @author Andreas Gohr <andi@splitbrain.org>
253 * @param string $tpl the used template
254 * @return array with keys 'stylesheets' and 'replacements'
255 */
256function css_styleini($tpl) {
257    $stylesheets = array(); // mode, file => base
258    $replacements = array(); // placeholder => value
259
260    // load template's style.ini
261    $incbase = tpl_incdir($tpl);
262    $webbase = tpl_basedir($tpl);
263    $ini = $incbase.'style.ini';
264    if(file_exists($ini)){
265        $data = parse_ini_file($ini, true);
266
267        // stylesheets
268        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
269            $stylesheets[$mode][$incbase.$file] = $webbase;
270        }
271
272        // replacements
273        if(is_array($data['replacements'])){
274            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
275        }
276    }
277
278    // load template's style.local.ini
279    // @deprecated 2013-08-03
280    $ini = $incbase.'style.local.ini';
281    if(file_exists($ini)){
282        $data = parse_ini_file($ini, true);
283
284        // stylesheets
285        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
286            $stylesheets[$mode][$incbase.$file] = $webbase;
287        }
288
289        // replacements
290        if(is_array($data['replacements'])){
291            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
292        }
293    }
294
295    // load configs's style.ini
296    $webbase = DOKU_BASE;
297    $ini = DOKU_CONF."tpl/$tpl/style.ini";
298    $incbase = dirname($ini).'/';
299    if(file_exists($ini)){
300        $data = parse_ini_file($ini, true);
301
302        // stylesheets
303        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
304            $stylesheets[$mode][$incbase.$file] = $webbase;
305        }
306
307        // replacements
308        if(is_array($data['replacements'])){
309            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
310        }
311    }
312
313    return array(
314        'stylesheets' => $stylesheets,
315        'replacements' => $replacements
316    );
317}
318
319function css_fixreplacementurls($replacements, $location) {
320    foreach($replacements as $key => $value) {
321        $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value);
322    }
323    return $replacements;
324}
325
326/**
327 * Prints classes for interwikilinks
328 *
329 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
330 * $name is the identifier given in the config. All Interwiki links get
331 * an default style with a default icon. If a special icon is available
332 * for an interwiki URL it is set in it's own class. Both classes can be
333 * overwritten in the template or userstyles.
334 *
335 * @author Andreas Gohr <andi@splitbrain.org>
336 */
337function css_interwiki(){
338
339    // default style
340    echo 'a.interwiki {';
341    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
342    echo ' padding: 1px 0px 1px 16px;';
343    echo '}';
344
345    // additional styles when icon available
346    $iwlinks = getInterwiki();
347    foreach(array_keys($iwlinks) as $iw){
348        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
349        if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
350            echo "a.iw_$class {";
351            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
352            echo '}';
353        }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
354            echo "a.iw_$class {";
355            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
356            echo '}';
357        }
358    }
359}
360
361/**
362 * Prints classes for file download links
363 *
364 * @author Andreas Gohr <andi@splitbrain.org>
365 */
366function css_filetypes(){
367
368    // default style
369    echo '.mediafile {';
370    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
371    echo ' padding-left: 18px;';
372    echo ' padding-bottom: 1px;';
373    echo '}';
374
375    // additional styles when icon available
376    // scan directory for all icons
377    $exts = array();
378    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
379        while(false !== ($file = readdir($dh))){
380            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
381                $ext = strtolower($match[1]);
382                $type = '.'.strtolower($match[2]);
383                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
384                    $exts[$ext] = $type;
385                }
386            }
387        }
388        closedir($dh);
389    }
390    foreach($exts as $ext=>$type){
391        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
392        echo ".mf_$class {";
393        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
394        echo '}';
395    }
396}
397
398/**
399 * Loads a given file and fixes relative URLs with the
400 * given location prefix
401 */
402function css_loadfile($file,$location=''){
403    if(!@file_exists($file)) return '';
404    $css = io_readFile($file);
405    if(!$location) return $css;
406
407    $css = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$css);
408    $css = preg_replace('#(@import\s+[\'"])(?!/|data:|http://|https://)#', '\\1'.$location, $css);
409
410    return $css;
411}
412
413/**
414 * Converte local image URLs to data URLs if the filesize is small
415 *
416 * Callback for preg_replace_callback
417 */
418function css_datauri($match){
419    global $conf;
420
421    $pre   = unslash($match[1]);
422    $base  = unslash($match[2]);
423    $url   = unslash($match[3]);
424    $ext   = unslash($match[4]);
425
426    $local = DOKU_INC.$url;
427    $size  = @filesize($local);
428    if($size && $size < $conf['cssdatauri']){
429        $data = base64_encode(file_get_contents($local));
430    }
431    if($data){
432        $url = 'data:image/'.$ext.';base64,'.$data;
433    }else{
434        $url = $base.$url;
435    }
436    return $pre.$url;
437}
438
439
440/**
441 * Returns a list of possible Plugin Styles (no existance check here)
442 *
443 * @author Andreas Gohr <andi@splitbrain.org>
444 */
445function css_pluginstyles($mediatype='screen'){
446    global $lang;
447    $list = array();
448    $plugins = plugin_list();
449    foreach ($plugins as $p){
450        $list[DOKU_PLUGIN."$p/$mediatype.css"]  = DOKU_BASE."lib/plugins/$p/";
451        $list[DOKU_PLUGIN."$p/$mediatype.less"]  = DOKU_BASE."lib/plugins/$p/";
452        // alternative for screen.css
453        if ($mediatype=='screen') {
454            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
455            $list[DOKU_PLUGIN."$p/style.less"]  = DOKU_BASE."lib/plugins/$p/";
456        }
457        // @deprecated 2012-04-09: rtl will cease to be a mode of its own,
458        //     please use "[dir=rtl]" in any css file in all, screen or print mode instead
459        if($lang['direction'] == 'rtl'){
460            $list[DOKU_PLUGIN."$p/rtl.css"] = DOKU_BASE."lib/plugins/$p/";
461        }
462    }
463    return $list;
464}
465
466/**
467 * Very simple CSS optimizer
468 *
469 * @author Andreas Gohr <andi@splitbrain.org>
470 */
471function css_compress($css){
472    //strip comments through a callback
473    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
474
475    //strip (incorrect but common) one line comments
476    $css = preg_replace('/(?<!:)\/\/.*$/m','',$css);
477
478    // strip whitespaces
479    $css = preg_replace('![\r\n\t ]+!',' ',$css);
480    $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css);
481    $css = preg_replace('/ ?: /',':',$css);
482
483    // number compression
484    $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"
485    $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0"
486    $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0"
487    $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em"
488    $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em"
489
490    // shorten attributes (1em 1em 1em 1em -> 1em)
491    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em"
492    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em"
493
494    // shorten colors
495    $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);
496
497    return $css;
498}
499
500/**
501 * Callback for css_compress()
502 *
503 * Keeps short comments (< 5 chars) to maintain typical browser hacks
504 *
505 * @author Andreas Gohr <andi@splitbrain.org>
506 */
507function css_comment_cb($matches){
508    if(strlen($matches[2]) > 4) return '';
509    return $matches[0];
510}
511
512//Setup VIM: ex: et ts=4 :
513