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