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