Thomas Bruederli
2013-04-25 ddfdd8938d78b40842a984d310e3c35af30ece0a
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 single quotes if magic_quotes_sybase is enabled
364         if (ini_get('magic_quotes_sybase')) {
365             $value = str_replace("''", "'", $value);
366         }
367         // strip slashes if magic_quotes enabled
368         else if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
369             $value = stripslashes($value);
370         }
371
372         // remove HTML tags if not allowed
373         if (!$allow_html) {
374             $value = strip_tags($value);
375         }
376
377         $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
378
379         // remove invalid characters (#1488124)
380         if ($output_charset == 'UTF-8') {
381             $value = rcube_charset::clean($value);
382         }
383
384         // convert to internal charset
385         if ($charset && $output_charset) {
386             $value = rcube_charset::convert($value, $output_charset, $charset);
387         }
388
389         return $value;
390     }
391
392
393     /**
394      * Convert array of request parameters (prefixed with _)
395      * to a regular array with non-prefixed keys.
396      *
397      * @param int    $mode   Source to get value from (GPC)
398      * @param string $ignore PCRE expression to skip parameters by name
399      *
400      * @return array Hash array with all request parameters
401      */
402     public static function request2param($mode = null, $ignore = 'task|action')
403     {
404         $out = array();
405         $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
406
407         foreach ($src as $key => $value) {
408             $fname = $key[0] == '_' ? substr($key, 1) : $key;
409             if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
410                 $out[$fname] = self::get_input_value($key, $mode);
411             }
412         }
413
414         return $out;
415     }
416
417
418     /**
419      * Convert the given string into a valid HTML identifier
420      * Same functionality as done in app.js with rcube_webmail.html_identifier()
421      */
422     public static function html_identifier($str, $encode=false)
423     {
424         if ($encode) {
425             return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
426         }
427         else {
428             return asciiwords($str, true, '_');
429         }
430     }
431
432
433     /**
434      * Replace all css definitions with #container [def]
435      * and remove css-inlined scripting
436      *
437      * @param string CSS source code
438      * @param string Container ID to use as prefix
439      *
440      * @return string Modified CSS source
441      */
442     public static function mod_css_styles($source, $container_id, $allow_remote=false)
443     {
444         $last_pos = 0;
445         $replacements = new rcube_string_replacer;
446
447         // ignore the whole block if evil styles are detected
448         $source   = self::xss_entity_decode($source);
449         $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
450         $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\(' : '');
451         if (preg_match("/$evilexpr/i", $stripped)) {
452             return '/* evil! */';
453         }
454
455         // cut out all contents between { and }
456         while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
457             $styles = substr($source, $pos+1, $pos2-($pos+1));
458
459             // check every line of a style block...
460             if ($allow_remote) {
461                 $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
462                 foreach ($a_styles as $line) {
463                     $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
464                     // ... and only allow strict url() values
465                     $regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
466                     if (stripos($stripped, 'url(') && !preg_match($regexp, $line)) {
467                         $a_styles = array('/* evil! */');
468                         break;
469                     }
470                 }
471                 $styles = join(";\n", $a_styles);
472             }
473
474             $key = $replacements->add($styles);
475             $source = substr($source, 0, $pos+1)
476                 . $replacements->get_replacement($key)
477                 . substr($source, $pos2, strlen($source)-$pos2);
478             $last_pos = $pos+2;
479         }
480
481         // remove html comments and add #container to each tag selector.
482         // also replace body definition because we also stripped off the <body> tag
483         $styles = preg_replace(
484             array(
485                 '/(^\s*<!--)|(-->\s*$)/',
486                 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
487                 '/'.preg_quote($container_id, '/').'\s+body/i',
488             ),
489             array(
490                 '',
491                 "\\1#$container_id \\2",
492                 $container_id,
493             ),
494             $source);
495
496         // put block contents back in
497         $styles = $replacements->resolve($styles);
498
499         return $styles;
500     }
501
502
503     /**
504      * Generate CSS classes from mimetype and filename extension
505      *
506      * @param string $mimetype  Mimetype
507      * @param string $filename  Filename
508      *
509      * @return string CSS classes separated by space
510      */
511     public static function file2class($mimetype, $filename)
512     {
513         list($primary, $secondary) = explode('/', $mimetype);
514
515         $classes = array($primary ? $primary : 'unknown');
516         if ($secondary) {
517             $classes[] = $secondary;
518         }
519         if (preg_match('/\.([a-z0-9]+)$/i', $filename, $m)) {
520             $classes[] = $m[1];
521         }
522
523         return strtolower(join(" ", $classes));
524     }
525
526
527     /**
528      * Decode escaped entities used by known XSS exploits.
529      * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
530      *
531      * @param string CSS content to decode
532      *
533      * @return string Decoded string
534      */
535     public static function xss_entity_decode($content)
536     {
537         $out = html_entity_decode(html_entity_decode($content));
538         $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
539             array(self, 'xss_entity_decode_callback'), $out);
540         $out = preg_replace('#/\*.*\*/#Ums', '', $out);
541
542         return $out;
543     }
544
545
546     /**
547      * preg_replace_callback callback for xss_entity_decode
548      *
549      * @param array $matches Result from preg_replace_callback
550      *
551      * @return string Decoded entity
552      */
553     public static function xss_entity_decode_callback($matches)
554     {
555         return chr(hexdec($matches[1]));
556     }
557
558
559     /**
560      * Check if we can process not exceeding memory_limit
561      *
562      * @param integer Required amount of memory
563      *
564      * @return boolean True if memory won't be exceeded, False otherwise
565      */
566     public static function mem_check($need)
567     {
568         $mem_limit = parse_bytes(ini_get('memory_limit'));
569         $memory    = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
570
571         return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
572     }
573
574
575     /**
576      * Check if working in SSL mode
577      *
578      * @param integer $port      HTTPS port number
579      * @param boolean $use_https Enables 'use_https' option checking
580      *
581      * @return boolean
582      */
583     public static function https_check($port=null, $use_https=true)
584     {
585         global $RCMAIL;
586
587         if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
588             return true;
589         }
590         if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
591             return true;
592         }
593         if ($port && $_SERVER['SERVER_PORT'] == $port) {
594             return true;
595         }
596         if ($use_https && isset($RCMAIL) && $RCMAIL->config->get('use_https')) {
597             return true;
598         }
599
600         return false;
601     }
602
603
604     /**
605      * Replaces hostname variables.
606      *
607      * @param string $name Hostname
608      * @param string $host Optional IMAP hostname
609      *
610      * @return string Hostname
611      */
612     public static function parse_host($name, $host = '')
613     {
614         // %n - host
615         $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
d359dc 616         // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
a13035 617         $t = preg_replace('/^[^\.]+\./', '', $n);
TB 618         // %d - domain name without first part
d359dc 619         $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
1aceb9 620         // %h - IMAP host
A 621         $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
622         // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
623         $z = preg_replace('/^[^\.]+\./', '', $h);
624         // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
625         if (strpos($name, '%s') !== false) {
626             $user_email = self::get_input_value('_user', self::INPUT_POST);
a13035 627             $user_email = self::idn_convert($user_email, true);
1aceb9 628             $matches    = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
A 629             if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
630                 return false;
631             }
632         }
633
d359dc 634         $name = str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
1aceb9 635         return $name;
A 636     }
637
638
639     /**
640      * Returns remote IP address and forwarded addresses if found
641      *
642      * @return string Remote IP address(es)
643      */
644     public static function remote_ip()
645     {
646         $address = $_SERVER['REMOTE_ADDR'];
647
648         // append the NGINX X-Real-IP header, if set
649         if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
650             $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
651         }
652         // append the X-Forwarded-For header, if set
653         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
654             $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
655         }
656
657         if (!empty($remote_ip)) {
658             $address .= '(' . implode(',', $remote_ip) . ')';
659         }
660
661         return $address;
662     }
663
664
665     /**
666      * Read a specific HTTP request header.
667      *
668      * @param  string $name Header name
669      *
670      * @return mixed  Header value or null if not available
671      */
672     public static function request_header($name)
673     {
674         if (function_exists('getallheaders')) {
675             $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
676             $key  = strtoupper($name);
677         }
678         else {
679             $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
680             $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
681         }
682
683         return $hdrs[$key];
684     }
685
686     /**
687      * Explode quoted string
688      *
689      * @param string Delimiter expression string for preg_match()
690      * @param string Input string
691      *
692      * @return array String items
693      */
694     public static function explode_quoted_string($delimiter, $string)
695     {
696         $result = array();
697         $strlen = strlen($string);
698
699         for ($q=$p=$i=0; $i < $strlen; $i++) {
700             if ($string[$i] == "\"" && $string[$i-1] != "\\") {
701                 $q = $q ? false : true;
702             }
703             else if (!$q && preg_match("/$delimiter/", $string[$i])) {
704                 $result[] = substr($string, $p, $i - $p);
705                 $p = $i + 1;
706             }
707         }
708
3a54cc 709         $result[] = (string) substr($string, $p);
1aceb9 710
A 711         return $result;
712     }
713
714
715     /**
716      * Improved equivalent to strtotime()
717      *
718      * @param string $date  Date string
719      *
720      * @return int Unix timestamp
721      */
722     public static function strtotime($date)
723     {
724         // check for MS Outlook vCard date format YYYYMMDD
725         if (preg_match('/^([12][90]\d\d)([01]\d)(\d\d)$/', trim($date), $matches)) {
726             return mktime(0,0,0, intval($matches[2]), intval($matches[3]), intval($matches[1]));
727         }
728         else if (is_numeric($date)) {
729             return $date;
730         }
731
b7570f 732         // Clean malformed data
AM 733         $date = preg_replace(
734             array(
735                 '/GMT\s*([+-][0-9]+)/',                     // support non-standard "GMTXXXX" literal
736                 '/[^a-z0-9\x20\x09:+-]/i',                  // remove any invalid characters
737                 '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i',   // remove weekday names
738             ),
739             array(
740                 '\\1',
741                 '',
742                 '',
743             ), $date);
744
745         $date = trim($date);
1aceb9 746
A 747         // if date parsing fails, we have a date in non-rfc format.
748         // remove token from the end and try again
749         while ((($ts = @strtotime($date)) === false) || ($ts < 0)) {
750             $d = explode(' ', $date);
751             array_pop($d);
752             if (!$d) {
753                 break;
754             }
755             $date = implode(' ', $d);
756         }
757
758         return $ts;
759     }
760
761
762     /*
763      * Idn_to_ascii wrapper.
764      * Intl/Idn modules version of this function doesn't work with e-mail address
765      */
766     public static function idn_to_ascii($str)
767     {
768         return self::idn_convert($str, true);
769     }
770
771
772     /*
773      * Idn_to_ascii wrapper.
774      * Intl/Idn modules version of this function doesn't work with e-mail address
775      */
776     public static function idn_to_utf8($str)
777     {
778         return self::idn_convert($str, false);
779     }
780
781
782     public static function idn_convert($input, $is_utf=false)
783     {
784         if ($at = strpos($input, '@')) {
785             $user   = substr($input, 0, $at);
786             $domain = substr($input, $at+1);
787         }
788         else {
789             $domain = $input;
790         }
791
792         $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
793
794         if ($domain === false) {
795             return '';
796         }
797
798         return $at ? $user . '@' . $domain : $domain;
799     }
800
ceb5b5 801     /**
TB 802      * Split the given string into word tokens
803      *
804      * @param string Input to tokenize
805      * @return array List of tokens
806      */
807     public static function tokenize_string($str)
808     {
809         return explode(" ", preg_replace(
810             array('/[\s;\/+-]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/u'),
811             array(' ', '\\1\\2', ' '),
812             $str));
813     }
814
815     /**
816      * Normalize the given string for fulltext search.
817      * Currently only optimized for Latin-1 characters; to be extended
818      *
819      * @param string  Input string (UTF-8)
820      * @param boolean True to return list of words as array
821      * @return mixed  Normalized string or a list of normalized tokens
822      */
823     public static function normalize_string($str, $as_array = false)
824     {
825         // split by words
826         $arr = self::tokenize_string($str);
827
828         foreach ($arr as $i => $part) {
829             if (utf8_encode(utf8_decode($part)) == $part) {  // is latin-1 ?
830                 $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
831                     'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
832                     'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
833                     array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
834             }
835             else
836                 $arr[$i] = mb_strtolower($part);
837         }
838
839         return $as_array ? $arr : join(" ", $arr);
840     }
841
929030 842     /**
AM 843      * Parse commandline arguments into a hash array
844      *
845      * @param array $aliases Argument alias names
846      *
847      * @return array Argument values hash
848      */
849     public static function get_opt($aliases = array())
850     {
851         $args = array();
852
853         for ($i=1; $i < count($_SERVER['argv']); $i++) {
854             $arg   = $_SERVER['argv'][$i];
855             $value = true;
856             $key   = null;
857
858             if ($arg[0] == '-') {
859                 $key = preg_replace('/^-+/', '', $arg);
860                 $sp  = strpos($arg, '=');
861                 if ($sp > 0) {
862                     $key   = substr($key, 0, $sp - 2);
863                     $value = substr($arg, $sp+1);
864                 }
865                 else if (strlen($_SERVER['argv'][$i+1]) && $_SERVER['argv'][$i+1][0] != '-') {
866                     $value = $_SERVER['argv'][++$i];
867                 }
868
869                 $args[$key] = is_string($value) ? preg_replace(array('/^["\']/', '/["\']$/'), '', $value) : $value;
870             }
871             else {
872                 $args[] = $arg;
873             }
874
875             if ($alias = $aliases[$key]) {
876                 $args[$alias] = $args[$key];
877             }
878         }
879
880         return $args;
881     }
882
883     /**
884      * Safe password prompt for command line
885      * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
886      *
887      * @return string Password
888      */
889     public static function prompt_silent($prompt = "Password:")
890     {
891         if (preg_match('/^win/i', PHP_OS)) {
892             $vbscript  = sys_get_temp_dir() . 'prompt_password.vbs';
893             $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
894             file_put_contents($vbscript, $vbcontent);
895
896             $command  = "cscript //nologo " . escapeshellarg($vbscript);
897             $password = rtrim(shell_exec($command));
898             unlink($vbscript);
899
900             return $password;
901         }
902         else {
903             $command = "/usr/bin/env bash -c 'echo OK'";
904             if (rtrim(shell_exec($command)) !== 'OK') {
905                 echo $prompt;
906                 $pass = trim(fgets(STDIN));
907                 echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
908                 return $pass;
909             }
910
911             $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
912             $password = rtrim(shell_exec($command));
913             echo "\n";
914             return $password;
915         }
916     }
f707fe 917
AM 918
919     /**
920      * Find out if the string content means true or false
921      *
922      * @param string $str Input value
923      *
924      * @return boolean Boolean value
925      */
926     public static function get_boolean($str)
927     {
928         $str = strtolower($str);
929
930         return !in_array($str, array('false', '0', 'no', 'off', 'nein', ''), true);
931     }
932
1aceb9 933 }