1<?php
2
3/**
4 +-----------------------------------------------------------------------+
5 | This file is part of the Roundcube Webmail client                     |
6 |                                                                       |
7 | Copyright (C) The Roundcube Dev Team                                  |
8 | Copyright (C) Kolab Systems AG                                        |
9 |                                                                       |
10 | Licensed under the GNU General Public License version 3 or            |
11 | any later version with exceptions for skins & plugins.                |
12 | See the README file for a full license statement.                     |
13 |                                                                       |
14 | PURPOSE:                                                              |
15 |   Utility class providing common functions                            |
16 +-----------------------------------------------------------------------+
17 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
18 | Author: Aleksander Machniak <alec@alec.pl>                            |
19 +-----------------------------------------------------------------------+
20*/
21
22/**
23 * Utility class providing common functions
24 *
25 * @package    Framework
26 * @subpackage Utils
27 */
28class rcube_utils
29{
30    // define constants for input reading
31    const INPUT_GET    = 1;
32    const INPUT_POST   = 2;
33    const INPUT_COOKIE = 4;
34    const INPUT_GP     = 3; // GET + POST
35    const INPUT_GPC    = 7; // GET + POST + COOKIE
36
37
38    /**
39     * A wrapper for PHP's explode() that does not throw a warning
40     * when the separator does not exist in the string
41     *
42     * @param string $separator Separator string
43     * @param string $string    The string to explode
44     *
45     * @return array Exploded string. Still an array if there's no separator in the string
46     */
47    public static function explode($separator, $string)
48    {
49        if (strpos($string, $separator) !== false) {
50            return explode($separator, $string);
51        }
52
53        return [$string, null];
54    }
55
56    /**
57     * Helper method to set a cookie with the current path and host settings
58     *
59     * @param string $name      Cookie name
60     * @param string $value     Cookie value
61     * @param int    $exp       Expiration time
62     * @param bool   $http_only HTTP Only
63     */
64    public static function setcookie($name, $value, $exp = 0, $http_only = true)
65    {
66        if (headers_sent()) {
67            return;
68        }
69
70        $attrib             = session_get_cookie_params();
71        $attrib['expires']  = $exp;
72        $attrib['secure']   = $attrib['secure'] || self::https_check();
73        $attrib['httponly'] = $http_only;
74
75        // session_get_cookie_params() return includes 'lifetime' but setcookie() does not use it, instead it uses 'expires'
76        unset($attrib['lifetime']);
77
78        if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
79            // An alternative signature for setcookie supporting an options array added in PHP 7.3.0
80            setcookie($name, $value, $attrib);
81        }
82        else {
83            setcookie($name, $value, $attrib['expires'], $attrib['path'], $attrib['domain'], $attrib['secure'], $attrib['httponly']);
84        }
85    }
86
87    /**
88     * E-mail address validation.
89     *
90     * @param string $email     Email address
91     * @param bool   $dns_check True to check dns
92     *
93     * @return bool True on success, False if address is invalid
94     */
95    public static function check_email($email, $dns_check = true)
96    {
97        // Check for invalid (control) characters
98        if (preg_match('/\p{Cc}/u', $email)) {
99            return false;
100        }
101
102        // Check for length limit specified by RFC 5321 (#1486453)
103        if (strlen($email) > 254) {
104            return false;
105        }
106
107        $pos = strrpos($email, '@');
108        if (!$pos) {
109            return false;
110        }
111
112        $domain_part = substr($email, $pos + 1);
113        $local_part  = substr($email, 0, $pos);
114
115        // quoted-string, make sure all backslashes and quotes are
116        // escaped
117        if (substr($local_part, 0, 1) == '"') {
118            $local_quoted = preg_replace('/\\\\(\\\\|\")/','', substr($local_part, 1, -1));
119            if (preg_match('/\\\\|"/', $local_quoted)) {
120                return false;
121            }
122        }
123        // dot-atom portion, make sure there's no prohibited characters
124        else if (preg_match('/(^\.|\.\.|\.$)/', $local_part)
125            || preg_match('/[\\ ",:;<>@]/', $local_part)
126        ) {
127            return false;
128        }
129
130        // Validate domain part
131        if (preg_match('/^\[((IPv6:[0-9a-f:.]+)|([0-9.]+))\]$/i', $domain_part, $matches)) {
132            return self::check_ip(preg_replace('/^IPv6:/i', '', $matches[1])); // valid IPv4 or IPv6 address
133        }
134        else {
135            // If not an IP address
136            $domain_array = explode('.', $domain_part);
137            // Not enough parts to be a valid domain
138            if (count($domain_array) < 2) {
139                return false;
140            }
141
142            foreach ($domain_array as $part) {
143                if (!preg_match('/^((xn--)?([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]))$/', $part)) {
144                    return false;
145                }
146            }
147
148            // last domain part (allow extended TLD)
149            $last_part = array_pop($domain_array);
150            if (strpos($last_part, 'xn--') !== 0
151                && (preg_match('/[^a-zA-Z0-9]/', $last_part) || preg_match('/^[0-9]+$/', $last_part))
152            ) {
153                return false;
154            }
155
156            $rcube = rcube::get_instance();
157
158            if (!$dns_check || !function_exists('checkdnsrr') || !$rcube->config->get('email_dns_check')) {
159                return true;
160            }
161
162            // Check DNS record(s)
163            // Note: We can't use ANY (#6581)
164            foreach (['A', 'MX', 'CNAME', 'AAAA'] as $type) {
165                if (checkdnsrr($domain_part, $type)) {
166                    return true;
167                }
168            }
169        }
170
171        return false;
172    }
173
174    /**
175     * Validates IPv4 or IPv6 address
176     *
177     * @param string $ip IP address in v4 or v6 format
178     *
179     * @return bool True if the address is valid
180     */
181    public static function check_ip($ip)
182    {
183        return filter_var($ip, FILTER_VALIDATE_IP) !== false;
184    }
185
186    /**
187     * Replacing specials characters to a specific encoding type
188     *
189     * @param string $str      Input string
190     * @param string $enctype  Encoding type: text|html|xml|js|url
191     * @param string $mode     Replace mode for tags: show|remove|strict
192     * @param bool   $newlines Convert newlines
193     *
194     * @return string The quoted string
195     */
196    public static function rep_specialchars_output($str, $enctype = '', $mode = '', $newlines = true)
197    {
198        static $html_encode_arr = false;
199        static $js_rep_table    = false;
200        static $xml_rep_table   = false;
201
202        if (!is_string($str)) {
203            $str = strval($str);
204        }
205
206        // encode for HTML output
207        if ($enctype == 'html') {
208            if (!$html_encode_arr) {
209                $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
210                unset($html_encode_arr['?']);
211            }
212
213            $encode_arr = $html_encode_arr;
214
215            if ($mode == 'remove') {
216                $str = strip_tags($str);
217            }
218            else if ($mode != 'strict') {
219                // don't replace quotes and html tags
220                $ltpos = strpos($str, '<');
221                if ($ltpos !== false && strpos($str, '>', $ltpos) !== false) {
222                    unset($encode_arr['"']);
223                    unset($encode_arr['<']);
224                    unset($encode_arr['>']);
225                    unset($encode_arr['&']);
226                }
227            }
228
229            $out = strtr($str, $encode_arr);
230
231            return $newlines ? nl2br($out) : $out;
232        }
233
234        // if the replace tables for XML and JS are not yet defined
235        if ($js_rep_table === false) {
236            $js_rep_table = $xml_rep_table = [];
237            $xml_rep_table['&'] = '&amp;';
238
239            // can be increased to support more charsets
240            for ($c=160; $c<256; $c++) {
241                $xml_rep_table[chr($c)] = "&#$c;";
242            }
243
244            $xml_rep_table['"'] = '&quot;';
245            $js_rep_table['"']  = '\\"';
246            $js_rep_table["'"]  = "\\'";
247            $js_rep_table["\\"] = "\\\\";
248            // Unicode line and paragraph separators (#1486310)
249            $js_rep_table[chr(hexdec('E2')).chr(hexdec('80')).chr(hexdec('A8'))] = '&#8232;';
250            $js_rep_table[chr(hexdec('E2')).chr(hexdec('80')).chr(hexdec('A9'))] = '&#8233;';
251        }
252
253        // encode for javascript use
254        if ($enctype == 'js') {
255            return preg_replace(["/\r?\n/", "/\r/", '/<\\//'], ['\n', '\n', '<\\/'], strtr($str, $js_rep_table));
256        }
257
258        // encode for plaintext
259        if ($enctype == 'text') {
260            return str_replace("\r\n", "\n", $mode == 'remove' ? strip_tags($str) : $str);
261        }
262
263        if ($enctype == 'url') {
264            return rawurlencode($str);
265        }
266
267        // encode for XML
268        if ($enctype == 'xml') {
269            return strtr($str, $xml_rep_table);
270        }
271
272        // no encoding given -> return original string
273        return $str;
274    }
275
276    /**
277     * Read input value and make sure it is a string.
278     *
279     * @param string $fname      Field name to read
280     * @param int    $source     Source to get value from (see self::INPUT_*)
281     * @param bool   $allow_html Allow HTML tags in field value
282     * @param string $charset    Charset to convert into
283     *
284     * @return string Request parameter value
285     * @see self::get_input_value()
286     */
287    public static function get_input_string($fname, $source, $allow_html = false, $charset = null)
288    {
289        $value = self::get_input_value($fname, $source, $allow_html, $charset);
290
291        return is_string($value) ? $value : '';
292    }
293
294    /**
295     * Read request parameter value and convert it for internal use
296     * Performs stripslashes() and charset conversion if necessary
297     *
298     * @param string $fname      Field name to read
299     * @param int    $source     Source to get value from (see self::INPUT_*)
300     * @param bool   $allow_html Allow HTML tags in field value
301     * @param string $charset    Charset to convert into
302     *
303     * @return string|array|null Request parameter value or NULL if not set
304     */
305    public static function get_input_value($fname, $source, $allow_html = false, $charset = null)
306    {
307        $value = null;
308
309        if (($source & self::INPUT_GET) && isset($_GET[$fname])) {
310            $value = $_GET[$fname];
311        }
312
313        if (($source & self::INPUT_POST) && isset($_POST[$fname])) {
314            $value = $_POST[$fname];
315        }
316
317        if (($source & self::INPUT_COOKIE) && isset($_COOKIE[$fname])) {
318            $value = $_COOKIE[$fname];
319        }
320
321        return self::parse_input_value($value, $allow_html, $charset);
322    }
323
324    /**
325     * Parse/validate input value. See self::get_input_value()
326     * Performs stripslashes() and charset conversion if necessary
327     *
328     * @param string $value      Input value
329     * @param bool   $allow_html Allow HTML tags in field value
330     * @param string $charset    Charset to convert into
331     *
332     * @return string Parsed value
333     */
334    public static function parse_input_value($value, $allow_html = false, $charset = null)
335    {
336        if (empty($value)) {
337            return $value;
338        }
339
340        if (is_array($value)) {
341            foreach ($value as $idx => $val) {
342                $value[$idx] = self::parse_input_value($val, $allow_html, $charset);
343            }
344
345            return $value;
346        }
347
348        // remove HTML tags if not allowed
349        if (!$allow_html) {
350            $value = strip_tags($value);
351        }
352
353        $rcube          = rcube::get_instance();
354        $output_charset = is_object($rcube->output) ? $rcube->output->get_charset() : null;
355
356        // remove invalid characters (#1488124)
357        if ($output_charset == 'UTF-8') {
358            $value = rcube_charset::clean($value);
359        }
360
361        // convert to internal charset
362        if ($charset && $output_charset) {
363            $value = rcube_charset::convert($value, $output_charset, $charset);
364        }
365
366        return $value;
367    }
368
369    /**
370     * Convert array of request parameters (prefixed with _)
371     * to a regular array with non-prefixed keys.
372     *
373     * @param int    $mode       Source to get value from (GPC)
374     * @param string $ignore     PCRE expression to skip parameters by name
375     * @param bool   $allow_html Allow HTML tags in field value
376     *
377     * @return array Hash array with all request parameters
378     */
379    public static function request2param($mode = null, $ignore = 'task|action', $allow_html = false)
380    {
381        $out = [];
382        $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
383
384        foreach (array_keys($src) as $key) {
385            $fname = $key[0] == '_' ? substr($key, 1) : $key;
386            if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
387                $out[$fname] = self::get_input_value($key, $mode, $allow_html);
388            }
389        }
390
391        return $out;
392    }
393
394    /**
395     * Convert the given string into a valid HTML identifier
396     * Same functionality as done in app.js with rcube_webmail.html_identifier()
397     *
398     * @param string $str    String input
399     * @param bool   $encode Use base64 encoding
400     *
401     * @param string Valid HTML identifier
402     */
403    public static function html_identifier($str, $encode = false)
404    {
405        if ($encode) {
406            return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
407        }
408
409        return asciiwords($str, true, '_');
410    }
411
412    /**
413     * Replace all css definitions with #container [def]
414     * and remove css-inlined scripting, make position style safe
415     *
416     * @param string $source       CSS source code
417     * @param string $container_id Container ID to use as prefix
418     * @param bool   $allow_remote Allow remote content
419     * @param string $prefix       Prefix to be added to id/class identifier
420     *
421     * @return string Modified CSS source
422     */
423    public static function mod_css_styles($source, $container_id, $allow_remote = false, $prefix = '')
424    {
425        $last_pos     = 0;
426        $replacements = new rcube_string_replacer;
427
428        // ignore the whole block if evil styles are detected
429        $source   = self::xss_entity_decode($source);
430        $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
431        $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\((?!data:image)' : '');
432
433        if (preg_match("/$evilexpr/i", $stripped)) {
434            return '/* evil! */';
435        }
436
437        $strict_url_regexp = '!url\s*\(\s*["\']?(https?:)//[a-z0-9/._+-]+["\']?\s*\)!Uims';
438
439        // remove html comments
440        $source = preg_replace('/(^\s*<\!--)|(-->\s*$)/m', '', $source);
441
442        // cut out all contents between { and }
443        while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
444            $nested = strpos($source, '{', $pos+1);
445            if ($nested && $nested < $pos2) { // when dealing with nested blocks (e.g. @media), take the inner one
446                $pos = $nested;
447            }
448            $length = $pos2 - $pos - 1;
449            $styles = substr($source, $pos+1, $length);
450            $output = '';
451
452            // check every css rule in the style block...
453            foreach (self::parse_css_block($styles) as $rule) {
454                // Remove 'page' attributes (#7604)
455                if ($rule[0] == 'page') {
456                    continue;
457                }
458
459                // Convert position:fixed to position:absolute (#5264)
460                if ($rule[0] == 'position' && strcasecmp($rule[1], 'fixed') === 0) {
461                    $rule[1] = 'absolute';
462                }
463                else if ($allow_remote) {
464                    $stripped = preg_replace('/[^a-z\(:;]/i', '', $rule[1]);
465
466                    // allow data:image and strict url() values only
467                    if (
468                        stripos($stripped, 'url(') !== false
469                        && stripos($stripped, 'url(data:image') === false
470                        && !preg_match($strict_url_regexp, $rule[1])
471                    ) {
472                        $rule[1] = '/* evil! */';
473                    }
474                }
475
476                $output .= sprintf(" %s: %s;", $rule[0] , $rule[1]);
477            }
478
479            $key      = $replacements->add($output . ' ');
480            $repl     = $replacements->get_replacement($key);
481            $source   = substr_replace($source, $repl, $pos+1, $length);
482            $last_pos = $pos2 - ($length - strlen($repl));
483        }
484
485        // add #container to each tag selector and prefix to id/class identifiers
486        if ($container_id || $prefix) {
487            // Exclude rcube_string_replacer pattern matches, this is needed
488            // for cases like @media { body { position: fixed; } } (#5811)
489            $excl     = '(?!' . substr($replacements->pattern, 1, -1) . ')';
490            $regexp   = '/(^\s*|,\s*|\}\s*|\{\s*)(' . $excl . ':?[a-z0-9\._#\*\[][a-z0-9\._:\(\)#=~ \[\]"\|\>\+\$\^-]*)/im';
491            $callback = function($matches) use ($container_id, $prefix) {
492                $replace = $matches[2];
493
494                if (stripos($replace, ':root') === 0) {
495                    $replace = substr($replace, 5);
496                }
497
498                if ($prefix) {
499                    $replace = str_replace(['.', '#'], [".$prefix", "#$prefix"], $replace);
500                }
501
502                if ($container_id) {
503                    $replace = "#$container_id " . $replace;
504                }
505
506                // Remove redundant spaces (for simpler testing)
507                $replace = preg_replace('/\s+/', ' ', $replace);
508
509                return str_replace($matches[2], $replace, $matches[0]);
510            };
511
512            $source = preg_replace_callback($regexp, $callback, $source);
513        }
514
515        // replace body definition because we also stripped off the <body> tag
516        if ($container_id) {
517            $regexp = '/#' . preg_quote($container_id, '/') . '\s+body/i';
518            $source = preg_replace($regexp, "#$container_id", $source);
519        }
520
521        // put block contents back in
522        $source = $replacements->resolve($source);
523
524        return $source;
525    }
526
527    /**
528     * Explode css style. Property names will be lower-cased and trimmed.
529     * Values will be trimmed. Invalid entries will be skipped.
530     *
531     * @param string $style CSS style
532     *
533     * @return array List of CSS rule pairs, e.g. [['color', 'red'], ['top', '0']]
534     */
535    public static function parse_css_block($style)
536    {
537        $pos = 0;
538
539        // first remove comments
540        while (($pos = strpos($style, '/*', $pos)) !== false) {
541            $end = strpos($style, '*/', $pos+2);
542
543            if ($end === false) {
544                $style = substr($style, 0, $pos);
545            }
546            else {
547                $style = substr_replace($style, '', $pos, $end - $pos + 2);
548            }
549        }
550
551        // Replace new lines with spaces
552        $style = preg_replace('/[\r\n]+/', ' ', $style);
553
554        $style  = trim($style);
555        $length = strlen($style);
556        $result = [];
557        $pos    = 0;
558
559        while ($pos < $length && ($colon_pos = strpos($style, ':', $pos))) {
560            // Property name
561            $name = strtolower(trim(substr($style, $pos, $colon_pos - $pos)));
562
563            // get the property value
564            $q = $s = false;
565            for ($i = $colon_pos + 1; $i < $length; $i++) {
566                if (($style[$i] == "\"" || $style[$i] == "'") && ($i == 0 || $style[$i-1] != "\\")) {
567                    if ($q == $style[$i]) {
568                        $q = false;
569                    }
570                    else if ($q === false) {
571                        $q = $style[$i];
572                    }
573                }
574                else if ($style[$i] == "(" && !$q && ($i == 0 || $style[$i-1] != "\\")) {
575                    $q = "(";
576                }
577                else if ($style[$i] == ")" && $q == "(" && $style[$i-1] != "\\") {
578                    $q = false;
579                }
580
581                if ($q === false && (($s = $style[$i] == ';') || $i == $length - 1)) {
582                    break;
583                }
584            }
585
586            $value_length = $i - $colon_pos - ($s ? 1 : 0);
587            $value        = trim(substr($style, $colon_pos + 1, $value_length));
588
589            if (strlen($name) && !preg_match('/[^a-z-]/', $name) && strlen($value) && $value !== ';') {
590                $result[] = [$name, $value];
591            }
592
593            $pos = $i + 1;
594        }
595
596        return $result;
597    }
598
599    /**
600     * Generate CSS classes from mimetype and filename extension
601     *
602     * @param string $mimetype Mimetype
603     * @param string $filename Filename
604     *
605     * @return string CSS classes separated by space
606     */
607    public static function file2class($mimetype, $filename)
608    {
609        $mimetype = strtolower($mimetype);
610        $filename = strtolower($filename);
611
612        list($primary, $secondary) = rcube_utils::explode('/', $mimetype);
613
614        $classes = [$primary ?: 'unknown'];
615
616        if (!empty($secondary)) {
617            $classes[] = $secondary;
618        }
619
620        if (preg_match('/\.([a-z0-9]+)$/', $filename, $m)) {
621            if (!in_array($m[1], $classes)) {
622                $classes[] = $m[1];
623            }
624        }
625
626        return implode(' ', $classes);
627    }
628
629    /**
630     * Decode escaped entities used by known XSS exploits.
631     * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
632     *
633     * @param string $content CSS content to decode
634     *
635     * @return string Decoded string
636     */
637    public static function xss_entity_decode($content)
638    {
639        $callback = function($matches) { return chr(hexdec($matches[1])); };
640
641        $out = html_entity_decode(html_entity_decode($content));
642        $out = trim(preg_replace('/(^<!--|-->$)/', '', trim($out)));
643        $out = preg_replace_callback('/\\\([0-9a-f]{2,6})\s*/i', $callback, $out);
644        $out = preg_replace('/\\\([^0-9a-f])/i', '\\1', $out);
645        $out = preg_replace('#/\*.*\*/#Ums', '', $out);
646        $out = strip_tags($out);
647
648        return $out;
649    }
650
651    /**
652     * Check if we can process not exceeding memory_limit
653     *
654     * @param int $need Required amount of memory
655     *
656     * @return bool True if memory won't be exceeded, False otherwise
657     */
658    public static function mem_check($need)
659    {
660        $mem_limit = parse_bytes(ini_get('memory_limit'));
661        $memory    = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
662
663        return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
664    }
665
666    /**
667     * Check if working in SSL mode
668     *
669     * @param int  $port      HTTPS port number
670     * @param bool $use_https Enables 'use_https' option checking
671     *
672     * @return bool True in SSL mode, False otherwise
673     */
674    public static function https_check($port = null, $use_https = true)
675    {
676        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
677            return true;
678        }
679
680        if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
681            && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
682            && in_array($_SERVER['REMOTE_ADDR'], (array) rcube::get_instance()->config->get('proxy_whitelist', []))
683        ) {
684            return true;
685        }
686
687        if ($port && isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == $port) {
688            return true;
689        }
690
691        if ($use_https && rcube::get_instance()->config->get('use_https')) {
692            return true;
693        }
694
695        return false;
696    }
697
698    /**
699     * Replaces hostname variables.
700     *
701     * @param string $name Hostname
702     * @param string $host Optional IMAP hostname
703     *
704     * @return string Hostname
705     */
706    public static function parse_host($name, $host = '')
707    {
708        if (!is_string($name)) {
709            return $name;
710        }
711
712        // %n - host
713        $n = self::server_name();
714        // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
715        // If %n=domain.tld then %t=domain.tld as well (remains valid)
716        $t = preg_replace('/^[^.]+\.(?![^.]+$)/', '', $n);
717        // %d - domain name without first part (up to domain.tld)
718        $d = preg_replace('/^[^.]+\.(?![^.]+$)/', '', self::server_name('HTTP_HOST'));
719        // %h - IMAP host
720        $h = !empty($_SESSION['storage_host']) ? $_SESSION['storage_host'] : $host;
721        // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
722        // If %h=domain.tld then %z=domain.tld as well (remains valid)
723        $z = preg_replace('/^[^.]+\.(?![^.]+$)/', '', $h);
724        // %s - domain name after the '@' from e-mail address provided at login screen.
725        //      Returns FALSE if an invalid email is provided
726        $s = '';
727        if (strpos($name, '%s') !== false) {
728            $user_email = self::idn_to_ascii(self::get_input_value('_user', self::INPUT_POST));
729            $matches    = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
730            if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
731                return false;
732            }
733            $s = $s[2];
734        }
735
736        return str_replace(['%n', '%t', '%d', '%h', '%z', '%s'], [$n, $t, $d, $h, $z, $s], $name);
737    }
738
739    /**
740     * Returns the server name after checking it against trusted hostname patterns.
741     *
742     * Returns 'localhost' and logs a warning when the hostname is not trusted.
743     *
744     * @param string $type       The $_SERVER key, e.g. 'HTTP_HOST', Default: 'SERVER_NAME'.
745     * @param bool   $strip_port Strip port from the host name
746     *
747     * @return string Server name
748     */
749    public static function server_name($type = null, $strip_port = true)
750    {
751        if (!$type) {
752            $type = 'SERVER_NAME';
753        }
754
755        $name     = isset($_SERVER[$type]) ? $_SERVER[$type] : null;
756        $rcube    = rcube::get_instance();
757        $patterns = (array) $rcube->config->get('trusted_host_patterns');
758
759        if (!empty($name)) {
760            if ($strip_port) {
761                $name = preg_replace('/:\d+$/', '', $name);
762            }
763
764            if (empty($patterns)) {
765                return $name;
766            }
767
768            foreach ($patterns as $pattern) {
769                // the pattern might be a regular expression or just a host/domain name
770                if (preg_match('/[^a-zA-Z0-9.:-]/', $pattern)) {
771                    if (preg_match("/$pattern/", $name)) {
772                        return $name;
773                    }
774                }
775                else if (strtolower($name) === strtolower($pattern)) {
776                    return $name;
777                }
778            }
779
780            $rcube->raise_error([
781                    'file' => __FILE__, 'line' => __LINE__,
782                    'message' => "Specified host is not trusted. Using 'localhost'."
783                ]
784                , true, false
785            );
786        }
787
788        return 'localhost';
789    }
790
791    /**
792     * Returns remote IP address and forwarded addresses if found
793     *
794     * @return string Remote IP address(es)
795     */
796    public static function remote_ip()
797    {
798        $address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
799
800        // append the NGINX X-Real-IP header, if set
801        if (!empty($_SERVER['HTTP_X_REAL_IP']) && $_SERVER['HTTP_X_REAL_IP'] != $address) {
802            $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
803        }
804
805        // append the X-Forwarded-For header, if set
806        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
807            $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
808        }
809
810        if (!empty($remote_ip)) {
811            $address .= ' (' . implode(',', $remote_ip) . ')';
812        }
813
814        return $address;
815    }
816
817    /**
818     * Returns the real remote IP address
819     *
820     * @return string Remote IP address
821     */
822    public static function remote_addr()
823    {
824        // Check if any of the headers are set first to improve performance
825        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !empty($_SERVER['HTTP_X_REAL_IP'])) {
826            $proxy_whitelist = (array) rcube::get_instance()->config->get('proxy_whitelist', []);
827            if (in_array($_SERVER['REMOTE_ADDR'], $proxy_whitelist)) {
828                if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
829                    foreach (array_reverse(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) as $forwarded_ip) {
830                        $forwarded_ip = trim($forwarded_ip);
831                        if (!in_array($forwarded_ip, $proxy_whitelist)) {
832                            return $forwarded_ip;
833                        }
834                    }
835                }
836
837                if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
838                    return $_SERVER['HTTP_X_REAL_IP'];
839                }
840            }
841        }
842
843        if (!empty($_SERVER['REMOTE_ADDR'])) {
844            return $_SERVER['REMOTE_ADDR'];
845        }
846
847        return '';
848    }
849
850    /**
851     * Read a specific HTTP request header.
852     *
853     * @param string $name Header name
854     *
855     * @return string|null Header value or null if not available
856     */
857    public static function request_header($name)
858    {
859        if (function_exists('apache_request_headers')) {
860            $headers = apache_request_headers();
861            $key     = strtoupper($name);
862        }
863        else {
864            $headers = $_SERVER;
865            $key     = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
866        }
867
868        if (!empty($headers)) {
869            $headers = array_change_key_case($headers, CASE_UPPER);
870
871            return isset($headers[$key]) ? $headers[$key] : null;
872        }
873    }
874
875    /**
876     * Explode quoted string
877     *
878     * @param string $delimiter Delimiter expression string for preg_match()
879     * @param string $string    Input string
880     *
881     * @return array String items
882     */
883    public static function explode_quoted_string($delimiter, $string)
884    {
885        $result = [];
886        $strlen = strlen($string);
887
888        for ($q=$p=$i=0; $i < $strlen; $i++) {
889            if ($string[$i] == "\"" && (!isset($string[$i-1]) || $string[$i-1] != "\\")) {
890                $q = $q ? false : true;
891            }
892            else if (!$q && preg_match("/$delimiter/", $string[$i])) {
893                $result[] = substr($string, $p, $i - $p);
894                $p = $i + 1;
895            }
896        }
897
898        $result[] = (string) substr($string, $p);
899
900        return $result;
901    }
902
903    /**
904     * Improved equivalent to strtotime()
905     *
906     * @param string       $date     Date string
907     * @param DateTimeZone $timezone Timezone to use for DateTime object
908     *
909     * @return int Unix timestamp
910     */
911    public static function strtotime($date, $timezone = null)
912    {
913        $date   = self::clean_datestr($date);
914        $tzname = $timezone ? ' ' . $timezone->getName() : '';
915
916        // unix timestamp
917        if (is_numeric($date)) {
918            return (int) $date;
919        }
920
921        // It can be very slow when provided string is not a date and very long
922        if (strlen($date) > 128) {
923            $date = substr($date, 0, 128);
924        }
925
926        // if date parsing fails, we have a date in non-rfc format.
927        // remove token from the end and try again
928        while (($ts = @strtotime($date . $tzname)) === false || $ts < 0) {
929            if (($pos = strrpos($date, ' ')) === false) {
930                break;
931            }
932
933            $date = rtrim(substr($date, 0, $pos));
934        }
935
936        return (int) $ts;
937    }
938
939    /**
940     * Date parsing function that turns the given value into a DateTime object
941     *
942     * @param string       $date     Date string
943     * @param DateTimeZone $timezone Timezone to use for DateTime object
944     *
945     * @return DateTime|false DateTime object or False on failure
946     */
947    public static function anytodatetime($date, $timezone = null)
948    {
949        if ($date instanceof DateTime) {
950            return $date;
951        }
952
953        $dt   = false;
954        $date = self::clean_datestr($date);
955
956        // try to parse string with DateTime first
957        if (!empty($date)) {
958            try {
959                $_date = preg_match('/^[0-9]+$/', $date) ? "@$date" : $date;
960                $dt    = $timezone ? new DateTime($_date, $timezone) : new DateTime($_date);
961            }
962            catch (Exception $e) {
963                // ignore
964            }
965        }
966
967        // try our advanced strtotime() method
968        if (!$dt && ($timestamp = self::strtotime($date, $timezone))) {
969            try {
970                $dt = new DateTime("@".$timestamp);
971                if ($timezone) {
972                    $dt->setTimezone($timezone);
973                }
974            }
975            catch (Exception $e) {
976                // ignore
977            }
978        }
979
980        return $dt;
981    }
982
983    /**
984     * Clean up date string for strtotime() input
985     *
986     * @param string $date Date string
987     *
988     * @return string Date string
989     */
990    public static function clean_datestr($date)
991    {
992        $date = trim($date);
993
994        // check for MS Outlook vCard date format YYYYMMDD
995        if (preg_match('/^([12][90]\d\d)([01]\d)([0123]\d)$/', $date, $m)) {
996            return sprintf('%04d-%02d-%02d 00:00:00', intval($m[1]), intval($m[2]), intval($m[3]));
997        }
998
999        // Clean malformed data
1000        $date = preg_replace(
1001            [
1002                '/\(.*\)/',                                 // remove RFC comments
1003                '/GMT\s*([+-][0-9]+)/',                     // support non-standard "GMTXXXX" literal
1004                '/[^a-z0-9\x20\x09:\/\.+-]/i',              // remove any invalid characters
1005                '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i',   // remove weekday names
1006            ],
1007            [
1008                '',
1009                '\\1',
1010                '',
1011                '',
1012            ],
1013            $date
1014        );
1015
1016        $date = trim($date);
1017
1018        // try to fix dd/mm vs. mm/dd discrepancy, we can't do more here
1019        if (preg_match('/^(\d{1,2})[.\/-](\d{1,2})[.\/-](\d{4})(\s.*)?$/', $date, $m)) {
1020            $mdy   = $m[2] > 12 && $m[1] <= 12;
1021            $day   = $mdy ? $m[2] : $m[1];
1022            $month = $mdy ? $m[1] : $m[2];
1023            $date  = sprintf('%04d-%02d-%02d%s', $m[3], $month, $day, isset($m[4]) ? $m[4]: ' 00:00:00');
1024        }
1025        // I've found that YYYY.MM.DD is recognized wrong, so here's a fix
1026        else if (preg_match('/^(\d{4})\.(\d{1,2})\.(\d{1,2})(\s.*)?$/', $date, $m)) {
1027            $date  = sprintf('%04d-%02d-%02d%s', $m[1], $m[2], $m[3], isset($m[4]) ? $m[4]: ' 00:00:00');
1028        }
1029
1030        return $date;
1031    }
1032
1033    /**
1034     * Turns the given date-only string in defined format into YYYY-MM-DD format.
1035     *
1036     * Supported formats: 'Y/m/d', 'Y.m.d', 'd-m-Y', 'd/m/Y', 'd.m.Y', 'j.n.Y'
1037     *
1038     * @param string $date   Date string
1039     * @param string $format Input date format
1040     *
1041     * @return string Date string in YYYY-MM-DD format, or the original string
1042     *                if format is not supported
1043     */
1044    public static function format_datestr($date, $format)
1045    {
1046        $format_items = preg_split('/[.-\/\\\\]/', $format);
1047        $date_items   = preg_split('/[.-\/\\\\]/', $date);
1048        $iso_format   = '%04d-%02d-%02d';
1049
1050        if (count($format_items) == 3 && count($date_items) == 3) {
1051            if ($format_items[0] == 'Y') {
1052                $date = sprintf($iso_format, $date_items[0], $date_items[1], $date_items[2]);
1053            }
1054            else if (strpos('dj', $format_items[0]) !== false) {
1055                $date = sprintf($iso_format, $date_items[2], $date_items[1], $date_items[0]);
1056            }
1057            else if (strpos('mn', $format_items[0]) !== false) {
1058                $date = sprintf($iso_format, $date_items[2], $date_items[0], $date_items[1]);
1059            }
1060        }
1061
1062        return $date;
1063    }
1064
1065    /**
1066     * Wrapper for idn_to_ascii with support for e-mail address.
1067     *
1068     * Warning: Domain names may be lowercase'd.
1069     * Warning: An empty string may be returned on invalid domain.
1070     *
1071     * @param string $str Decoded e-mail address
1072     *
1073     * @return string Encoded e-mail address
1074     */
1075    public static function idn_to_ascii($str)
1076    {
1077        return self::idn_convert($str, true);
1078    }
1079
1080    /**
1081     * Wrapper for idn_to_utf8 with support for e-mail address
1082     *
1083     * @param string $str Decoded e-mail address
1084     *
1085     * @return string Encoded e-mail address
1086     */
1087    public static function idn_to_utf8($str)
1088    {
1089        return self::idn_convert($str, false);
1090    }
1091
1092    /**
1093     * Convert a string to ascii or utf8 (using IDNA standard)
1094     *
1095     * @param string  $input  Decoded e-mail address
1096     * @param boolean $is_utf Convert by idn_to_ascii if true and idn_to_utf8 if false
1097     *
1098     * @return string Encoded e-mail address
1099     */
1100    public static function idn_convert($input, $is_utf = false)
1101    {
1102        if ($at = strpos($input, '@')) {
1103            $user   = substr($input, 0, $at);
1104            $domain = substr($input, $at + 1);
1105        }
1106        else {
1107            $user   = '';
1108            $domain = $input;
1109        }
1110
1111        // Note that in PHP 7.2/7.3 calling idn_to_* functions with default arguments
1112        // throws a warning, so we have to set the variant explicitly (#6075)
1113        $variant = defined('INTL_IDNA_VARIANT_UTS46') ? INTL_IDNA_VARIANT_UTS46 : null;
1114        $options = 0;
1115
1116        // Because php-intl extension lowercases domains and return false
1117        // on invalid input (#6224), we skip conversion when not needed
1118
1119        if ($is_utf) {
1120            if (preg_match('/[^\x20-\x7E]/', $domain)) {
1121                $options = defined('IDNA_NONTRANSITIONAL_TO_ASCII') ? IDNA_NONTRANSITIONAL_TO_ASCII : 0;
1122                $domain  = idn_to_ascii($domain, $options, $variant);
1123            }
1124        }
1125        else if (preg_match('/(^|\.)xn--/i', $domain)) {
1126            $options = defined('IDNA_NONTRANSITIONAL_TO_UNICODE') ? IDNA_NONTRANSITIONAL_TO_UNICODE : 0;
1127            $domain  = idn_to_utf8($domain, $options, $variant);
1128        }
1129
1130        if ($domain === false) {
1131            return '';
1132        }
1133
1134        return $at ? $user . '@' . $domain : $domain;
1135    }
1136
1137    /**
1138     * Split the given string into word tokens
1139     *
1140     * @param string $str     Input to tokenize
1141     * @param int    $minlen  Minimum length of a single token
1142     *
1143     * @return array List of tokens
1144     */
1145    public static function tokenize_string($str, $minlen = 2)
1146    {
1147        $expr = ['/[\s;,"\'\/+-]+/ui', '/(\d)[-.\s]+(\d)/u'];
1148        $repl = [' ', '\\1\\2'];
1149
1150        if ($minlen > 1) {
1151            $minlen--;
1152            $expr[] = "/(^|\s+)\w{1,$minlen}(\s+|$)/u";
1153            $repl[] = ' ';
1154        }
1155
1156        return array_filter(explode(" ", preg_replace($expr, $repl, $str)));
1157    }
1158
1159    /**
1160     * Normalize the given string for fulltext search.
1161     * Currently only optimized for ISO-8859-1 and ISO-8859-2 characters; to be extended
1162     *
1163     * @param string $str      Input string (UTF-8)
1164     * @param bool   $as_array True to return list of words as array
1165     * @param int    $minlen   Minimum length of tokens
1166     *
1167     * @return string|array Normalized string or a list of normalized tokens
1168     */
1169    public static function normalize_string($str, $as_array = false, $minlen = 2)
1170    {
1171        // replace 4-byte unicode characters with '?' character,
1172        // these are not supported in default utf-8 charset on mysql,
1173        // the chance we'd need them in searching is very low
1174        $str = preg_replace('/('
1175            . '\xF0[\x90-\xBF][\x80-\xBF]{2}'
1176            . '|[\xF1-\xF3][\x80-\xBF]{3}'
1177            . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'
1178            . ')/', '?', $str);
1179
1180        // split by words
1181        $arr = self::tokenize_string($str, $minlen);
1182
1183        // detect character set
1184        if (rcube_charset::convert(rcube_charset::convert($str, 'UTF-8', 'ISO-8859-1'), 'ISO-8859-1', 'UTF-8') == $str)  {
1185            // ISO-8859-1 (or ASCII)
1186            preg_match_all('/./u', 'äâàåáãæçéêëèïîìíñöôòøõóüûùúýÿ', $keys);
1187            preg_match_all('/./',  'aaaaaaaceeeeiiiinoooooouuuuyy', $values);
1188
1189            $mapping = array_combine($keys[0], $values[0]);
1190            $mapping = array_merge($mapping, ['ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u']);
1191        }
1192        else if (rcube_charset::convert(rcube_charset::convert($str, 'UTF-8', 'ISO-8859-2'), 'ISO-8859-2', 'UTF-8') == $str) {
1193            // ISO-8859-2
1194            preg_match_all('/./u', 'ąáâäćçčéęëěíîłľĺńňóôöŕřśšşťţůúűüźžżý', $keys);
1195            preg_match_all('/./',  'aaaaccceeeeiilllnnooorrsssttuuuuzzzy', $values);
1196
1197            $mapping = array_combine($keys[0], $values[0]);
1198            $mapping = array_merge($mapping, ['ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u']);
1199        }
1200
1201        foreach ($arr as $i => $part) {
1202            $part = mb_strtolower($part);
1203
1204            if (!empty($mapping)) {
1205                $part = strtr($part, $mapping);
1206            }
1207
1208            $arr[$i] = $part;
1209        }
1210
1211        return $as_array ? $arr : implode(' ', $arr);
1212    }
1213
1214    /**
1215     * Compare two strings for matching words (order not relevant)
1216     *
1217     * @param string $haystack Haystack
1218     * @param string $needle   Needle
1219     *
1220     * @return bool True if match, False otherwise
1221     */
1222    public static function words_match($haystack, $needle)
1223    {
1224        $a_needle  = self::tokenize_string($needle, 1);
1225        $_haystack = implode(' ', self::tokenize_string($haystack, 1));
1226        $valid     = strlen($_haystack) > 0;
1227        $hits      = 0;
1228
1229        foreach ($a_needle as $w) {
1230            if ($valid) {
1231                if (stripos($_haystack, $w) !== false) {
1232                    $hits++;
1233                }
1234            }
1235            else if (stripos($haystack, $w) !== false) {
1236                $hits++;
1237            }
1238        }
1239
1240        return $hits >= count($a_needle);
1241    }
1242
1243    /**
1244     * Parse commandline arguments into a hash array
1245     *
1246     * @param array $aliases Argument alias names
1247     *
1248     * @return array Argument values hash
1249     */
1250    public static function get_opt($aliases = [])
1251    {
1252        $args = [];
1253        $bool = [];
1254
1255        // find boolean (no value) options
1256        foreach ($aliases as $key => $alias) {
1257            if ($pos = strpos($alias, ':')) {
1258                $aliases[$key] = substr($alias, 0, $pos);
1259                $bool[] = $key;
1260                $bool[] = $aliases[$key];
1261            }
1262        }
1263
1264        for ($i=1; $i < count($_SERVER['argv']); $i++) {
1265            $arg   = $_SERVER['argv'][$i];
1266            $value = true;
1267            $key   = null;
1268
1269            if ($arg[0] == '-') {
1270                $key = preg_replace('/^-+/', '', $arg);
1271                $sp  = strpos($arg, '=');
1272
1273                if ($sp > 0) {
1274                    $key   = substr($key, 0, $sp - 2);
1275                    $value = substr($arg, $sp+1);
1276                }
1277                else if (in_array($key, $bool)) {
1278                    $value = true;
1279                }
1280                else if (
1281                    isset($_SERVER['argv'][$i + 1])
1282                    && strlen($_SERVER['argv'][$i + 1])
1283                    && $_SERVER['argv'][$i + 1][0] != '-'
1284                ) {
1285                    $value = $_SERVER['argv'][++$i];
1286                }
1287
1288                $args[$key] = is_string($value) ? preg_replace(['/^["\']/', '/["\']$/'], '', $value) : $value;
1289            }
1290            else {
1291                $args[] = $arg;
1292            }
1293
1294            if (!empty($aliases[$key])) {
1295                $alias = $aliases[$key];
1296                $args[$alias] = $args[$key];
1297            }
1298        }
1299
1300        return $args;
1301    }
1302
1303    /**
1304     * Safe password prompt for command line
1305     * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
1306     *
1307     * @param string $prompt Prompt text
1308     *
1309     * @return string Password
1310     */
1311    public static function prompt_silent($prompt = "Password:")
1312    {
1313        if (preg_match('/^win/i', PHP_OS)) {
1314            $vbscript  = sys_get_temp_dir() . 'prompt_password.vbs';
1315            $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
1316            file_put_contents($vbscript, $vbcontent);
1317
1318            $command  = "cscript //nologo " . escapeshellarg($vbscript);
1319            $password = rtrim(shell_exec($command));
1320            unlink($vbscript);
1321
1322            return $password;
1323        }
1324
1325        $command = "/usr/bin/env bash -c 'echo OK'";
1326
1327        if (rtrim(shell_exec($command)) !== 'OK') {
1328            echo $prompt;
1329            $pass = trim(fgets(STDIN));
1330            echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
1331
1332            return $pass;
1333        }
1334
1335        $command  = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
1336        $password = rtrim(shell_exec($command));
1337        echo "\n";
1338
1339        return $password;
1340    }
1341
1342    /**
1343     * Find out if the string content means true or false
1344     *
1345     * @param string $str Input value
1346     *
1347     * @return bool Boolean value
1348     */
1349    public static function get_boolean($str)
1350    {
1351        $str = strtolower($str);
1352
1353        return !in_array($str, ['false', '0', 'no', 'off', 'nein', ''], true);
1354    }
1355
1356    /**
1357     * OS-dependent absolute path detection
1358     *
1359     * @param string $path File path
1360     *
1361     * @return bool True if the path is absolute, False otherwise
1362     */
1363    public static function is_absolute_path($path)
1364    {
1365        if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
1366            return (bool) preg_match('!^[a-z]:[\\\\/]!i', $path);
1367        }
1368
1369        return isset($path[0]) && $path[0] == '/';
1370    }
1371
1372    /**
1373     * Resolve relative URL
1374     *
1375     * @param string $url Relative URL
1376     *
1377     * @return string Absolute URL
1378     */
1379    public static function resolve_url($url)
1380    {
1381        // prepend protocol://hostname:port
1382        if (!preg_match('|^https?://|', $url)) {
1383            $schema       = 'http';
1384            $default_port = 80;
1385
1386            if (self::https_check()) {
1387                $schema       = 'https';
1388                $default_port = 443;
1389            }
1390
1391            $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
1392            $port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : null;
1393
1394            $prefix = $schema . '://' . preg_replace('/:\d+$/', '', $host);
1395            if ($port != $default_port && $port != 80) {
1396                $prefix .= ':' . $port;
1397            }
1398
1399            $url = $prefix . ($url[0] == '/' ? '' : '/') . $url;
1400        }
1401
1402        return $url;
1403    }
1404
1405    /**
1406     * Generate a random string
1407     *
1408     * @param int  $length String length
1409     * @param bool $raw    Return RAW data instead of ascii
1410     *
1411     * @return string The generated random string
1412     */
1413    public static function random_bytes($length, $raw = false)
1414    {
1415        $hextab  = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1416        $tabsize = strlen($hextab);
1417
1418        // Use PHP7 true random generator
1419        if ($raw && function_exists('random_bytes')) {
1420            return random_bytes($length);
1421        }
1422
1423        if (!$raw && function_exists('random_int')) {
1424            $result = '';
1425            while ($length-- > 0) {
1426                $result .= $hextab[random_int(0, $tabsize - 1)];
1427            }
1428
1429            return $result;
1430        }
1431
1432        $random = openssl_random_pseudo_bytes($length);
1433
1434        if ($random === false && $length > 0) {
1435            throw new Exception("Failed to get random bytes");
1436        }
1437
1438        if (!$raw) {
1439            for ($x = 0; $x < $length; $x++) {
1440                $random[$x] = $hextab[ord($random[$x]) % $tabsize];
1441            }
1442        }
1443
1444        return $random;
1445    }
1446
1447    /**
1448     * Convert binary data into readable form (containing a-zA-Z0-9 characters)
1449     *
1450     * @param string $input Binary input
1451     *
1452     * @return string Readable output (Base62)
1453     * @deprecated since 1.3.1
1454     */
1455    public static function bin2ascii($input)
1456    {
1457        $hextab = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1458        $result = '';
1459
1460        for ($x = 0; $x < strlen($input); $x++) {
1461            $result .= $hextab[ord($input[$x]) % 62];
1462        }
1463
1464        return $result;
1465    }
1466
1467    /**
1468     * Format current date according to specified format.
1469     * This method supports microseconds (u).
1470     *
1471     * @param string $format Date format (default: 'd-M-Y H:i:s O')
1472     *
1473     * @return string Formatted date
1474     */
1475    public static function date_format($format = null)
1476    {
1477        if (empty($format)) {
1478            $format = 'd-M-Y H:i:s O';
1479        }
1480
1481        if (strpos($format, 'u') !== false) {
1482            $dt  = number_format(microtime(true), 6, '.', '');
1483            $dt .=  '.' . date_default_timezone_get();
1484
1485            if ($date = date_create_from_format('U.u.e', $dt)) {
1486                return $date->format($format);
1487            }
1488        }
1489
1490        return date($format);
1491    }
1492
1493    /**
1494     * Parses socket options and returns options for specified hostname.
1495     *
1496     * @param array  &$options Configured socket options
1497     * @param string $host     Hostname
1498     */
1499    public static function parse_socket_options(&$options, $host = null)
1500    {
1501        if (empty($host) || empty($options)) {
1502            return;
1503        }
1504
1505        // get rid of schema and port from the hostname
1506        $host_url = parse_url($host);
1507        if (isset($host_url['host'])) {
1508            $host = $host_url['host'];
1509        }
1510
1511        // find per-host options
1512        if ($host && array_key_exists($host, $options)) {
1513            $options = $options[$host];
1514        }
1515    }
1516
1517    /**
1518     * Get maximum upload size
1519     *
1520     * @return int Maximum size in bytes
1521     */
1522    public static function max_upload_size()
1523    {
1524        // find max filesize value
1525        $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
1526        $max_postsize = parse_bytes(ini_get('post_max_size'));
1527
1528        if ($max_postsize && $max_postsize < $max_filesize) {
1529            $max_filesize = $max_postsize;
1530        }
1531
1532        return $max_filesize;
1533    }
1534
1535    /**
1536     * Detect and log last PREG operation error
1537     *
1538     * @param array $error     Error data (line, file, code, message)
1539     * @param bool  $terminate Stop script execution
1540     *
1541     * @return bool True on error, False otherwise
1542     */
1543    public static function preg_error($error = [], $terminate = false)
1544    {
1545        if (($preg_error = preg_last_error()) != PREG_NO_ERROR) {
1546            $errstr = "PCRE Error: $preg_error.";
1547
1548            if ($preg_error == PREG_BACKTRACK_LIMIT_ERROR) {
1549                $errstr .= " Consider raising pcre.backtrack_limit!";
1550            }
1551            if ($preg_error == PREG_RECURSION_LIMIT_ERROR) {
1552                $errstr .= " Consider raising pcre.recursion_limit!";
1553            }
1554
1555            $error = array_merge(['code' => 620, 'line' => __LINE__, 'file' => __FILE__], $error);
1556
1557            if (!empty($error['message'])) {
1558                $error['message'] .= ' ' . $errstr;
1559            }
1560            else {
1561                $error['message'] = $errstr;
1562            }
1563
1564            rcube::raise_error($error, true, $terminate);
1565
1566            return true;
1567        }
1568
1569        return false;
1570    }
1571
1572    /**
1573     * Generate a temporary file path in the Roundcube temp directory
1574     *
1575     * @param string $file_name String identifier for the type of temp file
1576     * @param bool   $unique    Generate unique file names based on $file_name
1577     * @param bool   $create    Create the temp file or not
1578     *
1579     * @return string temporary file path
1580     */
1581    public static function temp_filename($file_name, $unique = true, $create = true)
1582    {
1583        $temp_dir = rcube::get_instance()->config->get('temp_dir');
1584
1585        // Fall back to system temp dir if configured dir is not writable
1586        if (!is_writable($temp_dir)) {
1587            $temp_dir = sys_get_temp_dir();
1588        }
1589
1590        // On Windows tempnam() uses only the first three characters of prefix so use uniqid() and manually add the prefix
1591        // Full prefix is required for garbage collection to recognise the file
1592        $temp_file = $unique ? str_replace('.', '', uniqid($file_name, true)) : $file_name;
1593        $temp_path = unslashify($temp_dir) . '/' . RCUBE_TEMP_FILE_PREFIX . $temp_file;
1594
1595        // Sanity check for unique file name
1596        if ($unique && file_exists($temp_path)) {
1597            return self::temp_filename($file_name, $unique, $create);
1598        }
1599
1600        // Create the file to prevent possible race condition like tempnam() does
1601        if ($create) {
1602            touch($temp_path);
1603        }
1604
1605        return $temp_path;
1606    }
1607
1608    /**
1609     * Clean the subject from reply and forward prefix
1610     *
1611     * @param string $subject Subject to clean
1612     * @param string $mode Mode of cleaning : reply, forward or both
1613     *
1614     * @return string Cleaned subject
1615     */
1616    public static function remove_subject_prefix($subject, $mode = 'both')
1617    {
1618        $config = rcmail::get_instance()->config;
1619
1620        // Clean subject prefix for reply, forward or both
1621        if ($mode == 'both') {
1622            $reply_prefixes = $config->get('subject_reply_prefixes', ['Re:']);
1623            $forward_prefixes = $config->get('subject_forward_prefixes', ['Fwd:', 'Fw:']);
1624            $prefixes = array_merge($reply_prefixes, $forward_prefixes);
1625        }
1626        else if ($mode == 'reply') {
1627            $prefixes = $config->get('subject_reply_prefixes', ['Re:']);
1628            // replace (was: ...) (#1489375)
1629            $subject = preg_replace('/\s*\([wW]as:[^\)]+\)\s*$/', '', $subject);
1630        }
1631        else if ($mode == 'forward') {
1632            $prefixes = $config->get('subject_forward_prefixes', ['Fwd:', 'Fw:']);
1633        }
1634
1635        // replace Re:, Re[x]:, Re-x (#1490497)
1636        $pieces = array_map(function($prefix) {
1637            $prefix = strtolower(str_replace(':', '', $prefix));
1638            return "$prefix:|$prefix\[\d\]:|$prefix-\d:";
1639        }, $prefixes);
1640        $pattern = '/^('.implode('|', $pieces).')\s*/i';
1641        do {
1642            $subject = preg_replace($pattern, '', $subject, -1, $count);
1643        }
1644        while ($count);
1645
1646        return trim($subject);
1647    }
1648}
1649