Thomas Bruederli
2013-10-07 120db629b0645033fd6a477b9f96cc8dad589213
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\(' : '');
448         if (preg_match("/$evilexpr/i", $stripped)) {
449             return '/* evil! */';
450         }
451
452         // cut out all contents between { and }
453         while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
454             $styles = substr($source, $pos+1, $pos2-($pos+1));
455
456             // check every line of a style block...
457             if ($allow_remote) {
458                 $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
459                 foreach ($a_styles as $line) {
460                     $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
461                     // ... and only allow strict url() values
462                     $regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
463                     if (stripos($stripped, 'url(') && !preg_match($regexp, $line)) {
464                         $a_styles = array('/* evil! */');
465                         break;
466                     }
467                 }
468                 $styles = join(";\n", $a_styles);
469             }
470
471             $key = $replacements->add($styles);
472             $source = substr($source, 0, $pos+1)
473                 . $replacements->get_replacement($key)
474                 . substr($source, $pos2, strlen($source)-$pos2);
475             $last_pos = $pos+2;
476         }
477
478         // remove html comments and add #container to each tag selector.
479         // also replace body definition because we also stripped off the <body> tag
af79a7 480         $source = preg_replace(
1aceb9 481             array(
af79a7 482                 '/(^\s*<\!--)|(-->\s*$)/m',
1aceb9 483                 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
A 484                 '/'.preg_quote($container_id, '/').'\s+body/i',
485             ),
486             array(
487                 '',
488                 "\\1#$container_id \\2",
489                 $container_id,
490             ),
491             $source);
492
493         // put block contents back in
af79a7 494         $source = $replacements->resolve($source);
1aceb9 495
af79a7 496         return $source;
1aceb9 497     }
A 498
499
500     /**
501      * Generate CSS classes from mimetype and filename extension
502      *
503      * @param string $mimetype  Mimetype
504      * @param string $filename  Filename
505      *
506      * @return string CSS classes separated by space
507      */
508     public static function file2class($mimetype, $filename)
509     {
fe0f1d 510         $mimetype = strtolower($mimetype);
AM 511         $filename = strtolower($filename);
512
1aceb9 513         list($primary, $secondary) = explode('/', $mimetype);
A 514
515         $classes = array($primary ? $primary : 'unknown');
fe0f1d 516
1aceb9 517         if ($secondary) {
A 518             $classes[] = $secondary;
519         }
fe0f1d 520
AM 521         if (preg_match('/\.([a-z0-9]+)$/', $filename, $m)) {
522             if (!in_array($m[1], $classes)) {
523                 $classes[] = $m[1];
524             }
1aceb9 525         }
A 526
fe0f1d 527         return join(" ", $classes);
1aceb9 528     }
A 529
530
531     /**
532      * Decode escaped entities used by known XSS exploits.
533      * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
534      *
535      * @param string CSS content to decode
536      *
537      * @return string Decoded string
538      */
539     public static function xss_entity_decode($content)
540     {
541         $out = html_entity_decode(html_entity_decode($content));
542         $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
543             array(self, 'xss_entity_decode_callback'), $out);
544         $out = preg_replace('#/\*.*\*/#Ums', '', $out);
545
546         return $out;
547     }
548
549
550     /**
551      * preg_replace_callback callback for xss_entity_decode
552      *
553      * @param array $matches Result from preg_replace_callback
554      *
555      * @return string Decoded entity
556      */
557     public static function xss_entity_decode_callback($matches)
558     {
559         return chr(hexdec($matches[1]));
560     }
561
562
563     /**
564      * Check if we can process not exceeding memory_limit
565      *
566      * @param integer Required amount of memory
567      *
568      * @return boolean True if memory won't be exceeded, False otherwise
569      */
570     public static function mem_check($need)
571     {
572         $mem_limit = parse_bytes(ini_get('memory_limit'));
573         $memory    = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
574
575         return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
576     }
577
578
579     /**
580      * Check if working in SSL mode
581      *
582      * @param integer $port      HTTPS port number
583      * @param boolean $use_https Enables 'use_https' option checking
584      *
585      * @return boolean
586      */
587     public static function https_check($port=null, $use_https=true)
588     {
589         global $RCMAIL;
590
591         if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
592             return true;
593         }
594         if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
595             return true;
596         }
597         if ($port && $_SERVER['SERVER_PORT'] == $port) {
598             return true;
599         }
600         if ($use_https && isset($RCMAIL) && $RCMAIL->config->get('use_https')) {
601             return true;
602         }
603
604         return false;
605     }
606
607
608     /**
609      * Replaces hostname variables.
610      *
611      * @param string $name Hostname
612      * @param string $host Optional IMAP hostname
613      *
614      * @return string Hostname
615      */
616     public static function parse_host($name, $host = '')
617     {
618         // %n - host
619         $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
d359dc 620         // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
a13035 621         $t = preg_replace('/^[^\.]+\./', '', $n);
TB 622         // %d - domain name without first part
d359dc 623         $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
1aceb9 624         // %h - IMAP host
A 625         $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
626         // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
627         $z = preg_replace('/^[^\.]+\./', '', $h);
628         // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
629         if (strpos($name, '%s') !== false) {
630             $user_email = self::get_input_value('_user', self::INPUT_POST);
a13035 631             $user_email = self::idn_convert($user_email, true);
1aceb9 632             $matches    = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
A 633             if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
634                 return false;
635             }
636         }
637
d359dc 638         $name = str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
1aceb9 639         return $name;
A 640     }
641
642
643     /**
644      * Returns remote IP address and forwarded addresses if found
645      *
646      * @return string Remote IP address(es)
647      */
648     public static function remote_ip()
649     {
650         $address = $_SERVER['REMOTE_ADDR'];
651
652         // append the NGINX X-Real-IP header, if set
653         if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
654             $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
655         }
656         // append the X-Forwarded-For header, if set
657         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
658             $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
659         }
660
661         if (!empty($remote_ip)) {
662             $address .= '(' . implode(',', $remote_ip) . ')';
663         }
664
665         return $address;
666     }
667
668
669     /**
4d480b 670      * Returns the real remote IP address
TB 671      *
672      * @return string Remote IP address
673      */
674     public static function remote_addr()
675     {
676         foreach (array('HTTP_X_FORWARDED_FOR','HTTP_X_REAL_IP','REMOTE_ADDR') as $prop) {
677             if (!empty($_SERVER[$prop]))
678                 return $_SERVER[$prop];
679         }
680
681         return '';
682     }
683
684     /**
1aceb9 685      * Read a specific HTTP request header.
A 686      *
687      * @param  string $name Header name
688      *
689      * @return mixed  Header value or null if not available
690      */
691     public static function request_header($name)
692     {
693         if (function_exists('getallheaders')) {
694             $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
695             $key  = strtoupper($name);
696         }
697         else {
698             $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
699             $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
700         }
701
702         return $hdrs[$key];
703     }
704
705     /**
706      * Explode quoted string
707      *
708      * @param string Delimiter expression string for preg_match()
709      * @param string Input string
710      *
711      * @return array String items
712      */
713     public static function explode_quoted_string($delimiter, $string)
714     {
715         $result = array();
716         $strlen = strlen($string);
717
718         for ($q=$p=$i=0; $i < $strlen; $i++) {
719             if ($string[$i] == "\"" && $string[$i-1] != "\\") {
720                 $q = $q ? false : true;
721             }
722             else if (!$q && preg_match("/$delimiter/", $string[$i])) {
723                 $result[] = substr($string, $p, $i - $p);
724                 $p = $i + 1;
725             }
726         }
727
3a54cc 728         $result[] = (string) substr($string, $p);
1aceb9 729
A 730         return $result;
731     }
732
733
734     /**
735      * Improved equivalent to strtotime()
736      *
737      * @param string $date  Date string
738      *
739      * @return int Unix timestamp
740      */
741     public static function strtotime($date)
742     {
b32fab 743         $date = trim($date);
AM 744
1aceb9 745         // check for MS Outlook vCard date format YYYYMMDD
b32fab 746         if (preg_match('/^([12][90]\d\d)([01]\d)([0123]\d)$/', $date, $m)) {
AM 747             return mktime(0,0,0, intval($m[2]), intval($m[3]), intval($m[1]));
1aceb9 748         }
b32fab 749
AM 750         // common little-endian formats, e.g. dd/mm/yyyy (not all are supported by strtotime)
751         if (preg_match('/^(\d{1,2})[.\/-](\d{1,2})[.\/-](\d{4})$/', $date, $m)
752             && $m[1] > 0 && $m[1] <= 31 && $m[2] > 0 && $m[2] <= 12 && $m[3] >= 1970
753         ) {
754             return mktime(0,0,0, intval($m[2]), intval($m[1]), intval($m[3]));
755         }
756
757         // unix timestamp
758         if (is_numeric($date)) {
896e2b 759             return (int) $date;
1aceb9 760         }
A 761
b7570f 762         // Clean malformed data
AM 763         $date = preg_replace(
764             array(
765                 '/GMT\s*([+-][0-9]+)/',                     // support non-standard "GMTXXXX" literal
766                 '/[^a-z0-9\x20\x09:+-]/i',                  // remove any invalid characters
767                 '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i',   // remove weekday names
768             ),
769             array(
770                 '\\1',
771                 '',
772                 '',
773             ), $date);
774
775         $date = trim($date);
1aceb9 776
A 777         // if date parsing fails, we have a date in non-rfc format.
778         // remove token from the end and try again
779         while ((($ts = @strtotime($date)) === false) || ($ts < 0)) {
780             $d = explode(' ', $date);
781             array_pop($d);
782             if (!$d) {
783                 break;
784             }
785             $date = implode(' ', $d);
786         }
787
896e2b 788         return (int) $ts;
1aceb9 789     }
A 790
52830e 791     /**
TB 792      * Date parsing function that turns the given value into a DateTime object
793      *
794      * @param string $date  Date string
795      *
796      * @return object DateTime instance or false on failure
797      */
798     public static function anytodatetime($date)
799     {
800         if (is_object($date) && is_a($date, 'DateTime')) {
801             return $date;
802         }
803
804         $dt = false;
805         $date = trim($date);
806
807         // try to parse string with DateTime first
808         if (!empty($date)) {
809             try {
810                 $dt = new DateTime($date);
811             }
812             catch (Exception $e) {
813                 // ignore
814             }
815         }
816
817         // try our advanced strtotime() method
818         if (!$dt && ($timestamp = self::strtotime($date))) {
819             try {
820                 $dt = new DateTime("@".$timestamp);
821             }
822             catch (Exception $e) {
823                 // ignore
824             }
825         }
826
827         return $dt;
828     }
1aceb9 829
A 830     /*
831      * Idn_to_ascii wrapper.
832      * Intl/Idn modules version of this function doesn't work with e-mail address
833      */
834     public static function idn_to_ascii($str)
835     {
836         return self::idn_convert($str, true);
837     }
838
839
840     /*
841      * Idn_to_ascii wrapper.
842      * Intl/Idn modules version of this function doesn't work with e-mail address
843      */
844     public static function idn_to_utf8($str)
845     {
846         return self::idn_convert($str, false);
847     }
848
849
850     public static function idn_convert($input, $is_utf=false)
851     {
852         if ($at = strpos($input, '@')) {
853             $user   = substr($input, 0, $at);
854             $domain = substr($input, $at+1);
855         }
856         else {
857             $domain = $input;
858         }
859
860         $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
861
862         if ($domain === false) {
863             return '';
864         }
865
866         return $at ? $user . '@' . $domain : $domain;
867     }
868
ceb5b5 869     /**
TB 870      * Split the given string into word tokens
871      *
872      * @param string Input to tokenize
873      * @return array List of tokens
874      */
875     public static function tokenize_string($str)
876     {
877         return explode(" ", preg_replace(
878             array('/[\s;\/+-]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/u'),
879             array(' ', '\\1\\2', ' '),
880             $str));
881     }
882
883     /**
884      * Normalize the given string for fulltext search.
885      * Currently only optimized for Latin-1 characters; to be extended
886      *
887      * @param string  Input string (UTF-8)
888      * @param boolean True to return list of words as array
889      * @return mixed  Normalized string or a list of normalized tokens
890      */
891     public static function normalize_string($str, $as_array = false)
892     {
893         // split by words
894         $arr = self::tokenize_string($str);
895
896         foreach ($arr as $i => $part) {
897             if (utf8_encode(utf8_decode($part)) == $part) {  // is latin-1 ?
898                 $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
899                     'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
900                     'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
901                     array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
902             }
903             else
904                 $arr[$i] = mb_strtolower($part);
905         }
906
907         return $as_array ? $arr : join(" ", $arr);
908     }
909
929030 910     /**
AM 911      * Parse commandline arguments into a hash array
912      *
913      * @param array $aliases Argument alias names
914      *
915      * @return array Argument values hash
916      */
917     public static function get_opt($aliases = array())
918     {
919         $args = array();
920
921         for ($i=1; $i < count($_SERVER['argv']); $i++) {
922             $arg   = $_SERVER['argv'][$i];
923             $value = true;
924             $key   = null;
925
926             if ($arg[0] == '-') {
927                 $key = preg_replace('/^-+/', '', $arg);
928                 $sp  = strpos($arg, '=');
929                 if ($sp > 0) {
930                     $key   = substr($key, 0, $sp - 2);
931                     $value = substr($arg, $sp+1);
932                 }
933                 else if (strlen($_SERVER['argv'][$i+1]) && $_SERVER['argv'][$i+1][0] != '-') {
934                     $value = $_SERVER['argv'][++$i];
935                 }
936
937                 $args[$key] = is_string($value) ? preg_replace(array('/^["\']/', '/["\']$/'), '', $value) : $value;
938             }
939             else {
940                 $args[] = $arg;
941             }
942
943             if ($alias = $aliases[$key]) {
944                 $args[$alias] = $args[$key];
945             }
946         }
947
948         return $args;
949     }
950
951     /**
952      * Safe password prompt for command line
953      * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
954      *
955      * @return string Password
956      */
957     public static function prompt_silent($prompt = "Password:")
958     {
959         if (preg_match('/^win/i', PHP_OS)) {
960             $vbscript  = sys_get_temp_dir() . 'prompt_password.vbs';
961             $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
962             file_put_contents($vbscript, $vbcontent);
963
964             $command  = "cscript //nologo " . escapeshellarg($vbscript);
965             $password = rtrim(shell_exec($command));
966             unlink($vbscript);
967
968             return $password;
969         }
970         else {
971             $command = "/usr/bin/env bash -c 'echo OK'";
972             if (rtrim(shell_exec($command)) !== 'OK') {
973                 echo $prompt;
974                 $pass = trim(fgets(STDIN));
975                 echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
976                 return $pass;
977             }
978
979             $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
980             $password = rtrim(shell_exec($command));
981             echo "\n";
982             return $password;
983         }
984     }
f707fe 985
AM 986
987     /**
988      * Find out if the string content means true or false
989      *
990      * @param string $str Input value
991      *
992      * @return boolean Boolean value
993      */
994     public static function get_boolean($str)
995     {
996         $str = strtolower($str);
997
998         return !in_array($str, array('false', '0', 'no', 'off', 'nein', ''), true);
999     }
1000
1aceb9 1001 }