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