source: subversion/trunk/roundcubemail/program/include/rcube_vcard.php @ 4765

Last change on this file since 4765 was 4765, checked in by thomasb, 2 years ago

Correctly handle empty contact names when importing

  • Property svn:keywords set to Id
File size: 22.1 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_vcard.php                                       |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2008-2011, The Roundcube Dev Team                       |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Logical representation of a vcard address record                    |
13 +-----------------------------------------------------------------------+
14 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
15 +-----------------------------------------------------------------------+
16
17 $Id$
18
19*/
20
21
22/**
23 * Logical representation of a vcard-based address record
24 * Provides functions to parse and export vCard data format
25 *
26 * @package    Addressbook
27 * @author     Thomas Bruederli <roundcube@gmail.com>
28 */
29class rcube_vcard
30{
31  private static $values_decoded = false;
32  private $raw = array(
33    'FN' => array(),
34    'N' => array(array('','','','','')),
35  );
36  private $fieldmap = array(
37    'phone'    => 'TEL',
38    'birthday' => 'BDAY',
39    'website'  => 'URL',
40    'notes'    => 'NOTE',
41    'email'    => 'EMAIL',
42    'address'  => 'ADR',
43    'jobtitle' => 'TITLE',
44    'gender'      => 'X-GENDER',
45    'maidenname'  => 'X-MAIDENNAME',
46    'anniversary' => 'X-ANNIVERSARY',
47    'assistant'   => 'X-ASSISTANT',
48    'manager'     => 'X-MANAGER',
49    'spouse'      => 'X-SPOUSE',
50  );
51  private $typemap = array('iPhone' => 'mobile', 'CELL' => 'mobile');
52  private $phonetypemap = array('HOME1' => 'HOME', 'BUSINESS1' => 'WORK', 'BUSINESS2' => 'WORK2', 'WORKFAX' => 'BUSINESSFAX');
53  private $addresstypemap = array('BUSINESS' => 'WORK');
54  private $immap = array('X-JABBER' => 'jabber', 'X-ICQ' => 'icq', 'X-MSN' => 'msn', 'X-AIM' => 'aim', 'X-YAHOO' => 'yahoo', 'X-SKYPE' => 'skype', 'X-SKYPE-USERNAME' => 'skype');
55
56  public $business = false;
57  public $displayname;
58  public $surname;
59  public $firstname;
60  public $middlename;
61  public $nickname;
62  public $organization;
63  public $notes;
64  public $email = array();
65
66
67  /**
68   * Constructor
69   */
70  public function __construct($vcard = null, $charset = RCMAIL_CHARSET, $detect = false)
71  {
72    if (!empty($vcard))
73      $this->load($vcard, $charset, $detect);
74  }
75
76
77  /**
78   * Load record from (internal, unfolded) vcard 3.0 format
79   *
80   * @param string vCard string to parse
81   * @param string Charset of string values
82   * @param boolean True if loading a 'foreign' vcard and extra heuristics for charset detection is required
83   */
84  public function load($vcard, $charset = RCMAIL_CHARSET, $detect = false)
85  {
86    self::$values_decoded = false;
87    $this->raw = self::vcard_decode($vcard);
88
89    // resolve charset parameters
90    if ($charset == null) {
91      $this->raw = self::charset_convert($this->raw);
92    }
93    // vcard has encoded values and charset should be detected
94    else if ($detect && self::$values_decoded &&
95      ($detected_charset = self::detect_encoding(self::vcard_encode($this->raw))) && $detected_charset != RCMAIL_CHARSET) {
96        $this->raw = self::charset_convert($this->raw, $detected_charset);
97    }
98   
99    // consider FN empty if the same as the primary e-mail address
100    if ($this->raw['FN'][0][0] == $this->raw['EMAIL'][0][0])
101      $this->raw['FN'][0][0] = '';
102
103    // find well-known address fields
104    $this->displayname = $this->raw['FN'][0][0];
105    $this->surname = $this->raw['N'][0][0];
106    $this->firstname = $this->raw['N'][0][1];
107    $this->middlename = $this->raw['N'][0][2];
108    $this->nickname = $this->raw['NICKNAME'][0][0];
109    $this->organization = $this->raw['ORG'][0][0];
110    $this->business = ($this->raw['X-ABSHOWAS'][0][0] == 'COMPANY') || (join('', (array)$this->raw['N'][0]) == '' && !empty($this->organization));
111
112    foreach ((array)$this->raw['EMAIL'] as $i => $raw_email)
113      $this->email[$i] = is_array($raw_email) ? $raw_email[0] : $raw_email;
114
115    // make the pref e-mail address the first entry in $this->email
116    $pref_index = $this->get_type_index('EMAIL', 'pref');
117    if ($pref_index > 0) {
118      $tmp = $this->email[0];
119      $this->email[0] = $this->email[$pref_index];
120      $this->email[$pref_index] = $tmp;
121    }
122  }
123
124
125  /**
126   * Return vCard data as associative array to be unsed in Roundcube address books
127   *
128   * @return array Hash array with key-value pairs
129   */
130  public function get_assoc()
131  {
132    $out = array('name' => $this->displayname);
133    $typemap = $this->typemap;
134
135    // copy name fields to output array
136    foreach (array('firstname','surname','middlename','nickname','organization') as $col) {
137      if (strlen($this->$col))
138        $out[$col] = $this->$col;
139    }
140
141    if ($this->raw['N'][0][3])
142      $out['prefix'] = $this->raw['N'][0][3];
143    if ($this->raw['N'][0][4])
144      $out['suffix'] = $this->raw['N'][0][4];
145
146    // convert from raw vcard data into associative data for Roundcube
147    foreach (array_flip($this->fieldmap) as $tag => $col) {
148      foreach ((array)$this->raw[$tag] as $i => $raw) {
149        if (is_array($raw)) {
150          $k = -1;
151          $key = $col;
152
153          $subtype = $typemap[$raw['type'][++$k]] ? $typemap[$raw['type'][$k]] : strtolower($raw['type'][$k]);
154          while ($k < count($raw['type']) && ($subtype == 'internet' || $subtype == 'pref'))
155            $subtype = $typemap[$raw['type'][++$k]] ? $typemap[$raw['type'][$k]] : strtolower($raw['type'][$k]);
156
157          // read vcard 2.1 subtype
158          if (!$subtype) {
159            foreach ($raw as $k => $v) {
160              if (!is_numeric($k) && $v === true && !in_array(strtolower($k), array('pref','internet','voice','base64'))) {
161                $subtype = $typemap[$k] ? $typemap[$k] : strtolower($k);
162                break;
163              }
164            }
165          }
166
167          // force subtype if none set
168          if (preg_match('/^(email|phone|address|website)/', $key) && !$subtype)
169            $subtype = 'other';
170
171          if ($subtype)
172            $key .= ':' . $subtype;
173
174          // split ADR values into assoc array
175          if ($tag == 'ADR') {
176            list(,, $value['street'], $value['locality'], $value['region'], $value['zipcode'], $value['country']) = $raw;
177            $out[$key][] = $value;
178          }
179          else
180            $out[$key][] = $raw[0];
181        }
182        else {
183          $out[$col][] = $raw;
184        }
185      }
186    }
187
188    // handle special IM fields as used by Apple
189    foreach ($this->immap as $tag => $type) {
190      foreach ((array)$this->raw[$tag] as $i => $raw) {
191        $out['im:'.$type][] = $raw[0];
192      }
193    }
194
195    // copy photo data
196    if ($this->raw['PHOTO'])
197      $out['photo'] = $this->raw['PHOTO'][0][0];
198
199    return $out;
200  }
201
202
203  /**
204   * Convert the data structure into a vcard 3.0 string
205   */
206  public function export($folded = true)
207  {
208    $vcard = self::vcard_encode($this->raw);
209    return $folded ? self::rfc2425_fold($vcard) : $vcard;
210  }
211
212
213  /**
214   * Clear the given fields in the loaded vcard data
215   *
216   * @param array List of field names to be reset
217   */
218  public function reset($fields = null)
219  {
220    if (!$fields)
221      $fields = array_merge(array_values($this->fieldmap), array_keys($this->immap), array('FN','N','ORG','NICKNAME','EMAIL','ADR','BDAY'));
222
223    foreach ($fields as $f)
224      unset($this->raw[$f]);
225
226    if (!$this->raw['N'])
227      $this->raw['N'] = array(array('','','','',''));
228    if (!$this->raw['FN'])
229      $this->raw['FN'] = array();
230
231    $this->email = array();
232  }
233
234
235  /**
236   * Setter for address record fields
237   *
238   * @param string Field name
239   * @param string Field value
240   * @param string Type/section name
241   */
242  public function set($field, $value, $type = 'HOME')
243  {
244    $field = strtolower($field);
245    $type = strtoupper($type);
246    $typemap = array_flip($this->typemap);
247
248    switch ($field) {
249      case 'name':
250      case 'displayname':
251        $this->raw['FN'][0][0] = $value;
252        break;
253
254      case 'surname':
255        $this->raw['N'][0][0] = $value;
256        break;
257
258      case 'firstname':
259        $this->raw['N'][0][1] = $value;
260        break;
261
262      case 'middlename':
263        $this->raw['N'][0][2] = $value;
264        break;
265
266      case 'prefix':
267        $this->raw['N'][0][3] = $value;
268        break;
269
270      case 'suffix':
271        $this->raw['N'][0][4] = $value;
272        break;
273
274      case 'nickname':
275        $this->raw['NICKNAME'][0][0] = $value;
276        break;
277
278      case 'organization':
279        $this->raw['ORG'][0][0] = $value;
280        break;
281
282      case 'photo':
283        if (strpos($value, 'http:') === 0) {
284            // TODO: fetch file from URL and save it locally?
285            $this->raw['PHOTO'][0] = array(0 => $value, 'URL' => true);
286        }
287        else {
288            $encoded = !preg_match('![^a-z0-9/=+-]!i', $value);
289            $this->raw['PHOTO'][0] = array(0 => $encoded ? $value : base64_encode($value), 'BASE64' => true);
290        }
291        break;
292
293      case 'email':
294        $this->raw['EMAIL'][] = array(0 => $value, 'type' => array_filter(array('INTERNET', $type)));
295        $this->email[] = $value;
296        break;
297
298      case 'im':
299        // save IM subtypes into extension fields
300        $typemap = array_flip($this->immap);
301        if ($field = $typemap[strtolower($type)])
302          $this->raw[$field][] = array(0 => $value);
303        break;
304
305      case 'birthday':
306        if ($val = rcube_strtotime($value))
307          $this->raw['BDAY'][] = array(0 => date('Y-m-d', $val), 'value' => array('date'));
308        break;
309
310      case 'address':
311        if ($this->addresstypemap[$type])
312          $type = $this->addresstypemap[$type];
313
314        $value = $value[0] ? $value : array('', '', $value['street'], $value['locality'], $value['region'], $value['zipcode'], $value['country']);
315
316        // fall through if not empty
317        if (!strlen(join('', $value)))
318          break;
319
320      default:
321        if ($field == 'phone' && $this->phonetypemap[$type])
322          $type = $this->phonetypemap[$type];
323
324        if (($tag = $this->fieldmap[$field]) && (is_array($value) || strlen($value))) {
325          $index = count($this->raw[$tag]);
326          $this->raw[$tag][$index] = (array)$value;
327          if ($type)
328            $this->raw[$tag][$index]['type'] = array(($typemap[$type] ? $typemap[$type] : $type));
329        }
330        break;
331    }
332  }
333
334
335  /**
336   * Find index with the '$type' attribute
337   *
338   * @param string Field name
339   * @return int Field index having $type set
340   */
341  private function get_type_index($field, $type = 'pref')
342  {
343    $result = 0;
344    if ($this->raw[$field]) {
345      foreach ($this->raw[$field] as $i => $data) {
346        if (is_array($data['type']) && in_array_nocase('pref', $data['type']))
347          $result = $i;
348      }
349    }
350
351    return $result;
352  }
353
354
355  /**
356   * Convert a whole vcard (array) to UTF-8.
357   * If $force_charset is null, each member value that has a charset parameter will be converted
358   */
359  private static function charset_convert($card, $force_charset = null)
360  {
361    foreach ($card as $key => $node) {
362      foreach ($node as $i => $subnode) {
363        if (is_array($subnode) && (($charset = $force_charset) || ($subnode['charset'] && ($charset = $subnode['charset'][0])))) {
364          foreach ($subnode as $j => $value) {
365            if (is_numeric($j) && is_string($value))
366              $card[$key][$i][$j] = rcube_charset_convert($value, $charset);
367          }
368          unset($card[$key][$i]['charset']);
369        }
370      }
371    }
372
373    return $card;
374  }
375
376
377  /**
378   * Factory method to import a vcard file
379   *
380   * @param string vCard file content
381   * @return array List of rcube_vcard objects
382   */
383  public static function import($data)
384  {
385    $out = array();
386
387    // check if charsets are specified (usually vcard version < 3.0 but this is not reliable)
388    if (preg_match('/charset=/i', substr($data, 0, 2048)))
389      $charset = null;
390    // detect charset and convert to utf-8
391    else if (($charset = self::detect_encoding($data)) && $charset != RCMAIL_CHARSET) {
392      $data = rcube_charset_convert($data, $charset);
393      $data = preg_replace(array('/^[\xFE\xFF]{2}/', '/^\xEF\xBB\xBF/', '/^\x00+/'), '', $data); // also remove BOM
394      $charset = RCMAIL_CHARSET;
395    }
396
397    $vcard_block = '';
398    $in_vcard_block = false;
399
400    foreach (preg_split("/[\r\n]+/", $data) as $i => $line) {
401      if ($in_vcard_block && !empty($line))
402        $vcard_block .= $line . "\n";
403
404      $line = trim($line);
405
406      if (preg_match('/^END:VCARD$/i', $line)) {
407        // parse vcard
408        $obj = new rcube_vcard(self::cleanup($vcard_block), $charset, true);
409        if (!empty($obj->displayname) || !empty($obj->email))
410          $out[] = $obj;
411
412        $in_vcard_block = false;
413      }
414      else if (preg_match('/^BEGIN:VCARD$/i', $line)) {
415        $vcard_block = $line . "\n";
416        $in_vcard_block = true;
417      }
418    }
419
420    return $out;
421  }
422
423
424  /**
425   * Normalize vcard data for better parsing
426   *
427   * @param string vCard block
428   * @return string Cleaned vcard block
429   */
430  private static function cleanup($vcard)
431  {
432    // Convert special types (like Skype) to normal type='skype' classes with this simple regex ;)
433    $vcard = preg_replace(
434      '/item(\d+)\.(TEL|EMAIL|URL)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
435      '\2;type=\5\3:\4',
436      $vcard);
437
438    // convert Apple X-ABRELATEDNAMES into X-* fields for better compatibility
439    $vcard = preg_replace_callback(
440      '/item(\d+)\.(X-ABRELATEDNAMES)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
441      array('self', 'x_abrelatednames_callback'),
442      $vcard);
443
444    // Remove cruft like item1.X-AB*, item1.ADR instead of ADR, and empty lines
445    $vcard = preg_replace(array('/^item\d*\.X-AB.*$/m', '/^item\d*\./m', "/\n+/"), array('', '', "\n"), $vcard);
446
447    // convert X-WAB-GENDER to X-GENDER
448    if (preg_match('/X-WAB-GENDER:(\d)/', $vcard, $matches)) {
449      $value = $matches[1] == '2' ? 'male' : 'female';
450      $vcard = preg_replace('/X-WAB-GENDER:\d/', 'X-GENDER:' . $value, $vcard);
451    }
452
453    // if N doesn't have any semicolons, add some
454    $vcard = preg_replace('/^(N:[^;\R]*)$/m', '\1;;;;', $vcard);
455
456    return $vcard;
457  }
458
459  private static function x_abrelatednames_callback($matches)
460  {
461    return 'X-' . strtoupper($matches[5]) . $matches[3] . ':'. $matches[4];
462  }
463
464  private static function rfc2425_fold_callback($matches)
465  {
466    // chunk_split string and avoid lines breaking multibyte characters
467    $c = 71;
468    $out .= substr($matches[1], 0, $c);
469    for ($n = $c; $c < strlen($matches[1]); $c++) {
470      // break if length > 75 or mutlibyte character starts after position 71
471      if ($n > 75 || ($n > 71 && ord($matches[1][$c]) >> 6 == 3)) {
472        $out .= "\r\n ";
473        $n = 0;
474      }
475      $out .= $matches[1][$c];
476      $n++;
477    }
478
479    return $out;
480  }
481
482  public static function rfc2425_fold($val)
483  {
484    return preg_replace_callback('/([^\n]{72,})/', array('self', 'rfc2425_fold_callback'), $val);
485  }
486
487
488  /**
489   * Decodes a vcard block (vcard 3.0 format, unfolded)
490   * into an array structure
491   *
492   * @param string vCard block to parse
493   * @return array Raw data structure
494   */
495  private static function vcard_decode($vcard)
496  {
497    // Perform RFC2425 line unfolding and split lines
498    $vcard = preg_replace(array("/\r/", "/\n\s+/"), '', $vcard);
499    $lines = explode("\n", $vcard);
500    $data  = array();
501
502    for ($i=0; $i < count($lines); $i++) {
503      if (!preg_match('/^([^:]+):(.+)$/', $lines[$i], $line))
504        continue;
505
506      if (preg_match('/^(BEGIN|END)$/i', $line[1]))
507        continue;
508
509      // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet;TYPE=home:"
510      if (($data['VERSION'][0] == "2.1") && preg_match('/^([^;]+);([^:]+)/', $line[1], $regs2) && !preg_match('/^TYPE=/i', $regs2[2])) {
511        $line[1] = $regs2[1];
512        foreach (explode(';', $regs2[2]) as $prop)
513          $line[1] .= ';' . (strpos($prop, '=') ? $prop : 'TYPE='.$prop);
514      }
515
516      if (preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
517        $entry = array();
518        $field = strtoupper($regs2[1][0]);
519
520        foreach($regs2[1] as $attrid => $attr) {
521          if ((list($key, $value) = explode('=', $attr)) && $value) {
522            $value = trim($value);
523            if ($key == 'ENCODING') {
524              // add next line(s) to value string if QP line end detected
525              while ($value == 'QUOTED-PRINTABLE' && preg_match('/=$/', $lines[$i]))
526                  $line[2] .= "\n" . $lines[++$i];
527
528              $line[2] = self::decode_value($line[2], $value);
529            }
530            else
531              $entry[strtolower($key)] = array_merge((array)$entry[strtolower($key)], (array)self::vcard_unquote($value, ','));
532          }
533          else if ($attrid > 0) {
534            $entry[$key] = true;  // true means attr without =value
535          }
536        }
537
538        $entry = array_merge($entry, (array)self::vcard_unquote($line[2]));
539        $data[$field][] = $entry;
540      }
541    }
542
543    unset($data['VERSION']);
544    return $data;
545  }
546
547
548  /**
549   * Decode a given string with the encoding rule from ENCODING attributes
550   *
551   * @param string String to decode
552   * @param string Encoding type (quoted-printable and base64 supported)
553   * @return string Decoded 8bit value
554   */
555  private static function decode_value($value, $encoding)
556  {
557    switch (strtolower($encoding)) {
558      case 'quoted-printable':
559        self::$values_decoded = true;
560        return quoted_printable_decode($value);
561
562      case 'base64':
563        self::$values_decoded = true;
564        return base64_decode($value);
565
566      default:
567        return $value;
568    }
569  }
570
571
572  /**
573   * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
574   *
575   * @param array Raw data structure to encode
576   * @return string vCard encoded string
577   */
578  static function vcard_encode($data)
579  {
580    foreach((array)$data as $type => $entries) {
581      /* valid N has 5 properties */
582      while ($type == "N" && is_array($entries[0]) && count($entries[0]) < 5)
583        $entries[0][] = "";
584
585      // make sure FN is not empty (required by RFC2426)
586      if ($type == "FN" && empty($entries))
587        $entries[0] = $data['EMAIL'][0][0];
588
589      foreach((array)$entries as $entry) {
590        $attr = '';
591        if (is_array($entry)) {
592          $value = array();
593          foreach($entry as $attrname => $attrvalues) {
594            if (is_int($attrname))
595              $value[] = $attrvalues;
596            elseif ($attrvalues === true)
597              $attr .= ";$attrname";    // true means just tag, not tag=value, as in PHOTO;BASE64:...
598            else {
599              foreach((array)$attrvalues as $attrvalue)
600                $attr .= ";$attrname=" . self::vcard_quote($attrvalue, ',');
601            }
602          }
603        }
604        else {
605          $value = $entry;
606        }
607
608        $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . "\n";
609      }
610    }
611
612    return "BEGIN:VCARD\nVERSION:3.0\n{$vcard}END:VCARD";
613  }
614
615
616  /**
617   * Join indexed data array to a vcard quoted string
618   *
619   * @param array Field data
620   * @param string Separator
621   * @return string Joined and quoted string
622   */
623  private static function vcard_quote($s, $sep = ';')
624  {
625    if (is_array($s)) {
626      foreach($s as $part) {
627        $r[] = self::vcard_quote($part, $sep);
628      }
629      return(implode($sep, (array)$r));
630    }
631    else {
632      return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ',' => '\,', ';' => '\;'));
633    }
634  }
635
636
637  /**
638   * Split quoted string
639   *
640   * @param string vCard string to split
641   * @param string Separator char/string
642   * @return array List with splitted values
643   */
644  private static function vcard_unquote($s, $sep = ';')
645  {
646    // break string into parts separated by $sep, but leave escaped $sep alone
647    if (count($parts = explode($sep, strtr($s, array("\\$sep" => "\007")))) > 1) {
648      foreach($parts as $s) {
649        $result[] = self::vcard_unquote(strtr($s, array("\007" => "\\$sep")), $sep);
650      }
651      return $result;
652    }
653    else {
654      return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\N' => "\n", '\,' => ',', '\;' => ';'));
655    }
656  }
657
658
659  /**
660   * Returns UNICODE type based on BOM (Byte Order Mark)
661   *
662   * @param string Input string to test
663   * @return string Detected encoding
664   */
665  private static function detect_encoding($string)
666  {
667    if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE';  // Big Endian
668    if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE';  // Little Endian
669    if (substr($string, 0, 2) == "\xFE\xFF")     return 'UTF-16BE';  // Big Endian
670    if (substr($string, 0, 2) == "\xFF\xFE")     return 'UTF-16LE';  // Little Endian
671    if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
672
673    // heuristics
674    if ($string[0] == "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-32BE';
675    if ($string[0] != "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] == "\0") return 'UTF-32LE';
676    if ($string[0] == "\0" && $string[1] != "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-16BE';
677    if ($string[0] != "\0" && $string[1] == "\0" && $string[2] != "\0" && $string[3] == "\0") return 'UTF-16LE';
678
679    // use mb_detect_encoding()
680    $encodings = array('UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3',
681      'ISO-8859-4', 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
682      'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
683      'WINDOWS-1252', 'WINDOWS-1251', 'BIG5', 'GB2312');
684
685    if (function_exists('mb_detect_encoding') && ($enc = mb_detect_encoding($string, $encodings)))
686      return $enc;
687
688    // No match, check for UTF-8
689    // from http://w3.org/International/questions/qa-forms-utf-8.html
690    if (preg_match('/\A(
691        [\x09\x0A\x0D\x20-\x7E]
692        | [\xC2-\xDF][\x80-\xBF]
693        | \xE0[\xA0-\xBF][\x80-\xBF]
694        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
695        | \xED[\x80-\x9F][\x80-\xBF]
696        | \xF0[\x90-\xBF][\x80-\xBF]{2}
697        | [\xF1-\xF3][\x80-\xBF]{3}
698        | \xF4[\x80-\x8F][\x80-\xBF]{2}
699        )*\z/xs', substr($string, 0, 2048)))
700      return 'UTF-8';
701
702    return rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'); # fallback to Latin-1
703  }
704
705}
Note: See TracBrowser for help on using the repository browser.