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