xref: /dokuwiki/lib/exe/css.php (revision c0c4ef9875d90979ed9d31ea1b6f2866aecaf565)
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
12require_once(DOKU_INC.'inc/init.php');
13
14// Main (don't run when UNIT test)
15if(!defined('SIMPLE_TEST')){
16    header('Content-Type: text/css; charset=utf-8');
17    css_out();
18}
19
20
21// ---------------------- functions ------------------------------
22
23/**
24 * Output all needed Styles
25 *
26 * @author Andreas Gohr <andi@splitbrain.org>
27 */
28function css_out(){
29    global $conf;
30    global $lang;
31    $style = '';
32    if (isset($_REQUEST['s']) &&
33        in_array($_REQUEST['s'], array('all', 'print', 'feed'))) {
34        $style = $_REQUEST['s'];
35    }
36
37    $tpl = trim(preg_replace('/[^\w-]+/','',$_REQUEST['t']));
38    if($tpl){
39        $tplinc = DOKU_INC.'lib/tpl/'.$tpl.'/';
40        $tpldir = DOKU_BASE.'lib/tpl/'.$tpl.'/';
41    }else{
42        $tplinc = DOKU_TPLINC;
43        $tpldir = DOKU_TPL;
44    }
45
46    // The generated script depends on some dynamic options
47    $cache = getCacheName('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].DOKU_BASE.$tplinc.$style,'.css');
48
49    // load template styles
50    $tplstyles = array();
51    if(@file_exists($tplinc.'style.ini')){
52        $ini = parse_ini_file($tplinc.'style.ini',true);
53        foreach($ini['stylesheets'] as $file => $mode){
54            $tplstyles[$mode][$tplinc.$file] = $tpldir;
55        }
56    }
57
58    // Array of needed files and their web locations, the latter ones
59    // are needed to fix relative paths in the stylesheets
60    $files   = array();
61    //if (isset($tplstyles['all'])) $files = array_merge($files, $tplstyles['all']);
62    if(!empty($style)){
63        $files[DOKU_INC.'lib/styles/'.$style.'.css'] = DOKU_BASE.'lib/styles/';
64        // load plugin, template, user styles
65        $files = array_merge($files, css_pluginstyles($style));
66        if (isset($tplstyles[$style])) $files = array_merge($files, $tplstyles[$style]);
67        $files[DOKU_CONF.'user'.$style.'.css'] = DOKU_BASE;
68    }else{
69        $files[DOKU_INC.'lib/styles/style.css'] = DOKU_BASE.'lib/styles/';
70        // load plugin, template, user styles
71        $files = array_merge($files, css_pluginstyles('screen'));
72        if (isset($tplstyles['screen'])) $files = array_merge($files, $tplstyles['screen']);
73        if($lang['direction'] == 'rtl'){
74            if (isset($tplstyles['rtl'])) $files = array_merge($files, $tplstyles['rtl']);
75        }
76        $files[DOKU_CONF.'userstyle.css'] = DOKU_BASE;
77    }
78
79    // check cache age & handle conditional request
80    header('Cache-Control: public, max-age=3600');
81    header('Pragma: public');
82    if(css_cacheok($cache,array_keys($files),$tplinc)){
83        http_conditionalRequest(filemtime($cache));
84        if($conf['allowdebug']) header("X-CacheUsed: $cache");
85
86        // finally send output
87        if ($conf['gzip_output'] && http_gzip_valid($cache)) {
88          header('Vary: Accept-Encoding');
89          header('Content-Encoding: gzip');
90          readfile($cache.".gz");
91        } else {
92          if (!http_sendfile($cache)) readfile($cache);
93        }
94
95        return;
96    } else {
97        http_conditionalRequest(time());
98    }
99
100    // start output buffering and build the stylesheet
101    ob_start();
102
103    // print the default classes for interwiki links and file downloads
104    css_interwiki();
105    css_filetypes();
106
107    // load files
108    foreach($files as $file => $location){
109        print css_loadfile($file, $location);
110    }
111
112    // end output buffering and get contents
113    $css = ob_get_contents();
114    ob_end_clean();
115
116    // apply style replacements
117    $css = css_applystyle($css,$tplinc);
118
119    // compress whitespace and comments
120    if($conf['compress']){
121        $css = css_compress($css);
122    }
123
124    // save cache file
125    io_saveFile($cache,$css);
126    if(function_exists('gzopen')) io_saveFile("$cache.gz",$css);
127
128    // finally send output
129    if ($conf['gzip_output']) {
130      header('Vary: Accept-Encoding');
131      header('Content-Encoding: gzip');
132      print gzencode($css,9,FORCE_GZIP);
133    } else {
134      print $css;
135    }
136}
137
138/**
139 * Checks if a CSS Cache file still is valid
140 *
141 * @author Andreas Gohr <andi@splitbrain.org>
142 */
143function css_cacheok($cache,$files,$tplinc){
144    global $config_cascade;
145
146    if(isset($_REQUEST['purge'])) return false; //support purge request
147
148    $ctime = @filemtime($cache);
149    if(!$ctime) return false; //There is no cache
150
151    // some additional files to check
152    $files = array_merge($files, getConfigFiles('main'));
153    $files[] = $tplinc.'style.ini';
154    $files[] = __FILE__;
155
156    // now walk the files
157    foreach($files as $file){
158        if(@filemtime($file) > $ctime){
159            return false;
160        }
161    }
162    return true;
163}
164
165/**
166 * Does placeholder replacements in the style according to
167 * the ones defined in a templates style.ini file
168 *
169 * @author Andreas Gohr <andi@splitbrain.org>
170 */
171function css_applystyle($css,$tplinc){
172    if(@file_exists($tplinc.'style.ini')){
173        $ini = parse_ini_file($tplinc.'style.ini',true);
174        $css = strtr($css,$ini['replacements']);
175    }
176    return $css;
177}
178
179/**
180 * Prints classes for interwikilinks
181 *
182 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
183 * $name is the identifier given in the config. All Interwiki links get
184 * an default style with a default icon. If a special icon is available
185 * for an interwiki URL it is set in it's own class. Both classes can be
186 * overwritten in the template or userstyles.
187 *
188 * @author Andreas Gohr <andi@splitbrain.org>
189 */
190function css_interwiki(){
191
192    // default style
193    echo 'a.interwiki {';
194    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
195    echo ' padding-left: 16px;';
196    echo '}';
197
198    // additional styles when icon available
199    $iwlinks = getInterwiki();
200    foreach(array_keys($iwlinks) as $iw){
201        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
202        if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
203            echo "a.iw_$class {";
204            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
205            echo '}';
206        }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
207            echo "a.iw_$class {";
208            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
209            echo '}';
210        }
211    }
212}
213
214/**
215 * Prints classes for file download links
216 *
217 * @author Andreas Gohr <andi@splitbrain.org>
218 */
219function css_filetypes(){
220
221    // default style
222    echo 'a.mediafile {';
223    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
224    echo ' padding-left: 18px;';
225    echo ' padding-bottom: 1px;';
226    echo '}';
227
228    // additional styles when icon available
229    // scan directory for all icons
230    $exts = array();
231    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
232        while(false !== ($file = readdir($dh))){
233            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
234                $ext = strtolower($match[1]);
235                $type = '.'.strtolower($match[2]);
236                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
237                    $exts[$ext] = $type;
238                }
239            }
240        }
241        closedir($dh);
242    }
243    foreach($exts as $ext=>$type){
244        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
245        echo "a.mf_$class {";
246        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
247        echo '}';
248    }
249}
250
251/**
252 * Loads a given file and fixes relative URLs with the
253 * given location prefix
254 */
255function css_loadfile($file,$location=''){
256    if(!@file_exists($file)) return '';
257    $css = io_readFile($file);
258    if(!$location) return $css;
259
260    $css = preg_replace('#(url\([ \'"]*)((?!/|http://|https://| |\'|"))#','\\1'.$location.'\\3',$css);
261    return $css;
262}
263
264
265/**
266 * Returns a list of possible Plugin Styles (no existance check here)
267 *
268 * @author Andreas Gohr <andi@splitbrain.org>
269 */
270function css_pluginstyles($mode='screen'){
271    global $lang;
272    $list = array();
273    $plugins = plugin_list();
274    foreach ($plugins as $p){
275        if($mode == 'all'){
276            $list[DOKU_PLUGIN."$p/all.css"]  = DOKU_BASE."lib/plugins/$p/";
277        }elseif($mode == 'print'){
278            $list[DOKU_PLUGIN."$p/print.css"]  = DOKU_BASE."lib/plugins/$p/";
279        }elseif($mode == 'feed'){
280            $list[DOKU_PLUGIN."$p/feed.css"]  = DOKU_BASE."lib/plugins/$p/";
281        }else{
282            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
283            $list[DOKU_PLUGIN."$p/screen.css"] = DOKU_BASE."lib/plugins/$p/";
284        }
285        if($lang['direction'] == 'rtl'){
286            $list[DOKU_PLUGIN."$p/rtl.css"] = DOKU_BASE."lib/plugins/$p/";
287        }
288    }
289    return $list;
290}
291
292/**
293 * Very simple CSS optimizer
294 *
295 * @author Andreas Gohr <andi@splitbrain.org>
296 */
297function css_compress($css){
298    //strip comments through a callback
299    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
300
301    //strip (incorrect but common) one line comments
302    $css = preg_replace('/(?<!:)\/\/.*$/m','',$css);
303
304    // strip whitespaces
305    $css = preg_replace('![\r\n\t ]+!',' ',$css);
306    $css = preg_replace('/ ?([:;,{}\/]) ?/','\\1',$css);
307
308    // shorten colors
309    $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);
310
311    return $css;
312}
313
314/**
315 * Callback for css_compress()
316 *
317 * Keeps short comments (< 5 chars) to maintain typical browser hacks
318 *
319 * @author Andreas Gohr <andi@splitbrain.org>
320 */
321function css_comment_cb($matches){
322    if(strlen($matches[2]) > 4) return '';
323    return $matches[0];
324}
325
326//Setup VIM: ex: et ts=4 enc=utf-8 :
327