xref: /dokuwiki/lib/exe/css.php (revision 6f0b0dd1609f2a253b48f1b9347168dd2d5a61d7)
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    $mediatype = 'screen';
34    if (isset($_REQUEST['s']) &&
35        in_array($_REQUEST['s'], array('all', 'print', 'feed'))) {
36        $mediatype = $_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 = new cache('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].DOKU_BASE.$tplinc.$mediatype,'.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    // load core styles
64    $files[DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/';
65    // load jQuery-UI theme
66    $files[DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/';
67    // load plugin styles
68    $files = array_merge($files, css_pluginstyles($mediatype));
69    // load template styles
70    if (isset($tplstyles[$mediatype])) {
71        $files = array_merge($files, $tplstyles[$mediatype]);
72    }
73    // if old 'default' userstyle setting exists, make it 'screen' userstyle for backwards compatibility
74    if (isset($config_cascade['userstyle']['default'])) {
75        $config_cascade['userstyle']['screen'] = $config_cascade['userstyle']['default'];
76    }
77    // load user styles
78    if(isset($config_cascade['userstyle'][$mediatype])){
79        $files[$config_cascade['userstyle'][$mediatype]] = DOKU_BASE;
80    }
81    // load rtl styles
82    // @todo: this currently adds the rtl styles only to the 'screen' media type
83    //        but 'print' and 'all' should also be supported
84    if ($mediatype=='screen') {
85        if($lang['direction'] == 'rtl'){
86            if (isset($tplstyles['rtl'])) $files = array_merge($files, $tplstyles['rtl']);
87        }
88    }
89
90    $cache_files = array_merge(array_keys($files), getConfigFiles('main'));
91    $cache_files[] = $tplinc.'style.ini';
92    $cache_files[] = __FILE__;
93
94    // check cache age & handle conditional request
95    // This may exit if a cache can be used
96    http_cached($cache->cache,
97                $cache->useCache(array('files' => $cache_files)));
98
99    // start output buffering and build the stylesheet
100    ob_start();
101
102    // print the default classes for interwiki links and file downloads
103    css_interwiki();
104    css_filetypes();
105
106    // load files
107    foreach($files as $file => $location){
108        print css_loadfile($file, $location);
109    }
110
111    // end output buffering and get contents
112    $css = ob_get_contents();
113    ob_end_clean();
114
115    // apply style replacements
116    $css = css_applystyle($css,$tplinc);
117
118    // place all @import statements at the top of the file
119    $css = css_moveimports($css);
120
121    // compress whitespace and comments
122    if($conf['compress']){
123        $css = css_compress($css);
124    }
125
126    // embed small images right into the stylesheet
127    if($conf['cssdatauri']){
128        $base = preg_quote(DOKU_BASE,'#');
129        $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css);
130    }
131
132    http_cached_finish($cache->cache, $css);
133}
134
135/**
136 * Does placeholder replacements in the style according to
137 * the ones defined in a templates style.ini file
138 *
139 * @author Andreas Gohr <andi@splitbrain.org>
140 */
141function css_applystyle($css,$tplinc){
142    if(@file_exists($tplinc.'style.ini')){
143        $ini = parse_ini_file($tplinc.'style.ini',true);
144        $css = strtr($css,$ini['replacements']);
145    }
146    return $css;
147}
148
149/**
150 * Prints classes for interwikilinks
151 *
152 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
153 * $name is the identifier given in the config. All Interwiki links get
154 * an default style with a default icon. If a special icon is available
155 * for an interwiki URL it is set in it's own class. Both classes can be
156 * overwritten in the template or userstyles.
157 *
158 * @author Andreas Gohr <andi@splitbrain.org>
159 */
160function css_interwiki(){
161
162    // default style
163    echo 'a.interwiki {';
164    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
165    echo ' padding: 1px 0px 1px 16px;';
166    echo '}';
167
168    // additional styles when icon available
169    $iwlinks = getInterwiki();
170    foreach(array_keys($iwlinks) as $iw){
171        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
172        if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
173            echo "a.iw_$class {";
174            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
175            echo '}';
176        }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
177            echo "a.iw_$class {";
178            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
179            echo '}';
180        }
181    }
182}
183
184/**
185 * Prints classes for file download links
186 *
187 * @author Andreas Gohr <andi@splitbrain.org>
188 */
189function css_filetypes(){
190
191    // default style
192    echo '.mediafile {';
193    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
194    echo ' padding-left: 18px;';
195    echo ' padding-bottom: 1px;';
196    echo '}';
197
198    // additional styles when icon available
199    // scan directory for all icons
200    $exts = array();
201    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
202        while(false !== ($file = readdir($dh))){
203            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
204                $ext = strtolower($match[1]);
205                $type = '.'.strtolower($match[2]);
206                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
207                    $exts[$ext] = $type;
208                }
209            }
210        }
211        closedir($dh);
212    }
213    foreach($exts as $ext=>$type){
214        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
215        echo ".mf_$class {";
216        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
217        echo '}';
218    }
219}
220
221/**
222 * Loads a given file and fixes relative URLs with the
223 * given location prefix
224 */
225function css_loadfile($file,$location=''){
226    if(!@file_exists($file)) return '';
227    $css = io_readFile($file);
228    if(!$location) return $css;
229
230    $css = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$css);
231    $css = preg_replace('#(@import\s+[\'"])(?!/|data:|http://|https://)#', '\\1'.$location, $css);
232
233    return $css;
234}
235
236/**
237 * Converte local image URLs to data URLs if the filesize is small
238 *
239 * Callback for preg_replace_callback
240 */
241function css_datauri($match){
242    global $conf;
243
244    $pre   = unslash($match[1]);
245    $base  = unslash($match[2]);
246    $url   = unslash($match[3]);
247    $ext   = unslash($match[4]);
248
249    $local = DOKU_INC.$url;
250    $size  = @filesize($local);
251    if($size && $size < $conf['cssdatauri']){
252        $data = base64_encode(file_get_contents($local));
253    }
254    if($data){
255        $url = 'data:image/'.$ext.';base64,'.$data;
256    }else{
257        $url = $base.$url;
258    }
259    return $pre.$url;
260}
261
262
263/**
264 * Returns a list of possible Plugin Styles (no existance check here)
265 *
266 * @author Andreas Gohr <andi@splitbrain.org>
267 */
268function css_pluginstyles($mediatype='screen'){
269    global $lang;
270    $list = array();
271    $plugins = plugin_list();
272    foreach ($plugins as $p){
273        $list[DOKU_PLUGIN."$p/$mediatype.css"]  = DOKU_BASE."lib/plugins/$p/";
274        // alternative for screen.css
275        if ($mediatype=='screen') {
276            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
277        }
278        if($lang['direction'] == 'rtl'){
279            $list[DOKU_PLUGIN."$p/rtl.css"] = DOKU_BASE."lib/plugins/$p/";
280        }
281    }
282    return $list;
283}
284
285/**
286 * Move all @import statements in a combined stylesheet to the top so they
287 * aren't ignored by the browser.
288 *
289 * @author Gabriel Birke <birke@d-scribe.de>
290 */
291function css_moveimports($css)
292{
293    if(!preg_match_all('/@import\s+(?:url\([^)]+\)|"[^"]+")\s*[^;]*;\s*/', $css, $matches, PREG_OFFSET_CAPTURE)) {
294        return $css;
295    }
296    $newCss  = "";
297    $imports = "";
298    $offset  = 0;
299    foreach($matches[0] as $match) {
300        $newCss  .= substr($css, $offset, $match[1] - $offset);
301        $imports .= $match[0];
302        $offset   = $match[1] + strlen($match[0]);
303    }
304    $newCss .= substr($css, $offset);
305    return $imports.$newCss;
306}
307
308/**
309 * Very simple CSS optimizer
310 *
311 * @author Andreas Gohr <andi@splitbrain.org>
312 */
313function css_compress($css){
314    //strip comments through a callback
315    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
316
317    //strip (incorrect but common) one line comments
318    $css = preg_replace('/(?<!:)\/\/.*$/m','',$css);
319
320    // strip whitespaces
321    $css = preg_replace('![\r\n\t ]+!',' ',$css);
322    $css = preg_replace('/ ?([:;,{}\/]) ?/','\\1',$css);
323
324    // shorten colors
325    $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);
326
327    return $css;
328}
329
330/**
331 * Callback for css_compress()
332 *
333 * Keeps short comments (< 5 chars) to maintain typical browser hacks
334 *
335 * @author Andreas Gohr <andi@splitbrain.org>
336 */
337function css_comment_cb($matches){
338    if(strlen($matches[2]) > 4) return '';
339    return $matches[0];
340}
341
342//Setup VIM: ex: et ts=4 :
343