source: subversion/trunk/roundcubemail/program/include/rcube_utils.php @ 6140

Last change on this file since 6140 was 6140, checked in by netbit, 13 months ago
  • Fix the idn_convert() function call that was preventing the login with the "%s" replacement variable in config.
  • Property svn:keywords set to Id Author Date
File size: 24.7 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_utils.php                                       |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2008-2012, The Roundcube Dev Team                       |
9 | Copyright (C) 2011-2012, Kolab Systems AG                             |
10 |                                                                       |
11 | Licensed under the GNU General Public License version 3 or            |
12 | any later version with exceptions for skins & plugins.                |
13 | See the README file for a full license statement.                     |
14 |                                                                       |
15 | PURPOSE:                                                              |
16 |   Utility class providing common functions                            |
17 +-----------------------------------------------------------------------+
18 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
19 | Author: Aleksander Machniak <alec@alec.pl>                            |
20 +-----------------------------------------------------------------------+
21
22 $Id$
23
24*/
25
26
27/**
28 * Utility class providing common functions
29 *
30 * @package Core
31 */
32class rcube_utils
33{
34    // define constants for input reading
35    const INPUT_GET  = 0x0101;
36    const INPUT_POST = 0x0102;
37    const INPUT_GPC  = 0x0103;
38
39    /**
40     * Helper method to set a cookie with the current path and host settings
41     *
42     * @param string Cookie name
43     * @param string Cookie value
44     * @param string Expiration time
45     */
46    public static function setcookie($name, $value, $exp = 0)
47    {
48        if (headers_sent()) {
49            return;
50        }
51
52        $cookie = session_get_cookie_params();
53        $secure = self::https_check();
54
55        setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'], $secure, true);
56    }
57
58    /**
59     * E-mail address validation.
60     *
61     * @param string $email Email address
62     * @param boolean $dns_check True to check dns
63     *
64     * @return boolean True on success, False if address is invalid
65     */
66    public static function check_email($email, $dns_check=true)
67    {
68        // Check for invalid characters
69        if (preg_match('/[\x00-\x1F\x7F-\xFF]/', $email)) {
70            return false;
71        }
72
73        // Check for length limit specified by RFC 5321 (#1486453)
74        if (strlen($email) > 254) {
75            return false;
76        }
77
78        $email_array = explode('@', $email);
79
80        // Check that there's one @ symbol
81        if (count($email_array) < 2) {
82            return false;
83        }
84
85        $domain_part = array_pop($email_array);
86        $local_part  = implode('@', $email_array);
87
88        // from PEAR::Validate
89        $regexp = '&^(?:
90                ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")|                                         #1 quoted name
91                ([-\w!\#\$%\&\'*+~/^`|{}=]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}=]+)*))  #2 OR dot-atom (RFC5322)
92                $&xi';
93
94        if (!preg_match($regexp, $local_part)) {
95            return false;
96        }
97
98        // Check domain part
99        if (preg_match('/^\[*(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}\]*$/', $domain_part)) {
100            return true; // IP address
101        }
102        else {
103            // If not an IP address
104            $domain_array = explode('.', $domain_part);
105            // Not enough parts to be a valid domain
106            if (sizeof($domain_array) < 2) {
107                return false;
108            }
109
110            foreach ($domain_array as $part) {
111                if (!preg_match('/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]))$/', $part)) {
112                    return false;
113                }
114            }
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)
134            if (getmxrr($domain_part, $mx_records)) {
135                return true;
136            }
137
138            // find any DNS record
139            if (checkdnsrr($domain_part, 'ANY')) {
140                return true;
141            }
142        }
143
144        return false;
145    }
146
147    /**
148     * Check whether the HTTP referer matches the current request
149     *
150     * @return boolean True if referer is the same host+path, false if not
151     */
152    public static function check_referer()
153    {
154        $uri = parse_url($_SERVER['REQUEST_URI']);
155        $referer = parse_url(rcube_request_header('Referer'));
156        return $referer['host'] == rcube_request_header('Host') && $referer['path'] == $uri['path'];
157    }
158
159
160    /**
161     * Replacing specials characters to a specific encoding type
162     *
163     * @param  string  Input string
164     * @param  string  Encoding type: text|html|xml|js|url
165     * @param  string  Replace mode for tags: show|replace|remove
166     * @param  boolean Convert newlines
167     *
168     * @return string  The quoted string
169     */
170    public static function rep_specialchars_output($str, $enctype = '', $mode = '', $newlines = true)
171    {
172        static $html_encode_arr = false;
173        static $js_rep_table = false;
174        static $xml_rep_table = false;
175
176        // encode for HTML output
177        if ($enctype == 'html') {
178            if (!$html_encode_arr) {
179                $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
180                unset($html_encode_arr['?']);
181            }
182
183            $encode_arr = $html_encode_arr;
184
185            // don't replace quotes and html tags
186            if ($mode == 'show' || $mode == '') {
187                $ltpos = strpos($str, '<');
188                if ($ltpos !== false && strpos($str, '>', $ltpos) !== false) {
189                    unset($encode_arr['"']);
190                    unset($encode_arr['<']);
191                    unset($encode_arr['>']);
192                    unset($encode_arr['&']);
193                }
194            }
195            else if ($mode == 'remove') {
196                $str = strip_tags($str);
197            }
198
199            $out = strtr($str, $encode_arr);
200
201            // avoid douple quotation of &
202            $out = preg_replace('/&amp;([A-Za-z]{2,6}|#[0-9]{2,4});/', '&\\1;', $out);
203
204            return $newlines ? nl2br($out) : $out;
205        }
206
207        // if the replace tables for XML and JS are not yet defined
208        if ($js_rep_table === false) {
209            $js_rep_table = $xml_rep_table = array();
210            $xml_rep_table['&'] = '&amp;';
211
212            // can be increased to support more charsets
213            for ($c=160; $c<256; $c++) {
214                $xml_rep_table[chr($c)] = "&#$c;";
215            }
216
217            $xml_rep_table['"'] = '&quot;';
218            $js_rep_table['"']  = '\\"';
219            $js_rep_table["'"]  = "\\'";
220            $js_rep_table["\\"] = "\\\\";
221            // Unicode line and paragraph separators (#1486310)
222            $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A8))] = '&#8232;';
223            $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A9))] = '&#8233;';
224        }
225
226        // encode for javascript use
227        if ($enctype == 'js') {
228            return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
229        }
230
231        // encode for plaintext
232        if ($enctype == 'text') {
233            return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
234        }
235
236        if ($enctype == 'url') {
237            return rawurlencode($str);
238        }
239
240        // encode for XML
241        if ($enctype == 'xml') {
242            return strtr($str, $xml_rep_table);
243        }
244
245        // no encoding given -> return original string
246        return $str;
247    }
248
249
250    /**
251     * Read input value and convert it for internal use
252     * Performs stripslashes() and charset conversion if necessary
253     *
254     * @param  string   Field name to read
255     * @param  int      Source to get value from (GPC)
256     * @param  boolean  Allow HTML tags in field value
257     * @param  string   Charset to convert into
258     *
259     * @return string   Field value or NULL if not available
260     */
261    public static function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
262    {
263        $value = NULL;
264
265        if ($source == self::INPUT_GET) {
266            if (isset($_GET[$fname])) {
267                $value = $_GET[$fname];
268            }
269        }
270        else if ($source == self::INPUT_POST) {
271            if (isset($_POST[$fname])) {
272                $value = $_POST[$fname];
273            }
274        }
275        else if ($source == self::INPUT_GPC) {
276            if (isset($_POST[$fname])) {
277                $value = $_POST[$fname];
278            }
279            else if (isset($_GET[$fname])) {
280                $value = $_GET[$fname];
281            }
282            else if (isset($_COOKIE[$fname])) {
283                $value = $_COOKIE[$fname];
284            }
285        }
286
287        return self::parse_input_value($value, $allow_html, $charset);
288    }
289
290
291    /**
292     * Parse/validate input value. See self::get_input_value()
293     * Performs stripslashes() and charset conversion if necessary
294     *
295     * @param  string   Input value
296     * @param  boolean  Allow HTML tags in field value
297     * @param  string   Charset to convert into
298     *
299     * @return string   Parsed value
300     */
301    public static function parse_input_value($value, $allow_html=FALSE, $charset=NULL)
302    {
303        global $OUTPUT;
304
305        if (empty($value)) {
306            return $value;
307        }
308
309        if (is_array($value)) {
310            foreach ($value as $idx => $val) {
311                $value[$idx] = self::parse_input_value($val, $allow_html, $charset);
312            }
313            return $value;
314        }
315
316        // strip single quotes if magic_quotes_sybase is enabled
317        if (ini_get('magic_quotes_sybase')) {
318            $value = str_replace("''", "'", $value);
319        }
320        // strip slashes if magic_quotes enabled
321        else if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
322            $value = stripslashes($value);
323        }
324
325        // remove HTML tags if not allowed
326        if (!$allow_html) {
327            $value = strip_tags($value);
328        }
329
330        $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
331
332        // remove invalid characters (#1488124)
333        if ($output_charset == 'UTF-8') {
334            $value = rcube_charset::clean($value);
335        }
336
337        // convert to internal charset
338        if ($charset && $output_charset) {
339            $value = rcube_charset::convert($value, $output_charset, $charset);
340        }
341
342        return $value;
343    }
344
345
346    /**
347     * Convert array of request parameters (prefixed with _)
348     * to a regular array with non-prefixed keys.
349     *
350     * @param int    $mode   Source to get value from (GPC)
351     * @param string $ignore PCRE expression to skip parameters by name
352     *
353     * @return array Hash array with all request parameters
354     */
355    public static function request2param($mode = null, $ignore = 'task|action')
356    {
357        $out = array();
358        $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
359
360        foreach ($src as $key => $value) {
361            $fname = $key[0] == '_' ? substr($key, 1) : $key;
362            if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
363                $out[$fname] = self::get_input_value($key, $mode);
364            }
365        }
366
367        return $out;
368    }
369
370
371    /**
372     * Convert the given string into a valid HTML identifier
373     * Same functionality as done in app.js with rcube_webmail.html_identifier()
374     */
375    public static function html_identifier($str, $encode=false)
376    {
377        if ($encode) {
378            return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
379        }
380        else {
381            return asciiwords($str, true, '_');
382        }
383    }
384
385
386    /**
387     * Create an edit field for inclusion on a form
388     *
389     * @param string col field name
390     * @param string value field value
391     * @param array attrib HTML element attributes for field
392     * @param string type HTML element type (default 'text')
393     *
394     * @return string HTML field definition
395     */
396    public static function get_edit_field($col, $value, $attrib, $type = 'text')
397    {
398        static $colcounts = array();
399
400        $fname = '_'.$col;
401        $attrib['name']  = $fname . ($attrib['array'] ? '[]' : '');
402        $attrib['class'] = trim($attrib['class'] . ' ff_' . $col);
403
404        if ($type == 'checkbox') {
405            $attrib['value'] = '1';
406            $input = new html_checkbox($attrib);
407        }
408        else if ($type == 'textarea') {
409            $attrib['cols'] = $attrib['size'];
410            $input = new html_textarea($attrib);
411        }
412        else if ($type == 'select') {
413            $input = new html_select($attrib);
414            $input->add('---', '');
415            $input->add(array_values($attrib['options']), array_keys($attrib['options']));
416        }
417        else if ($attrib['type'] == 'password') {
418            $input = new html_passwordfield($attrib);
419        }
420        else {
421            if ($attrib['type'] != 'text' && $attrib['type'] != 'hidden') {
422                $attrib['type'] = 'text';
423            }
424            $input = new html_inputfield($attrib);
425        }
426
427        // use value from post
428        if (isset($_POST[$fname])) {
429            $postvalue = self::get_input_value($fname, self::INPUT_POST, true);
430            $value = $attrib['array'] ? $postvalue[intval($colcounts[$col]++)] : $postvalue;
431        }
432
433        $out = $input->show($value);
434
435        return $out;
436    }
437
438
439    /**
440     * Replace all css definitions with #container [def]
441     * and remove css-inlined scripting
442     *
443     * @param string CSS source code
444     * @param string Container ID to use as prefix
445     *
446     * @return string Modified CSS source
447     */
448    public static function mod_css_styles($source, $container_id, $allow_remote=false)
449    {
450        $last_pos = 0;
451        $replacements = new rcube_string_replacer;
452
453        // ignore the whole block if evil styles are detected
454        $source   = self::xss_entity_decode($source);
455        $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
456        $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\(' : '');
457        if (preg_match("/$evilexpr/i", $stripped)) {
458            return '/* evil! */';
459        }
460
461        // cut out all contents between { and }
462        while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
463            $styles = substr($source, $pos+1, $pos2-($pos+1));
464
465            // check every line of a style block...
466            if ($allow_remote) {
467                $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
468                foreach ($a_styles as $line) {
469                    $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
470                    // ... and only allow strict url() values
471                    $regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
472                    if (stripos($stripped, 'url(') && !preg_match($regexp, $line)) {
473                        $a_styles = array('/* evil! */');
474                        break;
475                    }
476                }
477                $styles = join(";\n", $a_styles);
478            }
479
480            $key = $replacements->add($styles);
481            $source = substr($source, 0, $pos+1)
482                . $replacements->get_replacement($key)
483                . substr($source, $pos2, strlen($source)-$pos2);
484            $last_pos = $pos+2;
485        }
486
487        // remove html comments and add #container to each tag selector.
488        // also replace body definition because we also stripped off the <body> tag
489        $styles = preg_replace(
490            array(
491                '/(^\s*<!--)|(-->\s*$)/',
492                '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
493                '/'.preg_quote($container_id, '/').'\s+body/i',
494            ),
495            array(
496                '',
497                "\\1#$container_id \\2",
498                $container_id,
499            ),
500            $source);
501
502        // put block contents back in
503        $styles = $replacements->resolve($styles);
504
505        return $styles;
506    }
507
508
509    /**
510     * Generate CSS classes from mimetype and filename extension
511     *
512     * @param string $mimetype  Mimetype
513     * @param string $filename  Filename
514     *
515     * @return string CSS classes separated by space
516     */
517    public static function file2class($mimetype, $filename)
518    {
519        list($primary, $secondary) = explode('/', $mimetype);
520
521        $classes = array($primary ? $primary : 'unknown');
522        if ($secondary) {
523            $classes[] = $secondary;
524        }
525        if (preg_match('/\.([a-z0-9]+)$/i', $filename, $m)) {
526            $classes[] = $m[1];
527        }
528
529        return strtolower(join(" ", $classes));
530    }
531
532
533    /**
534     * Decode escaped entities used by known XSS exploits.
535     * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
536     *
537     * @param string CSS content to decode
538     *
539     * @return string Decoded string
540     */
541    public static function xss_entity_decode($content)
542    {
543        $out = html_entity_decode(html_entity_decode($content));
544        $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
545            array(self, 'xss_entity_decode_callback'), $out);
546        $out = preg_replace('#/\*.*\*/#Ums', '', $out);
547
548        return $out;
549    }
550
551
552    /**
553     * preg_replace_callback callback for xss_entity_decode
554     *
555     * @param array $matches Result from preg_replace_callback
556     *
557     * @return string Decoded entity
558     */
559    public static function xss_entity_decode_callback($matches)
560    {
561        return chr(hexdec($matches[1]));
562    }
563
564
565    /**
566     * Check if we can process not exceeding memory_limit
567     *
568     * @param integer Required amount of memory
569     *
570     * @return boolean True if memory won't be exceeded, False otherwise
571     */
572    public static function mem_check($need)
573    {
574        $mem_limit = parse_bytes(ini_get('memory_limit'));
575        $memory    = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
576
577        return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
578    }
579
580
581    /**
582     * Check if working in SSL mode
583     *
584     * @param integer $port      HTTPS port number
585     * @param boolean $use_https Enables 'use_https' option checking
586     *
587     * @return boolean
588     */
589    public static function https_check($port=null, $use_https=true)
590    {
591        global $RCMAIL;
592
593        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
594            return true;
595        }
596        if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
597            return true;
598        }
599        if ($port && $_SERVER['SERVER_PORT'] == $port) {
600            return true;
601        }
602        if ($use_https && isset($RCMAIL) && $RCMAIL->config->get('use_https')) {
603            return true;
604        }
605
606        return false;
607    }
608
609
610    /**
611     * Replaces hostname variables.
612     *
613     * @param string $name Hostname
614     * @param string $host Optional IMAP hostname
615     *
616     * @return string Hostname
617     */
618    public static function parse_host($name, $host = '')
619    {
620        // %n - host
621        $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
622        // %d - domain name without first part, e.g. %n=mail.domain.tld, %d=domain.tld
623        $d = preg_replace('/^[^\.]+\./', '', $n);
624        // %h - IMAP host
625        $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
626        // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
627        $z = preg_replace('/^[^\.]+\./', '', $h);
628        // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
629        if (strpos($name, '%s') !== false) {
630            $user_email = self::get_input_value('_user', self::INPUT_POST);
631            $user_email = rcube_utils::idn_convert($user_email, true);
632            $matches    = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
633            if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
634                return false;
635            }
636        }
637
638        $name = str_replace(array('%n', '%d', '%h', '%z', '%s'), array($n, $d, $h, $z, $s[2]), $name);
639        return $name;
640    }
641
642
643    /**
644     * Returns remote IP address and forwarded addresses if found
645     *
646     * @return string Remote IP address(es)
647     */
648    public static function remote_ip()
649    {
650        $address = $_SERVER['REMOTE_ADDR'];
651
652        // append the NGINX X-Real-IP header, if set
653        if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
654            $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
655        }
656        // append the X-Forwarded-For header, if set
657        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
658            $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
659        }
660
661        if (!empty($remote_ip)) {
662            $address .= '(' . implode(',', $remote_ip) . ')';
663        }
664
665        return $address;
666    }
667
668
669    /**
670     * Read a specific HTTP request header.
671     *
672     * @param  string $name Header name
673     *
674     * @return mixed  Header value or null if not available
675     */
676    public static function request_header($name)
677    {
678        if (function_exists('getallheaders')) {
679            $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
680            $key  = strtoupper($name);
681        }
682        else {
683            $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
684            $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
685        }
686
687        return $hdrs[$key];
688    }
689
690    /**
691     * Explode quoted string
692     *
693     * @param string Delimiter expression string for preg_match()
694     * @param string Input string
695     *
696     * @return array String items
697     */
698    public static function explode_quoted_string($delimiter, $string)
699    {
700        $result = array();
701        $strlen = strlen($string);
702
703        for ($q=$p=$i=0; $i < $strlen; $i++) {
704            if ($string[$i] == "\"" && $string[$i-1] != "\\") {
705                $q = $q ? false : true;
706            }
707            else if (!$q && preg_match("/$delimiter/", $string[$i])) {
708                $result[] = substr($string, $p, $i - $p);
709                $p = $i + 1;
710            }
711        }
712
713        $result[] = substr($string, $p);
714
715        return $result;
716    }
717
718
719    /**
720     * Improved equivalent to strtotime()
721     *
722     * @param string $date  Date string
723     *
724     * @return int Unix timestamp
725     */
726    public static function strtotime($date)
727    {
728        // check for MS Outlook vCard date format YYYYMMDD
729        if (preg_match('/^([12][90]\d\d)([01]\d)(\d\d)$/', trim($date), $matches)) {
730            return mktime(0,0,0, intval($matches[2]), intval($matches[3]), intval($matches[1]));
731        }
732        else if (is_numeric($date)) {
733            return $date;
734        }
735
736        // support non-standard "GMTXXXX" literal
737        $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
738
739        // if date parsing fails, we have a date in non-rfc format.
740        // remove token from the end and try again
741        while ((($ts = @strtotime($date)) === false) || ($ts < 0)) {
742            $d = explode(' ', $date);
743            array_pop($d);
744            if (!$d) {
745                break;
746            }
747            $date = implode(' ', $d);
748        }
749
750        return $ts;
751    }
752
753
754    /*
755     * Idn_to_ascii wrapper.
756     * Intl/Idn modules version of this function doesn't work with e-mail address
757     */
758    public static function idn_to_ascii($str)
759    {
760        return self::idn_convert($str, true);
761    }
762
763
764    /*
765     * Idn_to_ascii wrapper.
766     * Intl/Idn modules version of this function doesn't work with e-mail address
767     */
768    public static function idn_to_utf8($str)
769    {
770        return self::idn_convert($str, false);
771    }
772
773
774    public static function idn_convert($input, $is_utf=false)
775    {
776        if ($at = strpos($input, '@')) {
777            $user   = substr($input, 0, $at);
778            $domain = substr($input, $at+1);
779        }
780        else {
781            $domain = $input;
782        }
783
784        $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
785
786        if ($domain === false) {
787            return '';
788        }
789
790        return $at ? $user . '@' . $domain : $domain;
791    }
792
793}
Note: See TracBrowser for help on using the repository browser.