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