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