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