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