Felix Eckhofer
2014-03-26 f58a294949547ed132bf3cdb5815b68c659b992a
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))) {
fdb30f 457             $nested = strpos($source, '{', $pos+1);
TB 458             if ($nested && $nested < $pos2)  // when dealing with nested blocks (e.g. @media), take the inner one
459                 $pos = $nested;
ff6de9 460             $length = $pos2 - $pos - 1;
AM 461             $styles = substr($source, $pos+1, $length);
1aceb9 462
A 463             // check every line of a style block...
464             if ($allow_remote) {
465                 $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
d1abd8 466
1aceb9 467                 foreach ($a_styles as $line) {
A 468                     $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
469                     // ... and only allow strict url() values
d1abd8 470                     if (stripos($stripped, 'url(') && !preg_match($strict_url_regexp, $line)) {
1aceb9 471                         $a_styles = array('/* evil! */');
A 472                         break;
473                     }
474                 }
d1abd8 475
1aceb9 476                 $styles = join(";\n", $a_styles);
A 477             }
478
d1abd8 479             $key      = $replacements->add($styles);
AM 480             $repl     = $replacements->get_replacement($key);
481             $source   = substr_replace($source, $repl, $pos+1, $length);
482             $last_pos = $pos2 - ($length - strlen($repl));
1aceb9 483         }
A 484
485         // remove html comments and add #container to each tag selector.
486         // also replace body definition because we also stripped off the <body> tag
af79a7 487         $source = preg_replace(
1aceb9 488             array(
af79a7 489                 '/(^\s*<\!--)|(-->\s*$)/m',
1aceb9 490                 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
A 491                 '/'.preg_quote($container_id, '/').'\s+body/i',
492             ),
493             array(
494                 '',
495                 "\\1#$container_id \\2",
496                 $container_id,
497             ),
498             $source);
499
500         // put block contents back in
af79a7 501         $source = $replacements->resolve($source);
1aceb9 502
af79a7 503         return $source;
1aceb9 504     }
A 505
506
507     /**
508      * Generate CSS classes from mimetype and filename extension
509      *
510      * @param string $mimetype  Mimetype
511      * @param string $filename  Filename
512      *
513      * @return string CSS classes separated by space
514      */
515     public static function file2class($mimetype, $filename)
516     {
fe0f1d 517         $mimetype = strtolower($mimetype);
AM 518         $filename = strtolower($filename);
519
1aceb9 520         list($primary, $secondary) = explode('/', $mimetype);
A 521
522         $classes = array($primary ? $primary : 'unknown');
fe0f1d 523
1aceb9 524         if ($secondary) {
A 525             $classes[] = $secondary;
526         }
fe0f1d 527
AM 528         if (preg_match('/\.([a-z0-9]+)$/', $filename, $m)) {
529             if (!in_array($m[1], $classes)) {
530                 $classes[] = $m[1];
531             }
1aceb9 532         }
A 533
fe0f1d 534         return join(" ", $classes);
1aceb9 535     }
A 536
537
538     /**
539      * Decode escaped entities used by known XSS exploits.
540      * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
541      *
542      * @param string CSS content to decode
543      *
544      * @return string Decoded string
545      */
546     public static function xss_entity_decode($content)
547     {
548         $out = html_entity_decode(html_entity_decode($content));
549         $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
550             array(self, 'xss_entity_decode_callback'), $out);
551         $out = preg_replace('#/\*.*\*/#Ums', '', $out);
552
553         return $out;
554     }
555
556
557     /**
558      * preg_replace_callback callback for xss_entity_decode
559      *
560      * @param array $matches Result from preg_replace_callback
561      *
562      * @return string Decoded entity
563      */
564     public static function xss_entity_decode_callback($matches)
565     {
566         return chr(hexdec($matches[1]));
567     }
568
569
570     /**
571      * Check if we can process not exceeding memory_limit
572      *
573      * @param integer Required amount of memory
574      *
575      * @return boolean True if memory won't be exceeded, False otherwise
576      */
577     public static function mem_check($need)
578     {
579         $mem_limit = parse_bytes(ini_get('memory_limit'));
580         $memory    = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
581
582         return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
583     }
584
585
586     /**
587      * Check if working in SSL mode
588      *
589      * @param integer $port      HTTPS port number
590      * @param boolean $use_https Enables 'use_https' option checking
591      *
592      * @return boolean
593      */
594     public static function https_check($port=null, $use_https=true)
595     {
596         if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
597             return true;
598         }
f58a29 599         if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
FE 600             && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
601             && in_array($_SERVER['REMOTE_ADDR'], rcube::get_instance()->config->get('proxy_whitelist', array()))) {
1aceb9 602             return true;
A 603         }
604         if ($port && $_SERVER['SERVER_PORT'] == $port) {
605             return true;
606         }
d71a71 607         if ($use_https && rcube::get_instance()->config->get('use_https')) {
1aceb9 608             return true;
A 609         }
610
611         return false;
612     }
613
614
615     /**
616      * Replaces hostname variables.
617      *
618      * @param string $name Hostname
619      * @param string $host Optional IMAP hostname
620      *
621      * @return string Hostname
622      */
623     public static function parse_host($name, $host = '')
624     {
f6d23a 625         if (!is_string($name)) {
AM 626             return $name;
627         }
628
1aceb9 629         // %n - host
A 630         $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
d359dc 631         // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
a13035 632         $t = preg_replace('/^[^\.]+\./', '', $n);
TB 633         // %d - domain name without first part
d359dc 634         $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
1aceb9 635         // %h - IMAP host
A 636         $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
637         // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
638         $z = preg_replace('/^[^\.]+\./', '', $h);
639         // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
640         if (strpos($name, '%s') !== false) {
641             $user_email = self::get_input_value('_user', self::INPUT_POST);
a13035 642             $user_email = self::idn_convert($user_email, true);
1aceb9 643             $matches    = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
A 644             if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
645                 return false;
646             }
647         }
648
f6d23a 649         return str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
1aceb9 650     }
A 651
652
653     /**
654      * Returns remote IP address and forwarded addresses if found
655      *
656      * @return string Remote IP address(es)
657      */
658     public static function remote_ip()
659     {
660         $address = $_SERVER['REMOTE_ADDR'];
661
662         // append the NGINX X-Real-IP header, if set
663         if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
664             $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
665         }
666         // append the X-Forwarded-For header, if set
667         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
668             $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
669         }
670
671         if (!empty($remote_ip)) {
672             $address .= '(' . implode(',', $remote_ip) . ')';
673         }
674
675         return $address;
676     }
677
678
679     /**
4d480b 680      * Returns the real remote IP address
TB 681      *
682      * @return string Remote IP address
683      */
684     public static function remote_addr()
685     {
f58a29 686         // Check if any of the headers are set first to improve performance
FE 687         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !empty($_SERVER['HTTP_X_REAL_IP'])) {
688             $proxy_whitelist = rcube::get_instance()->config->get('proxy_whitelist', array());
689             if (in_array($_SERVER['REMOTE_ADDR'], $proxy_whitelist)) {
690                 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
691                     foreach(array_reverse(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) as $forwarded_ip) {
692                         if (!in_array($forwarded_ip, $proxy_whitelist)) {
693                             return $forwarded_ip;
694                         }
695                     }
696                 }
a520f3 697
f58a29 698                 if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
FE 699                     return $_SERVER['HTTP_X_REAL_IP'];
700                 }
701             }
a520f3 702         }
AM 703
704         if (!empty($_SERVER['REMOTE_ADDR'])) {
705             return $_SERVER['REMOTE_ADDR'];
4d480b 706         }
TB 707
708         return '';
709     }
710
711     /**
1aceb9 712      * Read a specific HTTP request header.
A 713      *
714      * @param  string $name Header name
715      *
716      * @return mixed  Header value or null if not available
717      */
718     public static function request_header($name)
719     {
720         if (function_exists('getallheaders')) {
721             $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
722             $key  = strtoupper($name);
723         }
724         else {
725             $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
726             $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
727         }
728
729         return $hdrs[$key];
730     }
731
732     /**
733      * Explode quoted string
734      *
735      * @param string Delimiter expression string for preg_match()
736      * @param string Input string
737      *
738      * @return array String items
739      */
740     public static function explode_quoted_string($delimiter, $string)
741     {
742         $result = array();
743         $strlen = strlen($string);
744
745         for ($q=$p=$i=0; $i < $strlen; $i++) {
746             if ($string[$i] == "\"" && $string[$i-1] != "\\") {
747                 $q = $q ? false : true;
748             }
749             else if (!$q && preg_match("/$delimiter/", $string[$i])) {
750                 $result[] = substr($string, $p, $i - $p);
751                 $p = $i + 1;
752             }
753         }
754
3a54cc 755         $result[] = (string) substr($string, $p);
1aceb9 756
A 757         return $result;
758     }
759
760
761     /**
762      * Improved equivalent to strtotime()
763      *
764      * @param string $date  Date string
765      *
766      * @return int Unix timestamp
767      */
768     public static function strtotime($date)
769     {
b1f3c3 770         $date = self::clean_datestr($date);
b32fab 771
AM 772         // unix timestamp
773         if (is_numeric($date)) {
896e2b 774             return (int) $date;
1aceb9 775         }
A 776
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
b1f3c3 804         $dt   = false;
AM 805         $date = self::clean_datestr($date);
52830e 806
TB 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
b1f3c3 830     /**
AM 831      * Clean up date string for strtotime() input
832      *
833      * @param string $date Date string
834      *
835      * @return string Date string
836      */
837     public static function clean_datestr($date)
838     {
839         $date = trim($date);
840
841         // check for MS Outlook vCard date format YYYYMMDD
842         if (preg_match('/^([12][90]\d\d)([01]\d)([0123]\d)$/', $date, $m)) {
843             return sprintf('%04d-%02d-%02d 00:00:00', intval($m[1]), intval($m[2]), intval($m[3]));
844         }
845
846         // Clean malformed data
847         $date = preg_replace(
848             array(
849                 '/GMT\s*([+-][0-9]+)/',                     // support non-standard "GMTXXXX" literal
850                 '/[^a-z0-9\x20\x09:+-\/]/i',                  // remove any invalid characters
851                 '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i',   // remove weekday names
852             ),
853             array(
854                 '\\1',
855                 '',
856                 '',
857             ), $date);
858
859         $date = trim($date);
860
861         // try to fix dd/mm vs. mm/dd discrepancy, we can't do more here
862         if (preg_match('/^(\d{1,2})[.\/-](\d{1,2})[.\/-](\d{4})$/', $date, $m)) {
863             $mdy   = $m[2] > 12 && $m[1] <= 12;
864             $day   = $mdy ? $m[2] : $m[1];
865             $month = $mdy ? $m[1] : $m[2];
866             $date  = sprintf('%04d-%02d-%02d 00:00:00', intval($m[3]), $month, $day);
867         }
868         // I've found that YYYY.MM.DD is recognized wrong, so here's a fix
869         else if (preg_match('/^(\d{4})\.(\d{1,2})\.(\d{1,2})$/', $date)) {
870             $date = str_replace('.', '-', $date) . ' 00:00:00';
871         }
872
873         return $date;
874     }
875
1aceb9 876     /*
A 877      * Idn_to_ascii wrapper.
878      * Intl/Idn modules version of this function doesn't work with e-mail address
879      */
880     public static function idn_to_ascii($str)
881     {
882         return self::idn_convert($str, true);
883     }
884
885
886     /*
887      * Idn_to_ascii wrapper.
888      * Intl/Idn modules version of this function doesn't work with e-mail address
889      */
890     public static function idn_to_utf8($str)
891     {
892         return self::idn_convert($str, false);
893     }
894
895
896     public static function idn_convert($input, $is_utf=false)
897     {
898         if ($at = strpos($input, '@')) {
899             $user   = substr($input, 0, $at);
900             $domain = substr($input, $at+1);
901         }
902         else {
903             $domain = $input;
904         }
905
906         $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
907
908         if ($domain === false) {
909             return '';
910         }
911
912         return $at ? $user . '@' . $domain : $domain;
913     }
914
ceb5b5 915     /**
TB 916      * Split the given string into word tokens
917      *
918      * @param string Input to tokenize
919      * @return array List of tokens
920      */
921     public static function tokenize_string($str)
922     {
923         return explode(" ", preg_replace(
924             array('/[\s;\/+-]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/u'),
925             array(' ', '\\1\\2', ' '),
926             $str));
927     }
928
929     /**
930      * Normalize the given string for fulltext search.
931      * Currently only optimized for Latin-1 characters; to be extended
932      *
933      * @param string  Input string (UTF-8)
934      * @param boolean True to return list of words as array
d19c0f 935      *
ceb5b5 936      * @return mixed  Normalized string or a list of normalized tokens
TB 937      */
938     public static function normalize_string($str, $as_array = false)
939     {
d19c0f 940         // replace 4-byte unicode characters with '?' character,
AM 941         // these are not supported in default utf-8 charset on mysql,
942         // the chance we'd need them in searching is very low
943         $str = preg_replace('/('
944             . '\xF0[\x90-\xBF][\x80-\xBF]{2}'
945             . '|[\xF1-\xF3][\x80-\xBF]{3}'
946             . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'
947             . ')/', '?', $str);
948
ceb5b5 949         // split by words
TB 950         $arr = self::tokenize_string($str);
951
952         foreach ($arr as $i => $part) {
953             if (utf8_encode(utf8_decode($part)) == $part) {  // is latin-1 ?
954                 $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
955                     'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
956                     'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
957                     array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
958             }
959             else
960                 $arr[$i] = mb_strtolower($part);
961         }
962
963         return $as_array ? $arr : join(" ", $arr);
964     }
965
929030 966     /**
AM 967      * Parse commandline arguments into a hash array
968      *
969      * @param array $aliases Argument alias names
970      *
971      * @return array Argument values hash
972      */
973     public static function get_opt($aliases = array())
974     {
975         $args = array();
976
977         for ($i=1; $i < count($_SERVER['argv']); $i++) {
978             $arg   = $_SERVER['argv'][$i];
979             $value = true;
980             $key   = null;
981
982             if ($arg[0] == '-') {
983                 $key = preg_replace('/^-+/', '', $arg);
984                 $sp  = strpos($arg, '=');
985                 if ($sp > 0) {
986                     $key   = substr($key, 0, $sp - 2);
987                     $value = substr($arg, $sp+1);
988                 }
989                 else if (strlen($_SERVER['argv'][$i+1]) && $_SERVER['argv'][$i+1][0] != '-') {
990                     $value = $_SERVER['argv'][++$i];
991                 }
992
993                 $args[$key] = is_string($value) ? preg_replace(array('/^["\']/', '/["\']$/'), '', $value) : $value;
994             }
995             else {
996                 $args[] = $arg;
997             }
998
999             if ($alias = $aliases[$key]) {
1000                 $args[$alias] = $args[$key];
1001             }
1002         }
1003
1004         return $args;
1005     }
1006
1007     /**
1008      * Safe password prompt for command line
1009      * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
1010      *
1011      * @return string Password
1012      */
1013     public static function prompt_silent($prompt = "Password:")
1014     {
1015         if (preg_match('/^win/i', PHP_OS)) {
1016             $vbscript  = sys_get_temp_dir() . 'prompt_password.vbs';
1017             $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
1018             file_put_contents($vbscript, $vbcontent);
1019
1020             $command  = "cscript //nologo " . escapeshellarg($vbscript);
1021             $password = rtrim(shell_exec($command));
1022             unlink($vbscript);
1023
1024             return $password;
1025         }
1026         else {
1027             $command = "/usr/bin/env bash -c 'echo OK'";
1028             if (rtrim(shell_exec($command)) !== 'OK') {
1029                 echo $prompt;
1030                 $pass = trim(fgets(STDIN));
1031                 echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
1032                 return $pass;
1033             }
1034
1035             $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
1036             $password = rtrim(shell_exec($command));
1037             echo "\n";
1038             return $password;
1039         }
1040     }
f707fe 1041
AM 1042
1043     /**
1044      * Find out if the string content means true or false
1045      *
1046      * @param string $str Input value
1047      *
1048      * @return boolean Boolean value
1049      */
1050     public static function get_boolean($str)
1051     {
1052         $str = strtolower($str);
1053
1054         return !in_array($str, array('false', '0', 'no', 'off', 'nein', ''), true);
1055     }
1056
f130f9 1057     /**
AM 1058      * OS-dependent absolute path detection
1059      */
1060     public static function is_absolute_path($path)
1061     {
1062         if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
1063             return (bool) preg_match('!^[a-z]:[\\\\/]!i', $path);
1064         }
1065         else {
1066             return $path[0] == DIRECTORY_SEPARATOR;
1067         }
1068     }
1aceb9 1069 }