source: github/program/include/rcube_vcard.php @ 58510fc

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 58510fc was 58510fc, checked in by thomascube <thomas@…>, 2 years ago

Use CRLF + 1 space for folding

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