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