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