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

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

Add support for X-AB-EDIT field upon user request

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