]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_vcard.php
Imported Upstream version 0.5.2+dfsg
[roundcube.git] / program / include / rcube_vcard.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_vcard.php                                       |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2008-2009, Roundcube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Logical representation of a vcard address record                    |
13  +-----------------------------------------------------------------------+
14  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
15  +-----------------------------------------------------------------------+
16
17  $Id: rcube_vcard.php 4393 2011-01-04 22:00:35Z thomasb $
18
19 */
20
21
22 /**
23  * Logical representation of a vcard-based address record
24  * Provides functions to parse and export vCard data format
25  *
26  * @package    Addressbook
27  * @author     Thomas Bruederli <roundcube@gmail.com>
28  */
29 class rcube_vcard
30 {
31   private static $values_decoded = false;
32   private $raw = array(
33     'FN' => array(),
34     'N' => array(array('','','','','')),
35   );
36
37   public $business = false;
38   public $displayname;
39   public $surname;
40   public $firstname;
41   public $middlename;
42   public $nickname;
43   public $organization;
44   public $notes;
45   public $email = array();
46
47
48   /**
49    * Constructor
50    */
51   public function __construct($vcard = null, $charset = RCMAIL_CHARSET, $detect = false)
52   {
53     if (!empty($vcard))
54       $this->load($vcard, $charset, $detect);
55   }
56
57
58   /**
59    * Load record from (internal, unfolded) vcard 3.0 format
60    *
61    * @param string vCard string to parse
62    * @param string Charset of string values
63    * @param boolean True if loading a 'foreign' vcard and extra heuristics for charset detection is required
64    */
65   public function load($vcard, $charset = RCMAIL_CHARSET, $detect = false)
66   {
67     self::$values_decoded = false;
68     $this->raw = self::vcard_decode($vcard);
69
70     // resolve charset parameters
71     if ($charset == null) {
72       $this->raw = self::charset_convert($this->raw);
73     }
74     // vcard has encoded values and charset should be detected
75     else if ($detect && self::$values_decoded &&
76       ($detected_charset = self::detect_encoding(self::vcard_encode($this->raw))) && $detected_charset != RCMAIL_CHARSET) {
77         $this->raw = self::charset_convert($this->raw, $detected_charset);
78     }
79
80     // find well-known address fields
81     $this->displayname = $this->raw['FN'][0][0];
82     $this->surname = $this->raw['N'][0][0];
83     $this->firstname = $this->raw['N'][0][1];
84     $this->middlename = $this->raw['N'][0][2];
85     $this->nickname = $this->raw['NICKNAME'][0][0];
86     $this->organization = $this->raw['ORG'][0][0];
87     $this->business = ($this->raw['X-ABSHOWAS'][0][0] == 'COMPANY') || (join('', (array)$this->raw['N'][0]) == '' && !empty($this->organization));
88     
89     foreach ((array)$this->raw['EMAIL'] as $i => $raw_email)
90       $this->email[$i] = is_array($raw_email) ? $raw_email[0] : $raw_email;
91     
92     // make the pref e-mail address the first entry in $this->email
93     $pref_index = $this->get_type_index('EMAIL', 'pref');
94     if ($pref_index > 0) {
95       $tmp = $this->email[0];
96       $this->email[0] = $this->email[$pref_index];
97       $this->email[$pref_index] = $tmp;
98     }
99
100     // make sure displayname is not empty (required by RFC2426)
101     if (!strlen($this->displayname)) {
102       // the same method is used in steps/mail/addcontact.inc
103       $this->displayname = ucfirst(preg_replace('/[\.\-]/', ' ',
104         substr($this->email[0], 0, strpos($this->email[0], '@'))));
105     }
106   }
107
108
109   /**
110    * Convert the data structure into a vcard 3.0 string
111    */
112   public function export()
113   {
114     return self::rfc2425_fold(self::vcard_encode($this->raw));
115   }
116
117
118   /**
119    * Setter for address record fields
120    *
121    * @param string Field name
122    * @param string Field value
123    * @param string Section name
124    */
125   public function set($field, $value, $section = 'HOME')
126   {
127     switch ($field) {
128       case 'name':
129       case 'displayname':
130         $this->raw['FN'][0][0] = $value;
131         break;
132         
133       case 'firstname':
134         $this->raw['N'][0][1] = $value;
135         break;
136         
137       case 'surname':
138         $this->raw['N'][0][0] = $value;
139         break;
140       
141       case 'nickname':
142         $this->raw['NICKNAME'][0][0] = $value;
143         break;
144         
145       case 'organization':
146         $this->raw['ORG'][0][0] = $value;
147         break;
148         
149       case 'email':
150         $index = $this->get_type_index('EMAIL', $section);
151         if (!is_array($this->raw['EMAIL'][$index])) {
152           $this->raw['EMAIL'][$index] = array(0 => $value, 'type' => array('INTERNET', $section, 'pref'));
153         }
154         else {
155           $this->raw['EMAIL'][$index][0] = $value;
156         }
157         break;
158     }
159   }
160
161
162   /**
163    * Find index with the '$type' attribute
164    *
165    * @param string Field name
166    * @return int Field index having $type set
167    */
168   private function get_type_index($field, $type = 'pref')
169   {
170     $result = 0;
171     if ($this->raw[$field]) {
172       foreach ($this->raw[$field] as $i => $data) {
173         if (is_array($data['type']) && in_array_nocase('pref', $data['type']))
174           $result = $i;
175       }
176     }
177     
178     return $result;
179   }
180   
181   
182   /**
183    * Convert a whole vcard (array) to UTF-8.
184    * If $force_charset is null, each member value that has a charset parameter will be converted
185    */
186   private static function charset_convert($card, $force_charset = null)
187   {
188     foreach ($card as $key => $node) {
189       foreach ($node as $i => $subnode) {
190         if (is_array($subnode) && (($charset = $force_charset) || ($subnode['charset'] && ($charset = $subnode['charset'][0])))) {
191           foreach ($subnode as $j => $value) {
192             if (is_numeric($j) && is_string($value))
193               $card[$key][$i][$j] = rcube_charset_convert($value, $charset);
194           }
195           unset($card[$key][$i]['charset']);
196         }
197       }
198     }
199
200     return $card;
201   }
202
203
204   /**
205    * Factory method to import a vcard file
206    *
207    * @param string vCard file content
208    * @return array List of rcube_vcard objects
209    */
210   public static function import($data)
211   {
212     $out = array();
213
214     // check if charsets are specified (usually vcard version < 3.0 but this is not reliable)
215     if (preg_match('/charset=/i', substr($data, 0, 2048)))
216       $charset = null;
217     // detect charset and convert to utf-8
218     else if (($charset = self::detect_encoding($data)) && $charset != RCMAIL_CHARSET) {
219       $data = rcube_charset_convert($data, $charset);
220       $data = preg_replace(array('/^[\xFE\xFF]{2}/', '/^\xEF\xBB\xBF/', '/^\x00+/'), '', $data); // also remove BOM
221       $charset = RCMAIL_CHARSET;
222     }
223
224     $vcard_block = '';
225     $in_vcard_block = false;
226
227     foreach (preg_split("/[\r\n]+/", $data) as $i => $line) {
228       if ($in_vcard_block && !empty($line))
229         $vcard_block .= $line . "\n";
230
231       $line = trim($line);
232
233       if (preg_match('/^END:VCARD$/i', $line)) {
234         // parse vcard
235         $obj = new rcube_vcard(self::cleanup($vcard_block), $charset, true);
236         if (!empty($obj->displayname))
237           $out[] = $obj;
238
239         $in_vcard_block = false;
240       }
241       else if (preg_match('/^BEGIN:VCARD$/i', $line)) {
242         $vcard_block = $line . "\n";
243         $in_vcard_block = true;
244       }
245     }
246
247     return $out;
248   }
249
250
251   /**
252    * Normalize vcard data for better parsing
253    *
254    * @param string vCard block
255    * @return string Cleaned vcard block
256    */
257   private static function cleanup($vcard)
258   {
259     // Convert special types (like Skype) to normal type='skype' classes with this simple regex ;)
260     $vcard = preg_replace(
261       '/item(\d+)\.(TEL|URL)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
262       '\2;type=\5\3:\4',
263       $vcard);
264
265     // Remove cruft like item1.X-AB*, item1.ADR instead of ADR, and empty lines
266     $vcard = preg_replace(array('/^item\d*\.X-AB.*$/m', '/^item\d*\./m', "/\n+/"), array('', '', "\n"), $vcard);
267
268     // if N doesn't have any semicolons, add some 
269     $vcard = preg_replace('/^(N:[^;\R]*)$/m', '\1;;;;', $vcard);
270
271     return $vcard;
272   }
273
274   private static function rfc2425_fold_callback($matches)
275   {
276     return ":\n  ".rtrim(chunk_split($matches[1], 72, "\n  "));
277   }
278
279   private static function rfc2425_fold($val)
280   {
281     return preg_replace_callback('/:([^\n]{72,})/', array('self', 'rfc2425_fold_callback'), $val) . "\n";
282   }
283
284
285   /**
286    * Decodes a vcard block (vcard 3.0 format, unfolded)
287    * into an array structure
288    *
289    * @param string vCard block to parse
290    * @return array Raw data structure
291    */
292   private static function vcard_decode($vcard)
293   {
294     // Perform RFC2425 line unfolding
295     $vcard = preg_replace(array("/\r/", "/\n\s+/"), '', $vcard);
296     
297     $lines = preg_split('/\r?\n/', $vcard);
298     $data = array();
299     
300     for ($i=0; $i < count($lines); $i++) {
301       if (!preg_match('/^([^\\:]*):(.+)$/', $lines[$i], $line))
302           continue;
303
304       // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet;TYPE=home:"
305       if (($data['VERSION'][0] == "2.1") && preg_match('/^([^;]+);([^:]+)/', $line[1], $regs2) && !preg_match('/^TYPE=/i', $regs2[2])) {
306         $line[1] = $regs2[1];
307         foreach (explode(';', $regs2[2]) as $prop)
308           $line[1] .= ';' . (strpos($prop, '=') ? $prop : 'TYPE='.$prop);
309       }
310
311       if (!preg_match('/^(BEGIN|END)$/i', $line[1]) && preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
312         $entry = array();
313         $field = strtoupper($regs2[1][0]);
314
315         foreach($regs2[1] as $attrid => $attr) {
316           if ((list($key, $value) = explode('=', $attr)) && $value) {
317             $value = trim($value);
318             if ($key == 'ENCODING') {
319               // add next line(s) to value string if QP line end detected
320               while ($value == 'QUOTED-PRINTABLE' && preg_match('/=$/', $lines[$i]))
321                   $line[2] .= "\n" . $lines[++$i];
322               
323               $line[2] = self::decode_value($line[2], $value);
324             }
325             else
326               $entry[strtolower($key)] = array_merge((array)$entry[strtolower($key)], (array)self::vcard_unquote($value, ','));
327           }
328           else if ($attrid > 0) {
329             $entry[$key] = true;  // true means attr without =value
330           }
331         }
332
333         $entry = array_merge($entry, (array)self::vcard_unquote($line[2]));
334         $data[$field][] = $entry;
335       }
336     }
337
338     unset($data['VERSION']);
339     return $data;
340   }
341
342
343   /**
344    * Split quoted string
345    *
346    * @param string vCard string to split
347    * @param string Separator char/string
348    * @return array List with splitted values
349    */
350   private static function vcard_unquote($s, $sep = ';')
351   {
352     // break string into parts separated by $sep, but leave escaped $sep alone
353     if (count($parts = explode($sep, strtr($s, array("\\$sep" => "\007")))) > 1) {
354       foreach($parts as $s) {
355         $result[] = self::vcard_unquote(strtr($s, array("\007" => "\\$sep")), $sep);
356       }
357       return $result;
358     }
359     else {
360       return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\,' => ',', '\;' => ';', '\:' => ':'));
361     }
362   }
363
364
365   /**
366    * Decode a given string with the encoding rule from ENCODING attributes
367    *
368    * @param string String to decode
369    * @param string Encoding type (quoted-printable and base64 supported)
370    * @return string Decoded 8bit value
371    */
372   private static function decode_value($value, $encoding)
373   {
374     switch (strtolower($encoding)) {
375       case 'quoted-printable':
376         self::$values_decoded = true;
377         return quoted_printable_decode($value);
378
379       case 'base64':
380         self::$values_decoded = true;
381         return base64_decode($value);
382
383       default:
384         return $value;
385     }
386   }
387
388
389   /**
390    * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
391    *
392    * @param array Raw data structure to encode
393    * @return string vCard encoded string
394    */
395   static function vcard_encode($data)
396   {
397     foreach((array)$data as $type => $entries) {
398       /* valid N has 5 properties */
399       while ($type == "N" && is_array($entries[0]) && count($entries[0]) < 5)
400         $entries[0][] = "";
401
402       foreach((array)$entries as $entry) {
403         $attr = '';
404         if (is_array($entry)) {
405           $value = array();
406           foreach($entry as $attrname => $attrvalues) {
407             if (is_int($attrname))
408               $value[] = $attrvalues;
409             elseif ($attrvalues === true)
410               $attr .= ";$attrname";    // true means just tag, not tag=value, as in PHOTO;BASE64:...
411             else {
412               foreach((array)$attrvalues as $attrvalue)
413                 $attr .= ";$attrname=" . self::vcard_quote($attrvalue, ',');
414             }
415           }
416         }
417         else {
418           $value = $entry;
419         }
420
421         $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . "\n";
422       }
423     }
424
425     return "BEGIN:VCARD\nVERSION:3.0\n{$vcard}END:VCARD";
426   }
427
428
429   /**
430    * Join indexed data array to a vcard quoted string
431    *
432    * @param array Field data
433    * @param string Separator
434    * @return string Joined and quoted string
435    */
436   private static function vcard_quote($s, $sep = ';')
437   {
438     if (is_array($s)) {
439       foreach($s as $part) {
440         $r[] = self::vcard_quote($part, $sep);
441       }
442       return(implode($sep, (array)$r));
443     }
444     else {
445       return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ';' => '\;', ':' => '\:'));
446     }
447   }
448
449
450   /**
451    * Returns UNICODE type based on BOM (Byte Order Mark)
452    *
453    * @param string Input string to test
454    * @return string Detected encoding
455    */
456   private static function detect_encoding($string)
457   {
458     if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE';  // Big Endian
459     if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE';  // Little Endian
460     if (substr($string, 0, 2) == "\xFE\xFF")     return 'UTF-16BE';  // Big Endian
461     if (substr($string, 0, 2) == "\xFF\xFE")     return 'UTF-16LE';  // Little Endian
462     if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
463
464     // use mb_detect_encoding()
465     $encodings = array('UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3',
466       'ISO-8859-4', 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
467       'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
468       'WINDOWS-1252', 'WINDOWS-1251', 'BIG5', 'GB2312');
469
470     if (function_exists('mb_detect_encoding') && ($enc = mb_detect_encoding($string, $encodings)))
471       return $enc;
472
473     // No match, check for UTF-8
474     // from http://w3.org/International/questions/qa-forms-utf-8.html
475     if (preg_match('/\A(
476         [\x09\x0A\x0D\x20-\x7E]
477         | [\xC2-\xDF][\x80-\xBF]
478         | \xE0[\xA0-\xBF][\x80-\xBF]
479         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
480         | \xED[\x80-\x9F][\x80-\xBF]
481         | \xF0[\x90-\xBF][\x80-\xBF]{2}
482         | [\xF1-\xF3][\x80-\xBF]{3}
483         | \xF4[\x80-\x8F][\x80-\xBF]{2}
484         )*\z/xs', substr($string, 0, 2048)))
485       return 'UTF-8';
486
487     return rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'); # fallback to Latin-1
488   }
489
490 }
491
492