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

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