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