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