xref: /dokuwiki/lib/exe/css.php (revision cbe37079b2519e6a79696ab6525a61498ab3c3a6)
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            $css_content .= css_loadfile($file, $location);
135        }
136        switch ($mediatype) {
137            case 'screen':
138                print NL.'@media screen { /* START screen styles */'.NL.$css_content.NL.'} /* /@media END screen styles */'.NL;
139                break;
140            case 'print':
141                print NL.'@media print { /* START print styles */'.NL.$css_content.NL.'} /* /@media END print styles */'.NL;
142                break;
143            case 'all':
144            case 'feed':
145            default:
146                print NL.'/* START rest styles */ '.NL.$css_content.NL.'/* END rest styles */'.NL;
147                break;
148        }
149    }
150    // end output buffering and get contents
151    $css = ob_get_contents();
152    ob_end_clean();
153
154    // apply style replacements
155    $css = css_applystyle($css,$tplinc);
156
157    print $css;
158
159
160    // parse LESS
161    $less = new lessc();
162    $css = $less->compile($css);
163
164    // place all remaining @import statements at the top of the file
165    $css = css_moveimports($css);
166
167    // compress whitespace and comments
168    if($conf['compress']){
169        $css = css_compress($css);
170    }
171
172    // embed small images right into the stylesheet
173    if($conf['cssdatauri']){
174        $base = preg_quote(DOKU_BASE,'#');
175        $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css);
176    }
177
178    http_cached_finish($cache->cache, $css);
179}
180
181/**
182 * Does placeholder replacements in the style according to
183 * the ones defined in a templates style.ini file
184 *
185 * This also adds the ini defined placeholders as less variables
186 * (sans the surrounding __ and with a ini_ prefix)
187 *
188 * @author Andreas Gohr <andi@splitbrain.org>
189 */
190function css_applystyle($css,$tplinc){
191    $styleini = css_styleini($tplinc);
192
193    if($styleini){
194        // we convert ini replacements to LESS variable names
195        // and build a list of variable: value; pairs
196        $less = '';
197        foreach($styleini['replacements'] as $key => $value){
198            $lkey = trim($key, '_');
199            $lkey = '@ini_'.$lkey;
200            $less .= "$lkey: $value;\n";
201
202            $styleini['replacements'][$key] = $lkey;
203        }
204
205        // we now replace all old ini replacements with LESS variables
206        $css = strtr($css, $styleini['replacements']);
207
208        // now prepend the list of LESS variables as the very first thing
209        $css = $less.$css;
210    }
211    return $css;
212}
213
214/**
215 * Get contents of merged style.ini and style.local.ini as an array.
216 *
217 * @author Anika Henke <anika@selfthinker.org>
218 */
219function css_styleini($tplinc) {
220    $styleini = array();
221
222    foreach (array($tplinc.'style.ini', $tplinc.'style.local.ini') as $ini) {
223        $tmp = (@file_exists($ini)) ? parse_ini_file($ini, true) : array();
224
225        foreach($tmp as $key => $value) {
226            if(array_key_exists($key, $styleini) && is_array($value)) {
227                $styleini[$key] = array_merge($styleini[$key], $tmp[$key]);
228            } else {
229                $styleini[$key] = $value;
230            }
231        }
232    }
233    return $styleini;
234}
235
236/**
237 * Prints classes for interwikilinks
238 *
239 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
240 * $name is the identifier given in the config. All Interwiki links get
241 * an default style with a default icon. If a special icon is available
242 * for an interwiki URL it is set in it's own class. Both classes can be
243 * overwritten in the template or userstyles.
244 *
245 * @author Andreas Gohr <andi@splitbrain.org>
246 */
247function css_interwiki(){
248
249    // default style
250    echo 'a.interwiki {';
251    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
252    echo ' padding: 1px 0px 1px 16px;';
253    echo '}';
254
255    // additional styles when icon available
256    $iwlinks = getInterwiki();
257    foreach(array_keys($iwlinks) as $iw){
258        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
259        if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
260            echo "a.iw_$class {";
261            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
262            echo '}';
263        }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
264            echo "a.iw_$class {";
265            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
266            echo '}';
267        }
268    }
269}
270
271/**
272 * Prints classes for file download links
273 *
274 * @author Andreas Gohr <andi@splitbrain.org>
275 */
276function css_filetypes(){
277
278    // default style
279    echo '.mediafile {';
280    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
281    echo ' padding-left: 18px;';
282    echo ' padding-bottom: 1px;';
283    echo '}';
284
285    // additional styles when icon available
286    // scan directory for all icons
287    $exts = array();
288    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
289        while(false !== ($file = readdir($dh))){
290            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
291                $ext = strtolower($match[1]);
292                $type = '.'.strtolower($match[2]);
293                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
294                    $exts[$ext] = $type;
295                }
296            }
297        }
298        closedir($dh);
299    }
300    foreach($exts as $ext=>$type){
301        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
302        echo ".mf_$class {";
303        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
304        echo '}';
305    }
306}
307
308/**
309 * Loads a given file and fixes relative URLs with the
310 * given location prefix
311 */
312function css_loadfile($file,$location=''){
313    if(!@file_exists($file)) return '';
314    $css = io_readFile($file);
315    if(!$location) return $css;
316
317    $css = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$css);
318    $css = preg_replace('#(@import\s+[\'"])(?!/|data:|http://|https://)#', '\\1'.$location, $css);
319
320    return $css;
321}
322
323/**
324 * Converte local image URLs to data URLs if the filesize is small
325 *
326 * Callback for preg_replace_callback
327 */
328function css_datauri($match){
329    global $conf;
330
331    $pre   = unslash($match[1]);
332    $base  = unslash($match[2]);
333    $url   = unslash($match[3]);
334    $ext   = unslash($match[4]);
335
336    $local = DOKU_INC.$url;
337    $size  = @filesize($local);
338    if($size && $size < $conf['cssdatauri']){
339        $data = base64_encode(file_get_contents($local));
340    }
341    if($data){
342        $url = 'data:image/'.$ext.';base64,'.$data;
343    }else{
344        $url = $base.$url;
345    }
346    return $pre.$url;
347}
348
349
350/**
351 * Returns a list of possible Plugin Styles (no existance check here)
352 *
353 * @author Andreas Gohr <andi@splitbrain.org>
354 */
355function css_pluginstyles($mediatype='screen'){
356    global $lang;
357    $list = array();
358    $plugins = plugin_list();
359    foreach ($plugins as $p){
360        $list[DOKU_PLUGIN."$p/$mediatype.css"]  = DOKU_BASE."lib/plugins/$p/";
361        $list[DOKU_PLUGIN."$p/$mediatype.less"]  = DOKU_BASE."lib/plugins/$p/";
362        // alternative for screen.css
363        if ($mediatype=='screen') {
364            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
365            $list[DOKU_PLUGIN."$p/style.less"]  = DOKU_BASE."lib/plugins/$p/";
366        }
367        // @deprecated 2012-04-09: rtl will cease to be a mode of its own,
368        //     please use "[dir=rtl]" in any css file in all, screen or print mode instead
369        if($lang['direction'] == 'rtl'){
370            $list[DOKU_PLUGIN."$p/rtl.css"] = DOKU_BASE."lib/plugins/$p/";
371            $list[DOKU_PLUGIN."$p/rtl.less"] = DOKU_BASE."lib/plugins/$p/";
372        }
373    }
374    return $list;
375}
376
377/**
378 * Move all @import statements in a combined stylesheet to the top so they
379 * aren't ignored by the browser.
380 *
381 * @author Gabriel Birke <birke@d-scribe.de>
382 */
383function css_moveimports($css)
384{
385    if(!preg_match_all('/@import\s+(?:url\([^)]+\)|"[^"]+")\s*[^;]*;\s*/', $css, $matches, PREG_OFFSET_CAPTURE)) {
386        return $css;
387    }
388    $newCss  = "";
389    $imports = "";
390    $offset  = 0;
391    foreach($matches[0] as $match) {
392        $newCss  .= substr($css, $offset, $match[1] - $offset);
393        $imports .= $match[0];
394        $offset   = $match[1] + strlen($match[0]);
395    }
396    $newCss .= substr($css, $offset);
397    return $imports.$newCss;
398}
399
400/**
401 * Very simple CSS optimizer
402 *
403 * @author Andreas Gohr <andi@splitbrain.org>
404 */
405function css_compress($css){
406    //strip comments through a callback
407    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
408
409    //strip (incorrect but common) one line comments
410    $css = preg_replace('/(?<!:)\/\/.*$/m','',$css);
411
412    // strip whitespaces
413    $css = preg_replace('![\r\n\t ]+!',' ',$css);
414    $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css);
415    $css = preg_replace('/ ?: /',':',$css);
416
417    // shorten colors
418    $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);
419
420    return $css;
421}
422
423/**
424 * Callback for css_compress()
425 *
426 * Keeps short comments (< 5 chars) to maintain typical browser hacks
427 *
428 * @author Andreas Gohr <andi@splitbrain.org>
429 */
430function css_comment_cb($matches){
431    if(strlen($matches[2]) > 4) return '';
432    return $matches[0];
433}
434
435//Setup VIM: ex: et ts=4 :
436