Thomas Bruederli
2012-11-17 6ddb16d181e285d4f0ef0ef55bdd0ba787f1b583
commit | author | age
9db0c8 1 <?php
1aceb9 2
A 3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_utils.php                                       |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2008-2012, The Roundcube Dev Team                       |
9  | Copyright (C) 2011-2012, Kolab Systems AG                             |
10  |                                                                       |
11  | Licensed under the GNU General Public License version 3 or            |
12  | any later version with exceptions for skins & plugins.                |
13  | See the README file for a full license statement.                     |
14  |                                                                       |
15  | PURPOSE:                                                              |
16  |   Utility class providing common functions                            |
17  +-----------------------------------------------------------------------+
18  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
19  | Author: Aleksander Machniak <alec@alec.pl>                            |
20  +-----------------------------------------------------------------------+
21 */
22
23
24 /**
25  * Utility class providing common functions
26  *
9ab346 27  * @package    Framework
AM 28  * @subpackage Utils
1aceb9 29  */
A 30 class rcube_utils
31 {
32     // define constants for input reading
33     const INPUT_GET  = 0x0101;
34     const INPUT_POST = 0x0102;
35     const INPUT_GPC  = 0x0103;
36
37     /**
38      * Helper method to set a cookie with the current path and host settings
39      *
40      * @param string Cookie name
41      * @param string Cookie value
42      * @param string Expiration time
43      */
44     public static function setcookie($name, $value, $exp = 0)
45     {
46         if (headers_sent()) {
47             return;
48         }
49
50         $cookie = session_get_cookie_params();
09e5fc 51         $secure = $cookie['secure'] || self::https_check();
1aceb9 52
A 53         setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'], $secure, true);
54     }
55
56     /**
57      * E-mail address validation.
58      *
59      * @param string $email Email address
60      * @param boolean $dns_check True to check dns
61      *
62      * @return boolean True on success, False if address is invalid
63      */
64     public static function check_email($email, $dns_check=true)
65     {
66         // Check for invalid characters
67         if (preg_match('/[\x00-\x1F\x7F-\xFF]/', $email)) {
68             return false;
69         }
70
71         // Check for length limit specified by RFC 5321 (#1486453)
72         if (strlen($email) > 254) {
73             return false;
74         }
75
76         $email_array = explode('@', $email);
77
78         // Check that there's one @ symbol
79         if (count($email_array) < 2) {
80             return false;
81         }
82
83         $domain_part = array_pop($email_array);
84         $local_part  = implode('@', $email_array);
85
86         // from PEAR::Validate
87         $regexp = '&^(?:
413df0 88             ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")|                             #1 quoted name
AM 89             ([-\w!\#\$%\&\'*+~/^`|{}=]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}=]+)*))  #2 OR dot-atom (RFC5322)
90             $&xi';
1aceb9 91
A 92         if (!preg_match($regexp, $local_part)) {
93             return false;
94         }
95
da2812 96         // Validate domain part
AM 97         if (preg_match('/^\[((IPv6:[0-9a-f:.]+)|([0-9.]+))\]$/i', $domain_part, $matches)) {
a65ce5 98             return self::check_ip(preg_replace('/^IPv6:/i', '', $matches[1])); // valid IPv4 or IPv6 address
1aceb9 99         }
A 100         else {
101             // If not an IP address
102             $domain_array = explode('.', $domain_part);
103             // Not enough parts to be a valid domain
104             if (sizeof($domain_array) < 2) {
105                 return false;
106             }
107
108             foreach ($domain_array as $part) {
109                 if (!preg_match('/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]))$/', $part)) {
110                     return false;
111                 }
112             }
113
c83b83 114             // last domain part
AM 115             if (preg_match('/[^a-zA-Z]/', array_pop($domain_array))) {
116                 return false;
1aceb9 117             }
A 118
119             $rcube = rcube::get_instance();
120
121             if (!$dns_check || !$rcube->config->get('email_dns_check')) {
122                 return true;
123             }
124
125             if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) {
126                 $lookup = array();
127                 @exec("nslookup -type=MX " . escapeshellarg($domain_part) . " 2>&1", $lookup);
128                 foreach ($lookup as $line) {
129                     if (strpos($line, 'MX preference')) {
130                         return true;
131                     }
132                 }
133                 return false;
134             }
135
136             // find MX record(s)
137             if (getmxrr($domain_part, $mx_records)) {
138                 return true;
139             }
140
141             // find any DNS record
142             if (checkdnsrr($domain_part, 'ANY')) {
143                 return true;
144             }
145         }
146
147         return false;
148     }
149
da2812 150
AM 151     /**
152      * Validates IPv4 or IPv6 address
153      *
154      * @param string $ip IP address in v4 or v6 format
155      *
156      * @return bool True if the address is valid
157      */
a65ce5 158     public static function check_ip($ip)
da2812 159     {
AM 160         // IPv6, but there's no build-in IPv6 support
161         if (strpos($ip, ':') !== false && !defined('AF_INET6')) {
162             $parts = explode(':', $domain_part);
163             $count = count($parts);
164
165             if ($count > 8 || $count < 2) {
166                 return false;
167             }
168
169             foreach ($parts as $idx => $part) {
170                 $length = strlen($part);
171                 if (!$length) {
172                     // there can be only one ::
173                     if ($found_empty) {
174                         return false;
175                     }
176                     $found_empty = true;
177                 }
178                 // last part can be an IPv4 address
179                 else if ($idx == $count - 1) {
180                     if (!preg_match('/^[0-9a-f]{1,4}$/i', $part)) {
181                         return @inet_pton($part) !== false;
182                     }
183                 }
184                 else if (!preg_match('/^[0-9a-f]{1,4}$/i', $part)) {
185                     return false;
186                 }
187             }
188
189             return true;
190         }
191
192         return @inet_pton($ip) !== false;
193     }
194
195
1aceb9 196     /**
A 197      * Check whether the HTTP referer matches the current request
198      *
199      * @return boolean True if referer is the same host+path, false if not
200      */
201     public static function check_referer()
202     {
203         $uri = parse_url($_SERVER['REQUEST_URI']);
be71ab 204         $referer = parse_url(self::request_header('Referer'));
AM 205         return $referer['host'] == self::request_header('Host') && $referer['path'] == $uri['path'];
1aceb9 206     }
A 207
208
209     /**
210      * Replacing specials characters to a specific encoding type
211      *
212      * @param  string  Input string
213      * @param  string  Encoding type: text|html|xml|js|url
214      * @param  string  Replace mode for tags: show|replace|remove
215      * @param  boolean Convert newlines
216      *
217      * @return string  The quoted string
218      */
219     public static function rep_specialchars_output($str, $enctype = '', $mode = '', $newlines = true)
220     {
221         static $html_encode_arr = false;
222         static $js_rep_table = false;
223         static $xml_rep_table = false;
224
fa4bf4 225         if (!is_string($str)) {
AM 226             $str = strval($str);
227         }
228
1aceb9 229         // encode for HTML output
A 230         if ($enctype == 'html') {
231             if (!$html_encode_arr) {
232                 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
233                 unset($html_encode_arr['?']);
234             }
235
236             $encode_arr = $html_encode_arr;
237
238             // don't replace quotes and html tags
239             if ($mode == 'show' || $mode == '') {
240                 $ltpos = strpos($str, '<');
241                 if ($ltpos !== false && strpos($str, '>', $ltpos) !== false) {
242                     unset($encode_arr['"']);
243                     unset($encode_arr['<']);
244                     unset($encode_arr['>']);
245                     unset($encode_arr['&']);
246                 }
247             }
248             else if ($mode == 'remove') {
249                 $str = strip_tags($str);
250             }
251
252             $out = strtr($str, $encode_arr);
253
254             return $newlines ? nl2br($out) : $out;
255         }
256
257         // if the replace tables for XML and JS are not yet defined
258         if ($js_rep_table === false) {
259             $js_rep_table = $xml_rep_table = array();
260             $xml_rep_table['&'] = '&amp;';
261
262             // can be increased to support more charsets
263             for ($c=160; $c<256; $c++) {
264                 $xml_rep_table[chr($c)] = "&#$c;";
265             }
266
267             $xml_rep_table['"'] = '&quot;';
268             $js_rep_table['"']  = '\\"';
269             $js_rep_table["'"]  = "\\'";
270             $js_rep_table["\\"] = "\\\\";
271             // Unicode line and paragraph separators (#1486310)
272             $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A8))] = '&#8232;';
273             $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A9))] = '&#8233;';
274         }
275
276         // encode for javascript use
277         if ($enctype == 'js') {
278             return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
279         }
280
281         // encode for plaintext
282         if ($enctype == 'text') {
283             return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
284         }
285
286         if ($enctype == 'url') {
287             return rawurlencode($str);
288         }
289
290         // encode for XML
291         if ($enctype == 'xml') {
292             return strtr($str, $xml_rep_table);
293         }
294
295         // no encoding given -> return original string
296         return $str;
297     }
298
299
300     /**
301      * Read input value and convert it for internal use
302      * Performs stripslashes() and charset conversion if necessary
303      *
304      * @param  string   Field name to read
305      * @param  int      Source to get value from (GPC)
306      * @param  boolean  Allow HTML tags in field value
307      * @param  string   Charset to convert into
308      *
309      * @return string   Field value or NULL if not available
310      */
311     public static function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
312     {
313         $value = NULL;
314
315         if ($source == self::INPUT_GET) {
316             if (isset($_GET[$fname])) {
317                 $value = $_GET[$fname];
318             }
319         }
320         else if ($source == self::INPUT_POST) {
321             if (isset($_POST[$fname])) {
322                 $value = $_POST[$fname];
323             }
324         }
325         else if ($source == self::INPUT_GPC) {
326             if (isset($_POST[$fname])) {
327                 $value = $_POST[$fname];
328             }
329             else if (isset($_GET[$fname])) {
330                 $value = $_GET[$fname];
331             }
332             else if (isset($_COOKIE[$fname])) {
333                 $value = $_COOKIE[$fname];
334             }
335         }
336
337         return self::parse_input_value($value, $allow_html, $charset);
338     }
339
340
341     /**
342      * Parse/validate input value. See self::get_input_value()
343      * Performs stripslashes() and charset conversion if necessary
344      *
345      * @param  string   Input value
346      * @param  boolean  Allow HTML tags in field value
347      * @param  string   Charset to convert into
348      *
349      * @return string   Parsed value
350      */
351     public static function parse_input_value($value, $allow_html=FALSE, $charset=NULL)
352     {
353         global $OUTPUT;
354
355         if (empty($value)) {
356             return $value;
357         }
358
359         if (is_array($value)) {
360             foreach ($value as $idx => $val) {
361                 $value[$idx] = self::parse_input_value($val, $allow_html, $charset);
362             }
363             return $value;
364         }
365
366         // strip single quotes if magic_quotes_sybase is enabled
367         if (ini_get('magic_quotes_sybase')) {
368             $value = str_replace("''", "'", $value);
369         }
370         // strip slashes if magic_quotes enabled
371         else if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
372             $value = stripslashes($value);
373         }
374
375         // remove HTML tags if not allowed
376         if (!$allow_html) {
377             $value = strip_tags($value);
378         }
379
380         $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
381
382         // remove invalid characters (#1488124)
383         if ($output_charset == 'UTF-8') {
384             $value = rcube_charset::clean($value);
385         }
386
387         // convert to internal charset
388         if ($charset && $output_charset) {
389             $value = rcube_charset::convert($value, $output_charset, $charset);
390         }
391
392         return $value;
393     }
394
395
396     /**
397      * Convert array of request parameters (prefixed with _)
398      * to a regular array with non-prefixed keys.
399      *
400      * @param int    $mode   Source to get value from (GPC)
401      * @param string $ignore PCRE expression to skip parameters by name
402      *
403      * @return array Hash array with all request parameters
404      */
405     public static function request2param($mode = null, $ignore = 'task|action')
406     {
407         $out = array();
408         $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
409
410         foreach ($src as $key => $value) {
411             $fname = $key[0] == '_' ? substr($key, 1) : $key;
412             if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
413                 $out[$fname] = self::get_input_value($key, $mode);
414             }
415         }
416
417         return $out;
418     }
419
420
421     /**
422      * Convert the given string into a valid HTML identifier
423      * Same functionality as done in app.js with rcube_webmail.html_identifier()
424      */
425     public static function html_identifier($str, $encode=false)
426     {
427         if ($encode) {
428             return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
429         }
430         else {
431             return asciiwords($str, true, '_');
432         }
433     }
434
435
436     /**
437      * Create an edit field for inclusion on a form
438      *
439      * @param string col field name
440      * @param string value field value
441      * @param array attrib HTML element attributes for field
442      * @param string type HTML element type (default 'text')
443      *
444      * @return string HTML field definition
445      */
446     public static function get_edit_field($col, $value, $attrib, $type = 'text')
447     {
448         static $colcounts = array();
449
450         $fname = '_'.$col;
451         $attrib['name']  = $fname . ($attrib['array'] ? '[]' : '');
452         $attrib['class'] = trim($attrib['class'] . ' ff_' . $col);
453
454         if ($type == 'checkbox') {
455             $attrib['value'] = '1';
456             $input = new html_checkbox($attrib);
457         }
458         else if ($type == 'textarea') {
459             $attrib['cols'] = $attrib['size'];
460             $input = new html_textarea($attrib);
461         }
462         else if ($type == 'select') {
463             $input = new html_select($attrib);
464             $input->add('---', '');
465             $input->add(array_values($attrib['options']), array_keys($attrib['options']));
466         }
467         else if ($attrib['type'] == 'password') {
468             $input = new html_passwordfield($attrib);
469         }
470         else {
471             if ($attrib['type'] != 'text' && $attrib['type'] != 'hidden') {
472                 $attrib['type'] = 'text';
473             }
474             $input = new html_inputfield($attrib);
475         }
476
477         // use value from post
478         if (isset($_POST[$fname])) {
479             $postvalue = self::get_input_value($fname, self::INPUT_POST, true);
480             $value = $attrib['array'] ? $postvalue[intval($colcounts[$col]++)] : $postvalue;
481         }
482
483         $out = $input->show($value);
484
485         return $out;
486     }
487
488
489     /**
490      * Replace all css definitions with #container [def]
491      * and remove css-inlined scripting
492      *
493      * @param string CSS source code
494      * @param string Container ID to use as prefix
495      *
496      * @return string Modified CSS source
497      */
498     public static function mod_css_styles($source, $container_id, $allow_remote=false)
499     {
500         $last_pos = 0;
501         $replacements = new rcube_string_replacer;
502
503         // ignore the whole block if evil styles are detected
504         $source   = self::xss_entity_decode($source);
505         $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
506         $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\(' : '');
507         if (preg_match("/$evilexpr/i", $stripped)) {
508             return '/* evil! */';
509         }
510
511         // cut out all contents between { and }
512         while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
513             $styles = substr($source, $pos+1, $pos2-($pos+1));
514
515             // check every line of a style block...
516             if ($allow_remote) {
517                 $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
518                 foreach ($a_styles as $line) {
519                     $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
520                     // ... and only allow strict url() values
521                     $regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
522                     if (stripos($stripped, 'url(') && !preg_match($regexp, $line)) {
523                         $a_styles = array('/* evil! */');
524                         break;
525                     }
526                 }
527                 $styles = join(";\n", $a_styles);
528             }
529
530             $key = $replacements->add($styles);
531             $source = substr($source, 0, $pos+1)
532                 . $replacements->get_replacement($key)
533                 . substr($source, $pos2, strlen($source)-$pos2);
534             $last_pos = $pos+2;
535         }
536
537         // remove html comments and add #container to each tag selector.
538         // also replace body definition because we also stripped off the <body> tag
539         $styles = preg_replace(
540             array(
541                 '/(^\s*<!--)|(-->\s*$)/',
542                 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
543                 '/'.preg_quote($container_id, '/').'\s+body/i',
544             ),
545             array(
546                 '',
547                 "\\1#$container_id \\2",
548                 $container_id,
549             ),
550             $source);
551
552         // put block contents back in
553         $styles = $replacements->resolve($styles);
554
555         return $styles;
556     }
557
558
559     /**
560      * Generate CSS classes from mimetype and filename extension
561      *
562      * @param string $mimetype  Mimetype
563      * @param string $filename  Filename
564      *
565      * @return string CSS classes separated by space
566      */
567     public static function file2class($mimetype, $filename)
568     {
569         list($primary, $secondary) = explode('/', $mimetype);
570
571         $classes = array($primary ? $primary : 'unknown');
572         if ($secondary) {
573             $classes[] = $secondary;
574         }
575         if (preg_match('/\.([a-z0-9]+)$/i', $filename, $m)) {
576             $classes[] = $m[1];
577         }
578
579         return strtolower(join(" ", $classes));
580     }
581
582
583     /**
584      * Decode escaped entities used by known XSS exploits.
585      * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
586      *
587      * @param string CSS content to decode
588      *
589      * @return string Decoded string
590      */
591     public static function xss_entity_decode($content)
592     {
593         $out = html_entity_decode(html_entity_decode($content));
594         $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
595             array(self, 'xss_entity_decode_callback'), $out);
596         $out = preg_replace('#/\*.*\*/#Ums', '', $out);
597
598         return $out;
599     }
600
601
602     /**
603      * preg_replace_callback callback for xss_entity_decode
604      *
605      * @param array $matches Result from preg_replace_callback
606      *
607      * @return string Decoded entity
608      */
609     public static function xss_entity_decode_callback($matches)
610     {
611         return chr(hexdec($matches[1]));
612     }
613
614
615     /**
616      * Check if we can process not exceeding memory_limit
617      *
618      * @param integer Required amount of memory
619      *
620      * @return boolean True if memory won't be exceeded, False otherwise
621      */
622     public static function mem_check($need)
623     {
624         $mem_limit = parse_bytes(ini_get('memory_limit'));
625         $memory    = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
626
627         return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
628     }
629
630
631     /**
632      * Check if working in SSL mode
633      *
634      * @param integer $port      HTTPS port number
635      * @param boolean $use_https Enables 'use_https' option checking
636      *
637      * @return boolean
638      */
639     public static function https_check($port=null, $use_https=true)
640     {
641         global $RCMAIL;
642
643         if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
644             return true;
645         }
646         if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
647             return true;
648         }
649         if ($port && $_SERVER['SERVER_PORT'] == $port) {
650             return true;
651         }
652         if ($use_https && isset($RCMAIL) && $RCMAIL->config->get('use_https')) {
653             return true;
654         }
655
656         return false;
657     }
658
659
660     /**
661      * Replaces hostname variables.
662      *
663      * @param string $name Hostname
664      * @param string $host Optional IMAP hostname
665      *
666      * @return string Hostname
667      */
668     public static function parse_host($name, $host = '')
669     {
670         // %n - host
671         $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
d359dc 672         // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
a13035 673         $t = preg_replace('/^[^\.]+\./', '', $n);
TB 674         // %d - domain name without first part
d359dc 675         $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
1aceb9 676         // %h - IMAP host
A 677         $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
678         // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
679         $z = preg_replace('/^[^\.]+\./', '', $h);
680         // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
681         if (strpos($name, '%s') !== false) {
682             $user_email = self::get_input_value('_user', self::INPUT_POST);
a13035 683             $user_email = self::idn_convert($user_email, true);
1aceb9 684             $matches    = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
A 685             if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
686                 return false;
687             }
688         }
689
d359dc 690         $name = str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
1aceb9 691         return $name;
A 692     }
693
694
695     /**
696      * Returns remote IP address and forwarded addresses if found
697      *
698      * @return string Remote IP address(es)
699      */
700     public static function remote_ip()
701     {
702         $address = $_SERVER['REMOTE_ADDR'];
703
704         // append the NGINX X-Real-IP header, if set
705         if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
706             $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
707         }
708         // append the X-Forwarded-For header, if set
709         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
710             $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
711         }
712
713         if (!empty($remote_ip)) {
714             $address .= '(' . implode(',', $remote_ip) . ')';
715         }
716
717         return $address;
718     }
719
720
721     /**
722      * Read a specific HTTP request header.
723      *
724      * @param  string $name Header name
725      *
726      * @return mixed  Header value or null if not available
727      */
728     public static function request_header($name)
729     {
730         if (function_exists('getallheaders')) {
731             $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
732             $key  = strtoupper($name);
733         }
734         else {
735             $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
736             $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
737         }
738
739         return $hdrs[$key];
740     }
741
742     /**
743      * Explode quoted string
744      *
745      * @param string Delimiter expression string for preg_match()
746      * @param string Input string
747      *
748      * @return array String items
749      */
750     public static function explode_quoted_string($delimiter, $string)
751     {
752         $result = array();
753         $strlen = strlen($string);
754
755         for ($q=$p=$i=0; $i < $strlen; $i++) {
756             if ($string[$i] == "\"" && $string[$i-1] != "\\") {
757                 $q = $q ? false : true;
758             }
759             else if (!$q && preg_match("/$delimiter/", $string[$i])) {
760                 $result[] = substr($string, $p, $i - $p);
761                 $p = $i + 1;
762             }
763         }
764
3a54cc 765         $result[] = (string) substr($string, $p);
1aceb9 766
A 767         return $result;
768     }
769
770
771     /**
772      * Improved equivalent to strtotime()
773      *
774      * @param string $date  Date string
775      *
776      * @return int Unix timestamp
777      */
778     public static function strtotime($date)
779     {
780         // check for MS Outlook vCard date format YYYYMMDD
781         if (preg_match('/^([12][90]\d\d)([01]\d)(\d\d)$/', trim($date), $matches)) {
782             return mktime(0,0,0, intval($matches[2]), intval($matches[3]), intval($matches[1]));
783         }
784         else if (is_numeric($date)) {
785             return $date;
786         }
787
788         // support non-standard "GMTXXXX" literal
789         $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
790
791         // if date parsing fails, we have a date in non-rfc format.
792         // remove token from the end and try again
793         while ((($ts = @strtotime($date)) === false) || ($ts < 0)) {
794             $d = explode(' ', $date);
795             array_pop($d);
796             if (!$d) {
797                 break;
798             }
799             $date = implode(' ', $d);
800         }
801
802         return $ts;
803     }
804
805
806     /*
807      * Idn_to_ascii wrapper.
808      * Intl/Idn modules version of this function doesn't work with e-mail address
809      */
810     public static function idn_to_ascii($str)
811     {
812         return self::idn_convert($str, true);
813     }
814
815
816     /*
817      * Idn_to_ascii wrapper.
818      * Intl/Idn modules version of this function doesn't work with e-mail address
819      */
820     public static function idn_to_utf8($str)
821     {
822         return self::idn_convert($str, false);
823     }
824
825
826     public static function idn_convert($input, $is_utf=false)
827     {
828         if ($at = strpos($input, '@')) {
829             $user   = substr($input, 0, $at);
830             $domain = substr($input, $at+1);
831         }
832         else {
833             $domain = $input;
834         }
835
836         $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
837
838         if ($domain === false) {
839             return '';
840         }
841
842         return $at ? $user . '@' . $domain : $domain;
843     }
844
ceb5b5 845     /**
TB 846      * Split the given string into word tokens
847      *
848      * @param string Input to tokenize
849      * @return array List of tokens
850      */
851     public static function tokenize_string($str)
852     {
853         return explode(" ", preg_replace(
854             array('/[\s;\/+-]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/u'),
855             array(' ', '\\1\\2', ' '),
856             $str));
857     }
858
859     /**
860      * Normalize the given string for fulltext search.
861      * Currently only optimized for Latin-1 characters; to be extended
862      *
863      * @param string  Input string (UTF-8)
864      * @param boolean True to return list of words as array
865      * @return mixed  Normalized string or a list of normalized tokens
866      */
867     public static function normalize_string($str, $as_array = false)
868     {
869         // split by words
870         $arr = self::tokenize_string($str);
871
872         foreach ($arr as $i => $part) {
873             if (utf8_encode(utf8_decode($part)) == $part) {  // is latin-1 ?
874                 $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
875                     'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
876                     'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
877                     array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
878             }
879             else
880                 $arr[$i] = mb_strtolower($part);
881         }
882
883         return $as_array ? $arr : join(" ", $arr);
884     }
885
1aceb9 886 }