xref: /dokuwiki/lib/exe/css.php (revision f2342ff08c1235896018b69b9cf2768d88c487fd)
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
12if(!defined('NL')) define('NL',"\n");
13if(!defined('DEFAULT_FLAVOUR')) define('DEFAULT_FLAVOUR',"style");
14require_once(DOKU_INC.'inc/init.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    global $config_cascade;
34    global $INPUT;
35
36    if ($INPUT->str('s') == 'feed') {
37        $mediatypes = array('feed');
38        $type = 'feed';
39    } else {
40        $mediatypes = array('screen', 'all', 'print', 'handheld');
41        $type = '';
42    }
43
44    // decide from where to get the template
45    $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t')));
46    if(!$tpl) $tpl = $conf['template'];
47
48    // decide from where to get the template
49    $flavour = trim(preg_replace('/[^\w-]+/','',$INPUT->str('f')));
50    if(!$flavour) $flavour = DEFAULT_FLAVOUR;
51
52    // load styl.ini
53    $styleini = css_styleini($tpl, $flavour, $INPUT->bool('preview'));
54
55    // cache influencers
56    $tplinc = tpl_incdir($tpl);
57    $cache_files = getConfigFiles('main');
58    $cache_files[] = $tplinc.'style.ini';
59    $cache_files[] = DOKU_CONF."tpl/$tpl/style.ini";
60    $cache_files[] = DOKU_CONF."tpl/$tpl/ini/".$flavour.".ini";
61    $cache_files[] = __FILE__;
62    if($INPUT->bool('preview')) $cache_files[] = $conf['cachedir'].'/preview.ini';
63
64    // Array of needed files and their web locations, the latter ones
65    // are needed to fix relative paths in the stylesheets
66    // We only need to build the list for the requested flavour.
67    $media_files = array();
68    foreach($mediatypes as $mediatype) {
69        $files = array();
70        if ( $flavour === DEFAULT_FLAVOUR ) {
71            // load core styles
72            $files[DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/';
73
74            // load jQuery-UI theme
75            if ($mediatype == 'screen') {
76                $files[DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/';
77            }
78            // load plugin styles
79            $files = array_merge($files, css_pluginstyles($mediatype));
80            // load template styles
81            if (isset($styleini['stylesheets'][$mediatype])) {
82                $files = array_merge($files, $styleini['stylesheets'][$mediatype]);
83            }
84            // load user styles
85            if(!empty($config_cascade['userstyle'][$mediatype])) {
86                foreach($config_cascade['userstyle'][$mediatype] as $userstyle) {
87                    $files[$userstyle] = DOKU_BASE;
88                }
89            }
90        } else if (isset($styleini['stylesheets'][$mediatype])) {
91            // only allow the predefined media types
92            $files = $styleini['stylesheets'][$mediatype];
93        }
94
95        // Let plugins decide to either put more styles here or to remove some
96        $media_files[$mediatype] = css_filewrapper($mediatype, $flavour, $files);
97        $CSSEvt = new Doku_Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]);
98
99        // Make it preventable.
100        if ( $CSSEvt->advise_before() ) {
101            $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files']));
102        } else {
103            // unset if prevented. Nothing will be printed for this mediatype.
104            unset($media_files[$mediatype]);
105        }
106
107        // finish event.
108        $CSSEvt->advise_after();
109    }
110
111    // The generated script depends on some dynamic options
112    $cache = new cache('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].DOKU_BASE.$tpl.$flavour.$type,'.css');
113    $cache->_event = 'CSS_CACHE_USE';
114
115    // check cache age & handle conditional request
116    // This may exit if a cache can be used
117    $cache_ok = $cache->useCache(array('files' => $cache_files));
118    http_cached($cache->cache, $cache_ok);
119
120    // start output buffering
121    ob_start();
122
123    if ( $flavour === DEFAULT_FLAVOUR ) {
124        // Fire CSS_STYLES_INCLUDED for one last time to let the
125        // plugins decide whether to include the DW default styles.
126        // This can be done by preventing the Default.
127        $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT');
128        trigger_event('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles');
129    }
130
131    // build the stylesheet
132    foreach ($mediatypes as $mediatype) {
133
134        // Check if there is a wrapper set for this type.
135        if ( !isset($media_files[$mediatype]) ) {
136            continue;
137        }
138
139        $cssData = $media_files[$mediatype];
140
141        // Print the styles.
142        print NL;
143        if ( $cssData['encapsulate'] === true ) print $cssData['encapsulationPrefix'] . ' {';
144        print '/* START '.$cssData['mediatype'].' styles */'.NL;
145
146        // load files
147        foreach($cssData['files'] as $file => $location){
148            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
149            print "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
150            print css_loadfile($file, $location);
151        }
152
153        print NL;
154        if ( $cssData['encapsulate'] === true ) print '} /* /@media ';
155        else print '/*';
156        print ' END '.$cssData['mediatype'].' styles */'.NL;
157    }
158
159    // end output buffering and get contents
160    $css = ob_get_contents();
161    ob_end_clean();
162
163    // strip any source maps
164    stripsourcemaps($css);
165
166    // apply style replacements
167    $css = css_applystyle($css, $styleini['replacements']);
168
169    // parse less
170    $css = css_parseless($css);
171
172    // compress whitespace and comments
173    if($conf['compress']){
174        $css = css_compress($css);
175    }
176
177    // embed small images right into the stylesheet
178    if($conf['cssdatauri']){
179        $base = preg_quote(DOKU_BASE,'#');
180        $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css);
181    }
182
183    http_cached_finish($cache->cache, $css);
184}
185
186/**
187 * Uses phpless to parse LESS in our CSS
188 *
189 * most of this function is error handling to show a nice useful error when
190 * LESS compilation fails
191 *
192 * @param string $css
193 * @return string
194 */
195function css_parseless($css) {
196    global $conf;
197
198    $less = new lessc();
199    $less->importDir = array(DOKU_INC);
200    $less->setPreserveComments(!$conf['compress']);
201
202    if (defined('DOKU_UNITTEST')){
203        $less->importDir[] = TMP_DIR;
204    }
205
206    try {
207        return $less->compile($css);
208    } catch(Exception $e) {
209        // get exception message
210        $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage());
211
212        // try to use line number to find affected file
213        if(preg_match('/line: (\d+)$/', $msg, $m)){
214            $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber
215            $lno = $m[1];
216
217            // walk upwards to last include
218            $lines = explode("\n", $css);
219            for($i=$lno-1; $i>=0; $i--){
220                if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){
221                    // we found it, add info to message
222                    $msg .= ' in '.$m[2].' at line '.($lno-$i);
223                    break;
224                }
225            }
226        }
227
228        // something went wrong
229        $error = 'A fatal error occured during compilation of the CSS files. '.
230            'If you recently installed a new plugin or template it '.
231            'might be broken and you should try disabling it again. ['.$msg.']';
232
233        echo ".dokuwiki:before {
234            content: '$error';
235            background-color: red;
236            display: block;
237            background-color: #fcc;
238            border-color: #ebb;
239            color: #000;
240            padding: 0.5em;
241        }";
242
243        exit;
244    }
245}
246
247/**
248 * Does placeholder replacements in the style according to
249 * the ones defined in a templates style.ini file
250 *
251 * This also adds the ini defined placeholders as less variables
252 * (sans the surrounding __ and with a ini_ prefix)
253 *
254 * @author Andreas Gohr <andi@splitbrain.org>
255 *
256 * @param string $css
257 * @param array $replacements  array(placeholder => value)
258 * @return string
259 */
260function css_applystyle($css, $replacements) {
261    // we convert ini replacements to LESS variable names
262    // and build a list of variable: value; pairs
263    $less = '';
264    foreach((array) $replacements as $key => $value) {
265        $lkey = trim($key, '_');
266        $lkey = '@ini_'.$lkey;
267        $less .= "$lkey: $value;\n";
268
269        $replacements[$key] = $lkey;
270    }
271
272    // we now replace all old ini replacements with LESS variables
273    $css = strtr($css, $replacements);
274
275    // now prepend the list of LESS variables as the very first thing
276    $css = $less.$css;
277    return $css;
278}
279
280/**
281 * Load style ini contents
282 *
283 * Loads and merges style.ini files from template and config and prepares
284 * the stylesheet modes
285 *
286 * @author Andreas Gohr <andi@splitbrain.org>
287 *
288 * @param string $tpl the used template
289 * @param bool   $preview load preview replacements
290 * @return array with keys 'stylesheets' and 'replacements'
291 */
292function css_styleini($tpl, $flavour=DEFAULT_FLAVOUR, $preview=false) {
293    global $conf;
294
295    $stylesheets = array(); // mode, file => base
296    $replacements = array(); // placeholder => value
297
298    // load template style.ini replacements first
299    // they should be the base for the colors - if not the default flavour
300    $incbase = tpl_incdir($tpl);
301    $webbase = tpl_basedir($tpl);
302    $ini = $incbase.DEFAULT_FLAVOUR.'.ini';
303    if($flavour != DEFAULT_FLAVOUR && file_exists($ini)) {
304        $data = parse_ini_file($ini, true);
305        // replacements
306        if(is_array($data['replacements'])) {
307            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'], $webbase));
308        }
309    }
310
311    // load template's style.ini
312    $ini = $incbase.$flavour.'.ini';
313    if(file_exists($ini)){
314        $data = parse_ini_file($ini, true);
315
316        // stylesheets
317        if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
318            $stylesheets[$mode][$incbase.$file] = $webbase;
319        }
320        // replacements
321        if(isset($data['replacements']) && is_array($data['replacements'])){
322            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
323        }
324    }
325
326    // load configs's style.ini
327    $webbase = DOKU_BASE;
328    $ini = DOKU_CONF."tpl/$tpl/style.ini";
329    $incbase = dirname($ini).'/';
330    if(file_exists($ini)){
331        $data = parse_ini_file($ini, true);
332
333        // stylesheets - but only if we are on the default flavour
334        if($flavour === DEFAULT_FLAVOUR && isset($data['stylesheets']) && is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){
335            $stylesheets[$mode][$incbase.$file] = $webbase;
336        }
337        // replacements
338        if(isset($data['replacements']) && is_array($data['replacements'])){
339            $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase));
340        }
341    }
342
343    // allow replacement overwrites in preview mode
344    if($preview) {
345        $webbase = DOKU_BASE;
346        $ini     = $conf['cachedir'].'/preview.ini';
347        if(file_exists($ini)) {
348            $data = parse_ini_file($ini, true);
349            // replacements
350            if(is_array($data['replacements'])) {
351                $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'], $webbase));
352            }
353        }
354    }
355
356    return array(
357        'stylesheets' => $stylesheets,
358        'replacements' => $replacements
359    );
360}
361
362/**
363 * Amend paths used in replacement relative urls, refer FS#2879
364 *
365 * @author Chris Smith <chris@jalakai.co.uk>
366 *
367 * @param array $replacements with key-value pairs
368 * @param string $location
369 * @return array
370 */
371function css_fixreplacementurls($replacements, $location) {
372    foreach($replacements as $key => $value) {
373        $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value);
374    }
375    return $replacements;
376}
377
378/**
379 * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED
380 *
381 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
382 *
383 * @param string $mediatype type ofthe current media files/content set
384 * @param array $files set of files that define the current mediatype
385 * @return array
386 */
387function css_filewrapper($mediatype, $flavour=DEFAULT_FLAVOUR, $files=array()){
388    return array(
389            'files'                 => $files,
390            'mediatype'             => $mediatype,
391            'flavour'               => $flavour,
392            'encapsulate'           => in_array($mediatype, array('screen', 'print', 'handheld')),
393            'encapsulationPrefix'   => '@media '.$mediatype
394        );
395}
396
397/**
398 * Prints the @media encapsulated default styles of DokuWiki
399 *
400 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
401 *
402 * This function is being called by a CSS_STYLES_INCLUDED event
403 * The event can be distinguished by the mediatype which is:
404 *   DW_DEFAULT
405 */
406function css_defaultstyles(){
407    // print the default classes for interwiki links and file downloads
408    print '@media screen {';
409    css_interwiki();
410    css_filetypes();
411    print '}';
412}
413
414/**
415 * Prints classes for interwikilinks
416 *
417 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
418 * $name is the identifier given in the config. All Interwiki links get
419 * an default style with a default icon. If a special icon is available
420 * for an interwiki URL it is set in it's own class. Both classes can be
421 * overwritten in the template or userstyles.
422 *
423 * @author Andreas Gohr <andi@splitbrain.org>
424 */
425function css_interwiki(){
426
427    // default style
428    echo 'a.interwiki {';
429    echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;';
430    echo ' padding: 1px 0px 1px 16px;';
431    echo '}';
432
433    // additional styles when icon available
434    $iwlinks = getInterwiki();
435    foreach(array_keys($iwlinks) as $iw){
436        $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw);
437        if(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){
438            echo "a.iw_$class {";
439            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)';
440            echo '}';
441        }elseif(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){
442            echo "a.iw_$class {";
443            echo '  background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)';
444            echo '}';
445        }
446    }
447}
448
449/**
450 * Prints classes for file download links
451 *
452 * @author Andreas Gohr <andi@splitbrain.org>
453 */
454function css_filetypes(){
455
456    // default style
457    echo '.mediafile {';
458    echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;';
459    echo ' padding-left: 18px;';
460    echo ' padding-bottom: 1px;';
461    echo '}';
462
463    // additional styles when icon available
464    // scan directory for all icons
465    $exts = array();
466    if($dh = opendir(DOKU_INC.'lib/images/fileicons')){
467        while(false !== ($file = readdir($dh))){
468            if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){
469                $ext = strtolower($match[1]);
470                $type = '.'.strtolower($match[2]);
471                if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){
472                    $exts[$ext] = $type;
473                }
474            }
475        }
476        closedir($dh);
477    }
478    foreach($exts as $ext=>$type){
479        $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
480        echo ".mf_$class {";
481        echo '  background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')';
482        echo '}';
483    }
484}
485
486/**
487 * Loads a given file and fixes relative URLs with the
488 * given location prefix
489 *
490 * @param string $file file system path
491 * @param string $location
492 * @return string
493 */
494function css_loadfile($file,$location=''){
495    $css_file = new DokuCssFile($file);
496    return $css_file->load($location);
497}
498
499/**
500 *  Helper class to abstract loading of css/less files
501 *
502 *  @author Chris Smith <chris@jalakai.co.uk>
503 */
504class DokuCssFile {
505
506    protected $filepath;             // file system path to the CSS/Less file
507    protected $location;             // base url location of the CSS/Less file
508    protected $relative_path = null;
509
510    public function __construct($file) {
511        $this->filepath = $file;
512    }
513
514    /**
515     * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
516     * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
517     * for less files.
518     *
519     * @param   string   $location   base url for this file
520     * @return  string               the CSS/Less contents of the file
521     */
522    public function load($location='') {
523        if (!file_exists($this->filepath)) return '';
524
525        $css = io_readFile($this->filepath);
526        if (!$location) return $css;
527
528        $this->location = $location;
529
530        $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css);
531        $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css);
532
533        return $css;
534    }
535
536    /**
537     * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
538     *
539     * @return string   relative file system path
540     */
541    protected function getRelativePath(){
542
543        if (is_null($this->relative_path)) {
544            $basedir = array(DOKU_INC);
545
546            // during testing, files may be found relative to a second base dir, TMP_DIR
547            if (defined('DOKU_UNITTEST')) {
548                $basedir[] = realpath(TMP_DIR);
549            }
550
551            $basedir = array_map('preg_quote_cb', $basedir);
552            $regex = '/^('.join('|',$basedir).')/';
553            $this->relative_path = preg_replace($regex, '', dirname($this->filepath));
554        }
555
556        return $this->relative_path;
557    }
558
559    /**
560     * preg_replace callback to adjust relative urls from relative to this file to relative
561     * to the appropriate dokuwiki root location as described in the code
562     *
563     * @param  array    see http://php.net/preg_replace_callback
564     * @return string   see http://php.net/preg_replace_callback
565     */
566    public function replacements($match) {
567
568        // not a relative url? - no adjustment required
569        if (preg_match('#^(/|data:|https?://)#',$match[3])) {
570            return $match[0];
571        }
572        // a less file import? - requires a file system location
573        else if (substr($match[3],-5) == '.less') {
574            if ($match[3]{0} != '/') {
575                $match[3] = $this->getRelativePath() . '/' . $match[3];
576            }
577        }
578        // everything else requires a url adjustment
579        else {
580            $match[3] = $this->location . $match[3];
581        }
582
583        return join('',array_slice($match,1));
584    }
585}
586
587/**
588 * Convert local image URLs to data URLs if the filesize is small
589 *
590 * Callback for preg_replace_callback
591 *
592 * @param array $match
593 * @return string
594 */
595function css_datauri($match){
596    global $conf;
597
598    $pre   = unslash($match[1]);
599    $base  = unslash($match[2]);
600    $url   = unslash($match[3]);
601    $ext   = unslash($match[4]);
602
603    $local = DOKU_INC.$url;
604    $size  = @filesize($local);
605    if($size && $size < $conf['cssdatauri']){
606        $data = base64_encode(file_get_contents($local));
607    }
608    if($data){
609        $url = 'data:image/'.$ext.';base64,'.$data;
610    }else{
611        $url = $base.$url;
612    }
613    return $pre.$url;
614}
615
616
617/**
618 * Returns a list of possible Plugin Styles (no existance check here)
619 *
620 * @author Andreas Gohr <andi@splitbrain.org>
621 *
622 * @param string $mediatype
623 * @return array
624 */
625function css_pluginstyles($mediatype='screen'){
626    $list = array();
627    $plugins = plugin_list();
628    foreach ($plugins as $p){
629        $list[DOKU_PLUGIN."$p/$mediatype.css"]  = DOKU_BASE."lib/plugins/$p/";
630        $list[DOKU_PLUGIN."$p/$mediatype.less"]  = DOKU_BASE."lib/plugins/$p/";
631        // alternative for screen.css
632        if ($mediatype=='screen') {
633            $list[DOKU_PLUGIN."$p/style.css"]  = DOKU_BASE."lib/plugins/$p/";
634            $list[DOKU_PLUGIN."$p/style.less"]  = DOKU_BASE."lib/plugins/$p/";
635        }
636    }
637    return $list;
638}
639
640/**
641 * Very simple CSS optimizer
642 *
643 * @author Andreas Gohr <andi@splitbrain.org>
644 *
645 * @param string $css
646 * @return string
647 */
648function css_compress($css){
649    //strip comments through a callback
650    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
651
652    //strip (incorrect but common) one line comments
653    $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css);
654
655    // strip whitespaces
656    $css = preg_replace('![\r\n\t ]+!',' ',$css);
657    $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css);
658    $css = preg_replace('/ ?: /',':',$css);
659
660    // number compression
661    $css = preg_replace('/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2$3', $css); // "0.1em" to ".1em", "1.10em" to "1.1em"
662    $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0"
663    $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0"
664    $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em"
665    $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em"
666
667    // shorten attributes (1em 1em 1em 1em -> 1em)
668    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em"
669    $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em"
670
671    // shorten colors
672    $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);
673
674    return $css;
675}
676
677/**
678 * Callback for css_compress()
679 *
680 * Keeps short comments (< 5 chars) to maintain typical browser hacks
681 *
682 * @author Andreas Gohr <andi@splitbrain.org>
683 *
684 * @param array $matches
685 * @return string
686 */
687function css_comment_cb($matches){
688    if(strlen($matches[2]) > 4) return '';
689    return $matches[0];
690}
691
692/**
693 * Callback for css_compress()
694 *
695 * Strips one line comments but makes sure it will not destroy url() constructs with slashes
696 *
697 * @param array $matches
698 * @return string
699 */
700function css_onelinecomment_cb($matches) {
701    $line = $matches[0];
702
703    $i = 0;
704    $len = strlen($line);
705
706    while ($i< $len){
707        $nextcom = strpos($line, '//', $i);
708        $nexturl = stripos($line, 'url(', $i);
709
710        if($nextcom === false) {
711            // no more comments, we're done
712            $i = $len;
713            break;
714        }
715
716        // keep any quoted string that starts before a comment
717        $nextsqt = strpos($line, "'", $i);
718        $nextdqt = strpos($line, '"', $i);
719        if(min($nextsqt, $nextdqt) < $nextcom) {
720            $skipto = false;
721            if($nextsqt !== false && ($nextdqt === false || $nextsqt < $nextdqt)) {
722                $skipto = strpos($line, "'", $nextsqt+1) +1;
723            } else if ($nextdqt !== false) {
724                $skipto = strpos($line, '"', $nextdqt+1) +1;
725            }
726
727            if($skipto !== false) {
728                $i = $skipto;
729                continue;
730            }
731        }
732
733        if($nexturl === false || $nextcom < $nexturl) {
734            // no url anymore, strip comment and be done
735            $i = $nextcom;
736            break;
737        }
738
739        // we have an upcoming url
740        $i = strpos($line, ')', $nexturl);
741    }
742
743    return substr($line, 0, $i);
744}
745
746//Setup VIM: ex: et ts=4 :
747