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