source: github/program/include/rcube_utils.php @ 09e5fc9

Last change on this file since 09e5fc9 was 09e5fc9, checked in by Aleksander Machniak <alec@…>, 10 months ago

Small performance improvement: use cookie 'secure' parameter if enabled

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