source: subversion/branches/devel-addressbook/program/include/rcube_vcard.php @ 4250

Last change on this file since 4250 was 4250, checked in by thomasb, 3 years ago

Fix contacts saving; correctly handle multiple e-mail addresses in autocomplete

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