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