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