alecpl
2008-10-07 2727053c61cac4a37a76b9e58e607acff7fc8dfb
commit | author | age
ed132e 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_vcard.php                                       |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2008, 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: $
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 {
0dbac3 31   private $raw = array(
T 32     'FN' => array(),
33     'N' => array(array('','','','','')),
34   );
ed132e 35
T 36   public $business = false;
37   public $displayname;
38   public $surname;
39   public $firstname;
40   public $middlename;
41   public $nickname;
42   public $organization;
43   public $notes;
44   public $email = array();
45
46
47   /**
48    * Constructor
49    */
50   public function __construct($vcard = null)
51   {
52     if (!empty($vcard))
53       $this->load($vcard);
54   }
55
56
57   /**
58    * Load record from (internal, unfolded) vcard 3.0 format
59    *
60    * @param string vCard string to parse
61    */
62   public function load($vcard)
63   {
64     $this->raw = self::vcard_decode($vcard);
65
66     // find well-known address fields
67     $this->displayname = $this->raw['FN'][0];
68     $this->surname = $this->raw['N'][0][0];
69     $this->firstname = $this->raw['N'][0][1];
70     $this->middlename = $this->raw['N'][0][2];
71     $this->nickname = $this->raw['NICKNAME'][0];
72     $this->organization = $this->raw['ORG'][0];
73     $this->business = ($this->raw['X-ABShowAs'][0] == 'COMPANY') || (join('', (array)$this->raw['N'][0]) == '' && !empty($this->organization));
74     
75     foreach ((array)$this->raw['EMAIL'] as $i => $raw_email)
bb8781 76       $this->email[$i] = is_array($raw_email) ? $raw_email[0] : $raw_email;
ed132e 77     
T 78     // make the pref e-mail address the first entry in $this->email
79     $pref_index = $this->get_type_index('EMAIL', 'pref');
80     if ($pref_index > 0) {
81       $tmp = $this->email[0];
82       $this->email[0] = $this->email[$pref_index];
83       $this->email[$pref_index] = $tmp;
84     }
85   }
86
87
88   /**
89    * Convert the data structure into a vcard 3.0 string
90    */
91   public function export()
92   {
93     return self::rfc2425_fold(self::vcard_encode($this->raw));
94   }
95
96
97   /**
98    * Setter for address record fields
99    *
100    * @param string Field name
101    * @param string Field value
102    * @param string Section name
103    */
0dbac3 104   public function set($field, $value, $section = 'HOME')
ed132e 105   {
T 106     switch ($field) {
107       case 'name':
108       case 'displayname':
109         $this->raw['FN'][0] = $value;
110         break;
111         
112       case 'firstname':
113         $this->raw['N'][0][1] = $value;
114         break;
115         
116       case 'surname':
117         $this->raw['N'][0][0] = $value;
118         break;
119       
120       case 'nickname':
121         $this->raw['NICKNAME'][0] = $value;
122         break;
123         
124       case 'organization':
125         $this->raw['ORG'][0] = $value;
126         break;
127         
128       case 'email':
129         $index = $this->get_type_index('EMAIL', $section);
130         if (!is_array($this->raw['EMAIL'][$index])) {
131           $this->raw['EMAIL'][$index] = array(0 => $value, 'type' => array('INTERNET', $section, 'pref'));
132         }
133         else {
134           $this->raw['EMAIL'][$index][0] = $value;
135         }
136         break;
137     }
138   }
139
140
141   /**
142    * Find index with the '$type' attribute
143    *
144    * @param string Field name
145    * @return int Field index having $type set
146    */
147   private function get_type_index($field, $type = 'pref')
148   {
149     $result = 0;
150     if ($this->raw[$field]) {
151       foreach ($this->raw[$field] as $i => $data) {
152         if (is_array($data['type']) && in_array_nocase('pref', $data['type']))
153           $result = $i;
154       }
155     }
156     
157     return $result;
158   }
159
160
161   /**
162    * Factory method to import a vcard file
163    *
164    * @param string vCard file content
165    * @return array List of rcube_vcard objects
166    */
167   public static function import($data)
168   {
169     $out = array();
170
171     // detect charset and convert to utf-8
172     $encoding = self::detect_encoding($data);
173     if ($encoding && $encoding != RCMAIL_CHARSET) {
174       $data = rcube_charset_convert($data, $encoding);
175     }
176
177     $vcard_block = '';
178     $in_vcard_block = false;
179
180     foreach (preg_split("/[\r\n]+/", $data) as $i => $line) {
181       if ($in_vcard_block && !empty($line))
182         $vcard_block .= $line . "\n";
183
184       if (trim($line) == 'END:VCARD') {
185         // parse vcard
186         $obj = new rcube_vcard(self::cleanup($vcard_block));
187         if (!empty($obj->displayname))
188           $out[] = $obj;
189
190         $in_vcard_block = false;
191       }
192       else if (trim($line) == 'BEGIN:VCARD') {
193         $vcard_block = $line . "\n";
194         $in_vcard_block = true;
195       }
196     }
197
198     return $out;
199   }
200
201
202   /**
203    * Normalize vcard data for better parsing
204    *
205    * @param string vCard block
206    * @return string Cleaned vcard block
207    */
208   private static function cleanup($vcard)
209   {
210     // Convert special types (like Skype) to normal type='skype' classes with this simple regex ;)
211     $vcard = preg_replace(
212       '/item(\d+)\.(TEL|URL)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
213       '\2;type=\5\3:\4',
214       $vcard);
215
216     // Remove cruft like item1.X-AB*, item1.ADR instead of ADR, and empty lines
217     $vcard = preg_replace(array('/^item\d*\.X-AB.*$/m', '/^item\d*\./m', "/\n+/"), array('', '', "\n"), $vcard);
218
219     // remove vcard 2.1 charset definitions
bb8781 220     $vcard = preg_replace('/;CHARSET=[^:;]+/', '', $vcard);
ed132e 221
T 222     return $vcard;
223   }
224
225
226   private static function rfc2425_fold($val)
227   {
0dbac3 228     return preg_replace('/:([^\n]{72,})/e', '":\n  ".rtrim(chunk_split("\\1", 72, "\n  "))', $val) . "\n";
ed132e 229   }
T 230
231
232   /**
233    * Decodes a vcard block (vcard 3.0 format, unfolded)
234    * into an array structure
235    *
236    * @param string vCard block to parse
237    * @return array Raw data structure
238    */
239   private static function vcard_decode($vcard)
240   {
241     // Perform RFC2425 line unfolding
242     $vcard = preg_replace(array("/\r/", "/\n\s+/"), '', $vcard);
243     
244     $data = array();
245     if (preg_match_all('/^([^\\:]*):(.+)$/m', $vcard, $regs, PREG_SET_ORDER)) {
246       foreach($regs as $line) {
bb8781 247         // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet;TYPE=home:"
T 248         if (($data['VERSION'][0] == "2.1") && preg_match('/^([^;]+);([^:]+)/', $line[1], $regs2) && !preg_match('/^TYPE=/i', $regs2[2])) {
249           $line[1] = $regs2[1];
250           foreach (explode(';', $regs2[2]) as $prop)
251             $line[1] .= ';' . (strpos($prop, '=') ? $prop : 'TYPE='.$prop);
ed132e 252         }
T 253
254         if (!preg_match('/^(BEGIN|END)$/', $line[1]) && preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
255           $entry = array(self::vcard_unquote($line[2]));
256
257           foreach($regs2[1] as $attrid => $attr) {
bb8781 258             if ((list($key, $value) = explode('=', $attr)) && $value) {
T 259               if ($key == 'ENCODING')
260                 $entry[0] = self::decode_value($entry[0], $value);
261               else
262                 $entry[strtolower($key)] = array_merge((array)$entry[strtolower($key)], (array)self::vcard_unquote($value, ','));
263             }
264             else if ($attrid > 0) {
ed132e 265               $entry[$key] = true;  # true means attr without =value
bb8781 266             }
ed132e 267           }
T 268
269           $data[$regs2[1][0]][] = count($entry) > 1 ? $entry : $entry[0];
270         }
271       }
272
273       unset($data['VERSION']);
274     }
275
276     return $data;
277   }
278
279
280   /**
281    * Split quoted string
282    *
283    * @param string vCard string to split
284    * @param string Separator char/string
285    * @return array List with splitted values
286    */
287   private static function vcard_unquote($s, $sep = ';')
288   {
289     // break string into parts separated by $sep, but leave escaped $sep alone
290     if (count($parts = explode($sep, strtr($s, array("\\$sep" => "\007")))) > 1) {
291       foreach($parts as $s) {
292         $result[] = self::vcard_unquote(strtr($s, array("\007" => "\\$sep")), $sep);
293       }
294       return $result;
295     }
296     else {
297       return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\,' => ',', '\;' => ';', '\:' => ':'));
bb8781 298     }
T 299   }
300
301
302   /**
303    * Decode a given string with the encoding rule from ENCODING attributes
304    *
305    * @param string String to decode
306    * @param string Encoding type (quoted-printable and base64 supported)
307    * @return string Decoded 8bit value
308    */
309   private static function decode_value($value, $encoding)
310   {
311     switch (strtolower($encoding)) {
312       case 'quoted-printable':
313         return quoted_printable_decode($value);
314
315       case 'base64':
316         return base64_decode($value);
317
318       default:
319         return $value;
ed132e 320     }
T 321   }
322
323
324   /**
325    * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
326    *
327    * @param array Raw data structure to encode
328    * @return string vCard encoded string
329    */
330   static function vcard_encode($data)
331   {
332     foreach((array)$data as $type => $entries) {
333       /* valid N has 5 properties */
334       while ($type == "N" && count($entries[0]) < 5)
335         $entries[0][] = "";
336
337       foreach((array)$entries as $entry) {
338         $attr = '';
339         if (is_array($entry)) {
340           $value = array();
341           foreach($entry as $attrname => $attrvalues) {
342             if (is_int($attrname))
343               $value[] = $attrvalues;
344             elseif ($attrvalues === true)
345               $attr .= ";$attrname";    # true means just tag, not tag=value, as in PHOTO;BASE64:...
346             else {
347               foreach((array)$attrvalues as $attrvalue)
348                 $attr .= ";$attrname=" . self::vcard_quote($attrvalue, ',');
349             }
350           }
351         }
352         else {
353           $value = $entry;
354         }
355
356         $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . "\n";
357       }
358     }
359
0dbac3 360     return "BEGIN:VCARD\nVERSION:3.0\n{$vcard}END:VCARD";
ed132e 361   }
T 362
363
364   /**
365    * Join indexed data array to a vcard quoted string
366    *
367    * @param array Field data
368    * @param string Separator
369    * @return string Joined and quoted string
370    */
371   private static function vcard_quote($s, $sep = ';')
372   {
373     if (is_array($s)) {
374       foreach($s as $part) {
375         $r[] = self::vcard_quote($part, $sep);
376       }
377       return(implode($sep, (array)$r));
378     }
379     else {
380       return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ';' => '\;', ':' => '\:'));
381     }
382   }
383
384
385   /**
386    * Returns UNICODE type based on BOM (Byte Order Mark)
387    *
388    * @param string Input string to test
389    * @return string Detected encoding
390    */
391   private static function detect_encoding($string)
392   {
393     if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE';  // Big Endian
394     if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE';  // Little Endian
395     if (substr($string, 0, 2) == "\xFE\xFF")     return 'UTF-16BE';  // Big Endian
396     if (substr($string, 0, 2) == "\xFF\xFE")     return 'UTF-16LE';  // Little Endian
397     if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
398
abdc58 399     if ($enc = rc_detect_encoding($string))
A 400       return $enc;
401
ed132e 402     // No match, check for UTF-8
T 403     // from http://w3.org/International/questions/qa-forms-utf-8.html
404     if (preg_match('/\A(
405         [\x09\x0A\x0D\x20-\x7E]
406         | [\xC2-\xDF][\x80-\xBF]
407         | \xE0[\xA0-\xBF][\x80-\xBF]
408         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
409         | \xED[\x80-\x9F][\x80-\xBF]
410         | \xF0[\x90-\xBF][\x80-\xBF]{2}
411         | [\xF1-\xF3][\x80-\xBF]{3}
412         | \xF4[\x80-\x8F][\x80-\xBF]{2}
413         )*\z/xs', substr($string, 0, 2048)))
414       return 'UTF-8';
415
bb8781 416     return 'ISO-8859-1'; # fallback to Latin-1
ed132e 417   }
T 418
419 }
420
421