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