xref: /dokuwiki/lib/exe/css.php (revision 0e6f9f08b1c948f45d1867346a4502021afa55bc)
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        $ini = parse_ini_file($styleini, true);
62        foreach($ini['stylesheets'] as $file => $mode) {
63            $tplstyles[$mode][$tplinc.$file] = $tpldir;
64        }
65    }
66
67    // if old 'default' userstyle setting exists, make it 'screen' userstyle for backwards compatibility
68    if (isset($config_cascade['userstyle']['default'])) {
69        $config_cascade['userstyle']['screen'] = $config_cascade['userstyle']['default'];
70    }
71
72    // Array of needed files and their web locations, the latter ones
73    // are needed to fix relative paths in the stylesheets
74    $files = array();
75
76    $cache_files = getConfigFiles('main');
77    if ($styleini)
78        $cache_files[] = $styleini;
79    $cache_files[] = __FILE__;
80
81    foreach($mediatypes as $mediatype) {
82        $files[$mediatype] = array();
83        // load core styles
84        $files[$mediatype][DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/';
85        // load jQuery-UI theme
86        if ($mediatype == 'screen') {
87            $files[$mediatype][DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/';
88        }
89        // load plugin styles
90        $files[$mediatype] = array_merge($files[$mediatype], css_pluginstyles($mediatype));
91        // load template styles
92        if (isset($tplstyles[$mediatype])) {
93            $files[$mediatype] = array_merge($files[$mediatype], $tplstyles[$mediatype]);
94        }
95        // load user styles
96        if(isset($config_cascade['userstyle'][$mediatype])){
97            $files[$mediatype][$config_cascade['userstyle'][$mediatype]] = DOKU_BASE;
98        }
99        // load rtl styles
100        // note: this adds the rtl styles only to the 'screen' media type
101        // @deprecated 2012-04-09: rtl will cease to be a mode of its own,
102        //     please use "[dir=rtl]" in any css file in all, screen or print mode instead
103        if ($mediatype=='screen') {
104            if($lang['direction'] == 'rtl'){
105                if (isset($tplstyles['rtl'])) $files[$mediatype] = array_merge($files[$mediatype], $tplstyles['rtl']);
106                if (isset($config_cascade['userstyle']['rtl'])) $files[$mediatype][$config_cascade['userstyle']['rtl']] = DOKU_BASE;
107            }
108        }
109
110        $cache_files = array_merge($cache_files, array_keys($files[$mediatype]));
111    }
112
113    // check cache age & handle conditional request
114    // This may exit if a cache can be used
115    http_cached($cache->cache,
116                $cache->useCache(array('files' => $cache_files)));
117
118    // start output buffering
119    ob_start();
120
121    // build the stylesheet
122    foreach ($mediatypes as $mediatype) {
123
124        // print the default classes for interwiki links and file downloads
125        if ($mediatype == 'screen') {
126            css_interwiki();
127            css_filetypes();
128        }
129
130        // load files
131        $css_content = '';
132        foreach($files[$mediatype] as $file => $location){
133            $css_content .= css_loadfile($file, $location);
134        }
135        switch ($mediatype) {
136            case 'screen':
137                print NL.'@media screen { /* START screen styles */'.NL.$css_content.NL.'} /* /@media END screen styles */'.NL;
138                break;
139            case 'print':
140                print NL.'@media print { /* START print styles */'.NL.$css_content.NL.'} /* /@media END print styles */'.NL;
141                break;
142            case 'all':
143            case 'feed':
144            default:
145                print NL.'/* START rest styles */ '.NL.$css_content.NL.'/* END rest styles */'.NL;
146                break;
147        }
148    }
149    // end output buffering and get contents
150    $css = ob_get_contents();
151    ob_end_clean();
152
153    // apply style replacements
154    $css = css_applystyle($css,$tplinc);
155
156    // place all @import statements at the top of the file
157    $css = css_moveimports($css);
158
159    // compress whitespace and comments
160    if($conf['compress']){
161        $css = css_compress($css);
162    }
163
164    // embed small images right into the stylesheet
165    if($conf['cssdatauri']){
166        $base = preg_quote(DOKU_BASE,'#');
167        $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css);
168    }
169
170    http_cached_finish($cache->cache, $css);
171}
172
173/**
174 * Does placeholder replacements in the style according to
175 * the ones defined in a templates style.ini file
176 *
177 * @author Andreas Gohr <andi@splitbrain.org>
178 */
179function css_applystyle($css,$tplinc){
180    $styleini = css_styleini($tplinc);
181
182    if($styleini){
183        $ini = parse_ini_file($styleini,true);
184        $css = strtr($css,$ini['replacements']);
185    }
186    return $css;
187}
188
189/**
190 * If either exist, get the template's style.local.ini or style.ini file.
191 */
192function css_styleini($tplinc) {
193    if(@file_exists($tplinc.'style.local.ini'))
194        return $tplinc.'style.local.ini';
195    if(@file_exists($tplinc.'style.ini'))
196        return $tplinc.'style.ini';
197    return '';
198}
199
200/**
201 * Prints classes for interwikilinks
202 *
203 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
204 * $name is the identifier given in the config. All Interwiki links get
205 * an default style with a default icon. If a special icon is available
206 * for an interwiki URL it is set in it's own class. Both classes can be
207 * overwritten in the template or userstyles.
208 *
209 * @author Andreas Gohr <andi@splitbrain.org>
210 */
211function css_interwiki(){
212
213    // default style
214    echo 'a.interwiki {';
215    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
216    echo ' padding: 1px 0px 1px 16px;';
217    echo '}';
218
219    // additional styles when icon available
220    $iwlinks = getInterwiki();
221    foreach(array_keys($iwlinks) as $iw){
222        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
223        if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
224            echo "a.iw_$class {";
225            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
226            echo '}';
227        }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
228            echo "a.iw_$class {";
229            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
230            echo '}';
231        }
232    }
233}
234
235/**
236 * Prints classes for file download links
237 *
238 * @author Andreas Gohr <andi@splitbrain.org>
239 */
240function css_filetypes(){
241
242    // default style
243    echo '.mediafile {';
244    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
245    echo ' padding-left: 18px;';
246    echo ' padding-bottom: 1px;';
247    echo '}';
248
249    // additional styles when icon available
250    // scan directory for all icons
251    $exts = array();
252    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
253        while(false !== ($file = readdir($dh))){
254            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
255                $ext = strtolower($match[1]);
256                $type = '.'.strtolower($match[2]);
257                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
258                    $exts[$ext] = $type;
259                }
260            }
261        }
262        closedir($dh);
263    }
264    foreach($exts as $ext=>$type){
265        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
266        echo ".mf_$class {";
267        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
268        echo '}';
269    }
270}
271
272/**
273 * Loads a given file and fixes relative URLs with the
274 * given location prefix
275 */
276function css_loadfile($file,$location=''){
277    if(!@file_exists($file)) return '';
278    $css = io_readFile($file);
279    if(!$location) return $css;
280
281    $css = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$css);
282    $css = preg_replace('#(@import\s+[\'"])(?!/|data:|http://|https://)#', '\\1'.$location, $css);
283
284    return $css;
285}
286
287/**
288 * Converte local image URLs to data URLs if the filesize is small
289 *
290 * Callback for preg_replace_callback
291 */
292function css_datauri($match){
293    global $conf;
294
295    $pre   = unslash($match[1]);
296    $base  = unslash($match[2]);
297    $url   = unslash($match[3]);
298    $ext   = unslash($match[4]);
299
300    $local = DOKU_INC.$url;
301    $size  = @filesize($local);
302    if($size && $size < $conf['cssdatauri']){
303        $data = base64_encode(file_get_contents($local));
304    }
305    if($data){
306        $url = 'data:image/'.$ext.';base64,'.$data;
307    }else{
308        $url = $base.$url;
309    }
310    return $pre.$url;
311}
312
313
314/**
315 * Returns a list of possible Plugin Styles (no existance check here)
316 *
317 * @author Andreas Gohr <andi@splitbrain.org>
318 */
319function css_pluginstyles($mediatype='screen'){
320    global $lang;
321    $list = array();
322    $plugins = plugin_list();
323    foreach ($plugins as $p){
324        $list[DOKU_PLUGIN."$p/$mediatype.css"]  = DOKU_BASE."lib/plugins/$p/";
325        // alternative for screen.css
326        if ($mediatype=='screen') {
327            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
328        }
329        // @deprecated 2012-04-09: rtl will cease to be a mode of its own,
330        //     please use "[dir=rtl]" in any css file in all, screen or print mode instead
331        if($lang['direction'] == 'rtl'){
332            $list[DOKU_PLUGIN."$p/rtl.css"] = DOKU_BASE."lib/plugins/$p/";
333        }
334    }
335    return $list;
336}
337
338/**
339 * Move all @import statements in a combined stylesheet to the top so they
340 * aren't ignored by the browser.
341 *
342 * @author Gabriel Birke <birke@d-scribe.de>
343 */
344function css_moveimports($css)
345{
346    if(!preg_match_all('/@import\s+(?:url\([^)]+\)|"[^"]+")\s*[^;]*;\s*/', $css, $matches, PREG_OFFSET_CAPTURE)) {
347        return $css;
348    }
349    $newCss  = "";
350    $imports = "";
351    $offset  = 0;
352    foreach($matches[0] as $match) {
353        $newCss  .= substr($css, $offset, $match[1] - $offset);
354        $imports .= $match[0];
355        $offset   = $match[1] + strlen($match[0]);
356    }
357    $newCss .= substr($css, $offset);
358    return $imports.$newCss;
359}
360
361/**
362 * Very simple CSS optimizer
363 *
364 * @author Andreas Gohr <andi@splitbrain.org>
365 */
366function css_compress($css){
367    //strip comments through a callback
368    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
369
370    //strip (incorrect but common) one line comments
371    $css = preg_replace('/(?<!:)\/\/.*$/m','',$css);
372
373    // strip whitespaces
374    $css = preg_replace('![\r\n\t ]+!',' ',$css);
375    $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css);
376    $css = preg_replace('/ ?: /',':',$css);
377
378    // shorten colors
379    $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);
380
381    return $css;
382}
383
384/**
385 * Callback for css_compress()
386 *
387 * Keeps short comments (< 5 chars) to maintain typical browser hacks
388 *
389 * @author Andreas Gohr <andi@splitbrain.org>
390 */
391function css_comment_cb($matches){
392    if(strlen($matches[2]) > 4) return '';
393    return $matches[0];
394}
395
396//Setup VIM: ex: et ts=4 :
397