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