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