alecpl
2008-09-20 c17dc6aa31aaa6e7f61bd25993be55354e428996
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)
76       $this->email[$i] = $raw_email[0];
77     
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
220     $vcard = preg_replace('/;CHARSET=[^:]+/', '', $vcard);
221
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) {
247         // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet,home:"
248         if(($data['VERSION'][0] == "2.1") && preg_match('/^([^;]+);([^:]+)/', $line[1], $regs2) && !preg_match('/^TYPE=/i', $regs2[2])) {
249           $line[1] = $regs2[1] . ";TYPE=" . strtr($regs2[2], array(";" => ","));
250         }
251
252         if (!preg_match('/^(BEGIN|END)$/', $line[1]) && preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
253           $entry = array(self::vcard_unquote($line[2]));
254
255           foreach($regs2[1] as $attrid => $attr) {
256             if ((list($key, $value) = explode('=', $attr)) && $value)
257               $entry[strtolower($key)] = array_merge((array)$entry[strtolower($key)], (array)self::vcard_unquote($value, ','));
258             elseif ($attrid > 0)
259               $entry[$key] = true;  # true means attr without =value
260           }
261
262           $data[$regs2[1][0]][] = count($entry) > 1 ? $entry : $entry[0];
263         }
264       }
265
266       unset($data['VERSION']);
267     }
268
269     return $data;
270   }
271
272
273   /**
274    * Split quoted string
275    *
276    * @param string vCard string to split
277    * @param string Separator char/string
278    * @return array List with splitted values
279    */
280   private static function vcard_unquote($s, $sep = ';')
281   {
282     // break string into parts separated by $sep, but leave escaped $sep alone
283     if (count($parts = explode($sep, strtr($s, array("\\$sep" => "\007")))) > 1) {
284       foreach($parts as $s) {
285         $result[] = self::vcard_unquote(strtr($s, array("\007" => "\\$sep")), $sep);
286       }
287       return $result;
288     }
289     else {
290       return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\,' => ',', '\;' => ';', '\:' => ':'));
291     }
292   }
293
294
295   /**
296    * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
297    *
298    * @param array Raw data structure to encode
299    * @return string vCard encoded string
300    */
301   static function vcard_encode($data)
302   {
303     foreach((array)$data as $type => $entries) {
304       /* valid N has 5 properties */
305       while ($type == "N" && count($entries[0]) < 5)
306         $entries[0][] = "";
307
308       foreach((array)$entries as $entry) {
309         $attr = '';
310         if (is_array($entry)) {
311           $value = array();
312           foreach($entry as $attrname => $attrvalues) {
313             if (is_int($attrname))
314               $value[] = $attrvalues;
315             elseif ($attrvalues === true)
316               $attr .= ";$attrname";    # true means just tag, not tag=value, as in PHOTO;BASE64:...
317             else {
318               foreach((array)$attrvalues as $attrvalue)
319                 $attr .= ";$attrname=" . self::vcard_quote($attrvalue, ',');
320             }
321           }
322         }
323         else {
324           $value = $entry;
325         }
326
327         $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . "\n";
328       }
329     }
330
0dbac3 331     return "BEGIN:VCARD\nVERSION:3.0\n{$vcard}END:VCARD";
ed132e 332   }
T 333
334
335   /**
336    * Join indexed data array to a vcard quoted string
337    *
338    * @param array Field data
339    * @param string Separator
340    * @return string Joined and quoted string
341    */
342   private static function vcard_quote($s, $sep = ';')
343   {
344     if (is_array($s)) {
345       foreach($s as $part) {
346         $r[] = self::vcard_quote($part, $sep);
347       }
348       return(implode($sep, (array)$r));
349     }
350     else {
351       return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ';' => '\;', ':' => '\:'));
352     }
353   }
354
355
356   /**
357    * Returns UNICODE type based on BOM (Byte Order Mark)
358    *
359    * @param string Input string to test
360    * @return string Detected encoding
361    */
362   private static function detect_encoding($string)
363   {
364     if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE';  // Big Endian
365     if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE';  // Little Endian
366     if (substr($string, 0, 2) == "\xFE\xFF")     return 'UTF-16BE';  // Big Endian
367     if (substr($string, 0, 2) == "\xFF\xFE")     return 'UTF-16LE';  // Little Endian
368     if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
369
370     // No match, check for UTF-8
371     // from http://w3.org/International/questions/qa-forms-utf-8.html
372     if (preg_match('/\A(
373         [\x09\x0A\x0D\x20-\x7E]
374         | [\xC2-\xDF][\x80-\xBF]
375         | \xE0[\xA0-\xBF][\x80-\xBF]
376         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
377         | \xED[\x80-\x9F][\x80-\xBF]
378         | \xF0[\x90-\xBF][\x80-\xBF]{2}
379         | [\xF1-\xF3][\x80-\xBF]{3}
380         | \xF4[\x80-\x8F][\x80-\xBF]{2}
381         )*\z/xs', substr($string, 0, 2048)))
382       return 'UTF-8';
383
384     return null;
385   }
386
387 }
388
389