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

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

Fix vcard value decoding; add setter for individual vcard fields

  • Property svn:keywords set to Id
File size: 22.5 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   * Setter for individual vcard properties
336   *
337   * @param string VCard tag name
338   * @param array Value-set of this vcard property
339   * @param boolean Set to true if the value-set should be appended instead of replacing any existing value-set
340   */
341  public function set_raw($tag, $value, $append = false)
342  {
343    $index = $append ? count($this->raw[$tag]) : 0;
344    $this->raw[$tag][$index] = (array)$value;
345  }
346
347
348  /**
349   * Find index with the '$type' attribute
350   *
351   * @param string Field name
352   * @return int Field index having $type set
353   */
354  private function get_type_index($field, $type = 'pref')
355  {
356    $result = 0;
357    if ($this->raw[$field]) {
358      foreach ($this->raw[$field] as $i => $data) {
359        if (is_array($data['type']) && in_array_nocase('pref', $data['type']))
360          $result = $i;
361      }
362    }
363
364    return $result;
365  }
366
367
368  /**
369   * Convert a whole vcard (array) to UTF-8.
370   * If $force_charset is null, each member value that has a charset parameter will be converted
371   */
372  private static function charset_convert($card, $force_charset = null)
373  {
374    foreach ($card as $key => $node) {
375      foreach ($node as $i => $subnode) {
376        if (is_array($subnode) && (($charset = $force_charset) || ($subnode['charset'] && ($charset = $subnode['charset'][0])))) {
377          foreach ($subnode as $j => $value) {
378            if (is_numeric($j) && is_string($value))
379              $card[$key][$i][$j] = rcube_charset_convert($value, $charset);
380          }
381          unset($card[$key][$i]['charset']);
382        }
383      }
384    }
385
386    return $card;
387  }
388
389
390  /**
391   * Factory method to import a vcard file
392   *
393   * @param string vCard file content
394   * @return array List of rcube_vcard objects
395   */
396  public static function import($data)
397  {
398    $out = array();
399
400    // check if charsets are specified (usually vcard version < 3.0 but this is not reliable)
401    if (preg_match('/charset=/i', substr($data, 0, 2048)))
402      $charset = null;
403    // detect charset and convert to utf-8
404    else if (($charset = self::detect_encoding($data)) && $charset != RCMAIL_CHARSET) {
405      $data = rcube_charset_convert($data, $charset);
406      $data = preg_replace(array('/^[\xFE\xFF]{2}/', '/^\xEF\xBB\xBF/', '/^\x00+/'), '', $data); // also remove BOM
407      $charset = RCMAIL_CHARSET;
408    }
409
410    $vcard_block = '';
411    $in_vcard_block = false;
412
413    foreach (preg_split("/[\r\n]+/", $data) as $i => $line) {
414      if ($in_vcard_block && !empty($line))
415        $vcard_block .= $line . "\n";
416
417      $line = trim($line);
418
419      if (preg_match('/^END:VCARD$/i', $line)) {
420        // parse vcard
421        $obj = new rcube_vcard(self::cleanup($vcard_block), $charset, true);
422        if (!empty($obj->displayname) || !empty($obj->email))
423          $out[] = $obj;
424
425        $in_vcard_block = false;
426      }
427      else if (preg_match('/^BEGIN:VCARD$/i', $line)) {
428        $vcard_block = $line . "\n";
429        $in_vcard_block = true;
430      }
431    }
432
433    return $out;
434  }
435
436
437  /**
438   * Normalize vcard data for better parsing
439   *
440   * @param string vCard block
441   * @return string Cleaned vcard block
442   */
443  private static function cleanup($vcard)
444  {
445    // Convert special types (like Skype) to normal type='skype' classes with this simple regex ;)
446    $vcard = preg_replace(
447      '/item(\d+)\.(TEL|EMAIL|URL)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
448      '\2;type=\5\3:\4',
449      $vcard);
450
451    // convert Apple X-ABRELATEDNAMES into X-* fields for better compatibility
452    $vcard = preg_replace_callback(
453      '/item(\d+)\.(X-ABRELATEDNAMES)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
454      array('self', 'x_abrelatednames_callback'),
455      $vcard);
456
457    // Remove cruft like item1.X-AB*, item1.ADR instead of ADR, and empty lines
458    $vcard = preg_replace(array('/^item\d*\.X-AB.*$/m', '/^item\d*\./m', "/\n+/"), array('', '', "\n"), $vcard);
459
460    // convert X-WAB-GENDER to X-GENDER
461    if (preg_match('/X-WAB-GENDER:(\d)/', $vcard, $matches)) {
462      $value = $matches[1] == '2' ? 'male' : 'female';
463      $vcard = preg_replace('/X-WAB-GENDER:\d/', 'X-GENDER:' . $value, $vcard);
464    }
465
466    // if N doesn't have any semicolons, add some
467    $vcard = preg_replace('/^(N:[^;\R]*)$/m', '\1;;;;', $vcard);
468
469    return $vcard;
470  }
471
472  private static function x_abrelatednames_callback($matches)
473  {
474    return 'X-' . strtoupper($matches[5]) . $matches[3] . ':'. $matches[4];
475  }
476
477  private static function rfc2425_fold_callback($matches)
478  {
479    // chunk_split string and avoid lines breaking multibyte characters
480    $c = 71;
481    $out .= substr($matches[1], 0, $c);
482    for ($n = $c; $c < strlen($matches[1]); $c++) {
483      // break if length > 75 or mutlibyte character starts after position 71
484      if ($n > 75 || ($n > 71 && ord($matches[1][$c]) >> 6 == 3)) {
485        $out .= "\r\n ";
486        $n = 0;
487      }
488      $out .= $matches[1][$c];
489      $n++;
490    }
491
492    return $out;
493  }
494
495  public static function rfc2425_fold($val)
496  {
497    return preg_replace_callback('/([^\n]{72,})/', array('self', 'rfc2425_fold_callback'), $val);
498  }
499
500
501  /**
502   * Decodes a vcard block (vcard 3.0 format, unfolded)
503   * into an array structure
504   *
505   * @param string vCard block to parse
506   * @return array Raw data structure
507   */
508  private static function vcard_decode($vcard)
509  {
510    // Perform RFC2425 line unfolding and split lines
511    $vcard = preg_replace(array("/\r/", "/\n\s+/"), '', $vcard);
512    $lines = explode("\n", $vcard);
513    $data  = array();
514
515    for ($i=0; $i < count($lines); $i++) {
516      if (!preg_match('/^([^:]+):(.+)$/', $lines[$i], $line))
517        continue;
518
519      if (preg_match('/^(BEGIN|END)$/i', $line[1]))
520        continue;
521
522      // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet;TYPE=home:"
523      if (($data['VERSION'][0] == "2.1") && preg_match('/^([^;]+);([^:]+)/', $line[1], $regs2) && !preg_match('/^TYPE=/i', $regs2[2])) {
524        $line[1] = $regs2[1];
525        foreach (explode(';', $regs2[2]) as $prop)
526          $line[1] .= ';' . (strpos($prop, '=') ? $prop : 'TYPE='.$prop);
527      }
528
529      if (preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
530        $entry = array();
531        $field = strtoupper($regs2[1][0]);
532
533        foreach($regs2[1] as $attrid => $attr) {
534          if ((list($key, $value) = explode('=', $attr)) && $value) {
535            $value = trim($value);
536            if ($key == 'ENCODING') {
537              // add next line(s) to value string if QP line end detected
538              while ($value == 'QUOTED-PRINTABLE' && preg_match('/=$/', $lines[$i]))
539                  $line[2] .= "\n" . $lines[++$i];
540
541              $line[2] = self::decode_value($line[2], $value);
542            }
543            else
544              $entry[strtolower($key)] = array_merge((array)$entry[strtolower($key)], (array)self::vcard_unquote($value, ','));
545          }
546          else if ($attrid > 0) {
547            $entry[$key] = true;  // true means attr without =value
548          }
549        }
550
551        $entry = array_merge($entry, (array)self::vcard_unquote($line[2]));
552        $data[$field][] = $entry;
553      }
554    }
555
556    unset($data['VERSION']);
557    return $data;
558  }
559
560
561  /**
562   * Decode a given string with the encoding rule from ENCODING attributes
563   *
564   * @param string String to decode
565   * @param string Encoding type (quoted-printable and base64 supported)
566   * @return string Decoded 8bit value
567   */
568  private static function decode_value($value, $encoding)
569  {
570    switch (strtolower($encoding)) {
571      case 'quoted-printable':
572        self::$values_decoded = true;
573        return quoted_printable_decode($value);
574
575      case 'base64':
576        self::$values_decoded = true;
577        return base64_decode($value);
578
579      default:
580        return $value;
581    }
582  }
583
584
585  /**
586   * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
587   *
588   * @param array Raw data structure to encode
589   * @return string vCard encoded string
590   */
591  static function vcard_encode($data)
592  {
593    foreach((array)$data as $type => $entries) {
594      /* valid N has 5 properties */
595      while ($type == "N" && is_array($entries[0]) && count($entries[0]) < 5)
596        $entries[0][] = "";
597
598      // make sure FN is not empty (required by RFC2426)
599      if ($type == "FN" && empty($entries))
600        $entries[0] = $data['EMAIL'][0][0];
601
602      foreach((array)$entries as $entry) {
603        $attr = '';
604        if (is_array($entry)) {
605          $value = array();
606          foreach($entry as $attrname => $attrvalues) {
607            if (is_int($attrname))
608              $value[] = $attrvalues;
609            elseif ($attrvalues === true)
610              $attr .= ";$attrname";    // true means just tag, not tag=value, as in PHOTO;BASE64:...
611            else {
612              foreach((array)$attrvalues as $attrvalue)
613                $attr .= ";$attrname=" . self::vcard_quote($attrvalue, ',');
614            }
615          }
616        }
617        else {
618          $value = $entry;
619        }
620
621        $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . "\n";
622      }
623    }
624
625    return "BEGIN:VCARD\nVERSION:3.0\n{$vcard}END:VCARD";
626  }
627
628
629  /**
630   * Join indexed data array to a vcard quoted string
631   *
632   * @param array Field data
633   * @param string Separator
634   * @return string Joined and quoted string
635   */
636  private static function vcard_quote($s, $sep = ';')
637  {
638    if (is_array($s)) {
639      foreach($s as $part) {
640        $r[] = self::vcard_quote($part, $sep);
641      }
642      return(implode($sep, (array)$r));
643    }
644    else {
645      return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ',' => '\,', ';' => '\;'));
646    }
647  }
648
649
650  /**
651   * Split quoted string
652   *
653   * @param string vCard string to split
654   * @param string Separator char/string
655   * @return array List with splitted values
656   */
657  private static function vcard_unquote($s, $sep = ';')
658  {
659    // break string into parts separated by $sep, but leave escaped $sep alone
660    if (count($parts = explode($sep, strtr($s, array("\\$sep" => "\007")))) > 1) {
661      foreach($parts as $s) {
662        $result[] = self::vcard_unquote(strtr($s, array("\007" => "\\$sep")), $sep);
663      }
664      return $result;
665    }
666    else {
667      return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\N' => "\n", '\,' => ',', '\;' => ';', '\:' => ':'));
668    }
669  }
670
671
672  /**
673   * Returns UNICODE type based on BOM (Byte Order Mark)
674   *
675   * @param string Input string to test
676   * @return string Detected encoding
677   */
678  private static function detect_encoding($string)
679  {
680    if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE';  // Big Endian
681    if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE';  // Little Endian
682    if (substr($string, 0, 2) == "\xFE\xFF")     return 'UTF-16BE';  // Big Endian
683    if (substr($string, 0, 2) == "\xFF\xFE")     return 'UTF-16LE';  // Little Endian
684    if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
685
686    // heuristics
687    if ($string[0] == "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-32BE';
688    if ($string[0] != "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] == "\0") return 'UTF-32LE';
689    if ($string[0] == "\0" && $string[1] != "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-16BE';
690    if ($string[0] != "\0" && $string[1] == "\0" && $string[2] != "\0" && $string[3] == "\0") return 'UTF-16LE';
691
692    // use mb_detect_encoding()
693    $encodings = array('UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3',
694      'ISO-8859-4', 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
695      'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
696      'WINDOWS-1252', 'WINDOWS-1251', 'BIG5', 'GB2312');
697
698    if (function_exists('mb_detect_encoding') && ($enc = mb_detect_encoding($string, $encodings)))
699      return $enc;
700
701    // No match, check for UTF-8
702    // from http://w3.org/International/questions/qa-forms-utf-8.html
703    if (preg_match('/\A(
704        [\x09\x0A\x0D\x20-\x7E]
705        | [\xC2-\xDF][\x80-\xBF]
706        | \xE0[\xA0-\xBF][\x80-\xBF]
707        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
708        | \xED[\x80-\x9F][\x80-\xBF]
709        | \xF0[\x90-\xBF][\x80-\xBF]{2}
710        | [\xF1-\xF3][\x80-\xBF]{3}
711        | \xF4[\x80-\x8F][\x80-\xBF]{2}
712        )*\z/xs', substr($string, 0, 2048)))
713      return 'UTF-8';
714
715    return rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'); # fallback to Latin-1
716  }
717
718}
Note: See TracBrowser for help on using the repository browser.