]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_vcard.php
Imported Upstream version 0.2.1
[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: $
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 $raw = array(
32     'FN' => array(),
33     'N' => array(array('','','','','')),
34   );
35
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] = is_array($raw_email) ? $raw_email[0] : $raw_email;
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    */
104   public function set($field, $value, $section = 'HOME')
105   {
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       $data = preg_replace(array('/^[\xFE\xFF]{2}/', '/^\xEF\xBB\xBF/', '/^\x00+/'), '', $data); // also remove BOM
176     }
177
178     $vcard_block = '';
179     $in_vcard_block = false;
180
181     foreach (preg_split("/[\r\n]+/", $data) as $i => $line) {
182       if ($in_vcard_block && !empty($line))
183         $vcard_block .= $line . "\n";
184
185       if (trim($line) == 'END:VCARD') {
186         // parse vcard
187         $obj = new rcube_vcard(self::cleanup($vcard_block));
188         if (!empty($obj->displayname))
189           $out[] = $obj;
190
191         $in_vcard_block = false;
192       }
193       else if (trim($line) == 'BEGIN:VCARD') {
194         $vcard_block = $line . "\n";
195         $in_vcard_block = true;
196       }
197     }
198
199     return $out;
200   }
201
202
203   /**
204    * Normalize vcard data for better parsing
205    *
206    * @param string vCard block
207    * @return string Cleaned vcard block
208    */
209   private static function cleanup($vcard)
210   {
211     // Convert special types (like Skype) to normal type='skype' classes with this simple regex ;)
212     $vcard = preg_replace(
213       '/item(\d+)\.(TEL|URL)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
214       '\2;type=\5\3:\4',
215       $vcard);
216
217     // Remove cruft like item1.X-AB*, item1.ADR instead of ADR, and empty lines
218     $vcard = preg_replace(array('/^item\d*\.X-AB.*$/m', '/^item\d*\./m', "/\n+/"), array('', '', "\n"), $vcard);
219
220     // remove vcard 2.1 charset definitions
221     $vcard = preg_replace('/;CHARSET=[^:;]+/', '', $vcard);
222     
223     // if N doesn't have any semicolons, add some 
224     $vcard = preg_replace('/^(N:[^;\R]*)$/m', '\1;;;;', $vcard);
225
226     return $vcard;
227   }
228
229   private static function rfc2425_fold_callback($matches)
230   {
231     return ":\n  ".rtrim(chunk_split($matches[1], 72, "\n  "));
232   }
233
234   private static function rfc2425_fold($val)
235   {
236     return preg_replace_callback('/:([^\n]{72,})/', array('self', 'rfc2425_fold_callback'), $val) . "\n";
237   }
238
239
240   /**
241    * Decodes a vcard block (vcard 3.0 format, unfolded)
242    * into an array structure
243    *
244    * @param string vCard block to parse
245    * @return array Raw data structure
246    */
247   private static function vcard_decode($vcard)
248   {
249     // Perform RFC2425 line unfolding
250     $vcard = preg_replace(array("/\r/", "/\n\s+/"), '', $vcard);
251     
252     $lines = preg_split('/\r?\n/', $vcard);
253     $data = array();
254     
255     for ($i=0; $i < count($lines); $i++) {
256       if (!preg_match('/^([^\\:]*):(.+)$/', $lines[$i], $line))
257           continue;
258
259       // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet;TYPE=home:"
260       if (($data['VERSION'][0] == "2.1") && preg_match('/^([^;]+);([^:]+)/', $line[1], $regs2) && !preg_match('/^TYPE=/i', $regs2[2])) {
261         $line[1] = $regs2[1];
262         foreach (explode(';', $regs2[2]) as $prop)
263           $line[1] .= ';' . (strpos($prop, '=') ? $prop : 'TYPE='.$prop);
264       }
265
266       if (!preg_match('/^(BEGIN|END)$/', $line[1]) && preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
267         $entry = array('');
268         $field = $regs2[1][0];
269
270         foreach($regs2[1] as $attrid => $attr) {
271           if ((list($key, $value) = explode('=', $attr)) && $value) {
272             if ($key == 'ENCODING') {
273               # add next line(s) to value string if QP line end detected
274               while ($value == 'QUOTED-PRINTABLE' && ereg('=$', $lines[$i]))
275                   $line[2] .= "\n" . $lines[++$i];
276               
277               $line[2] = self::decode_value($line[2], $value);
278             }
279             else
280               $entry[strtolower($key)] = array_merge((array)$entry[strtolower($key)], (array)self::vcard_unquote($value, ','));
281           }
282           else if ($attrid > 0) {
283             $entry[$key] = true;  # true means attr without =value
284           }
285         }
286
287         $entry[0] = self::vcard_unquote($line[2]);
288         $data[$field][] = count($entry) > 1 ? $entry : $entry[0];
289       }
290     }
291
292     unset($data['VERSION']);
293
294     return $data;
295   }
296
297
298   /**
299    * Split quoted string
300    *
301    * @param string vCard string to split
302    * @param string Separator char/string
303    * @return array List with splitted values
304    */
305   private static function vcard_unquote($s, $sep = ';')
306   {
307     // break string into parts separated by $sep, but leave escaped $sep alone
308     if (count($parts = explode($sep, strtr($s, array("\\$sep" => "\007")))) > 1) {
309       foreach($parts as $s) {
310         $result[] = self::vcard_unquote(strtr($s, array("\007" => "\\$sep")), $sep);
311       }
312       return $result;
313     }
314     else {
315       return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\,' => ',', '\;' => ';', '\:' => ':'));
316     }
317   }
318
319
320   /**
321    * Decode a given string with the encoding rule from ENCODING attributes
322    *
323    * @param string String to decode
324    * @param string Encoding type (quoted-printable and base64 supported)
325    * @return string Decoded 8bit value
326    */
327   private static function decode_value($value, $encoding)
328   {
329     switch (strtolower($encoding)) {
330       case 'quoted-printable':
331         return quoted_printable_decode($value);
332
333       case 'base64':
334         return base64_decode($value);
335
336       default:
337         return $value;
338     }
339   }
340
341
342   /**
343    * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
344    *
345    * @param array Raw data structure to encode
346    * @return string vCard encoded string
347    */
348   static function vcard_encode($data)
349   {
350     foreach((array)$data as $type => $entries) {
351       /* valid N has 5 properties */
352       while ($type == "N" && is_array($entries[0]) && count($entries[0]) < 5)
353         $entries[0][] = "";
354
355       foreach((array)$entries as $entry) {
356         $attr = '';
357         if (is_array($entry)) {
358           $value = array();
359           foreach($entry as $attrname => $attrvalues) {
360             if (is_int($attrname))
361               $value[] = $attrvalues;
362             elseif ($attrvalues === true)
363               $attr .= ";$attrname";    # true means just tag, not tag=value, as in PHOTO;BASE64:...
364             else {
365               foreach((array)$attrvalues as $attrvalue)
366                 $attr .= ";$attrname=" . self::vcard_quote($attrvalue, ',');
367             }
368           }
369         }
370         else {
371           $value = $entry;
372         }
373
374         $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . "\n";
375       }
376     }
377
378     return "BEGIN:VCARD\nVERSION:3.0\n{$vcard}END:VCARD";
379   }
380
381
382   /**
383    * Join indexed data array to a vcard quoted string
384    *
385    * @param array Field data
386    * @param string Separator
387    * @return string Joined and quoted string
388    */
389   private static function vcard_quote($s, $sep = ';')
390   {
391     if (is_array($s)) {
392       foreach($s as $part) {
393         $r[] = self::vcard_quote($part, $sep);
394       }
395       return(implode($sep, (array)$r));
396     }
397     else {
398       return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ';' => '\;', ':' => '\:'));
399     }
400   }
401
402
403   /**
404    * Returns UNICODE type based on BOM (Byte Order Mark)
405    *
406    * @param string Input string to test
407    * @return string Detected encoding
408    */
409   private static function detect_encoding($string)
410   {
411     if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE';  // Big Endian
412     if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE';  // Little Endian
413     if (substr($string, 0, 2) == "\xFE\xFF")     return 'UTF-16BE';  // Big Endian
414     if (substr($string, 0, 2) == "\xFF\xFE")     return 'UTF-16LE';  // Little Endian
415     if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
416
417     // use mb_detect_encoding()
418     $encodings = array('UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3',
419       'ISO-8859-4', 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
420       'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
421       'WINDOWS-1252', 'WINDOWS-1251', 'BIG5', 'GB2312');
422
423     if (function_exists('mb_detect_encoding') && ($enc = mb_detect_encoding($string, $encodings)))
424       return $enc;
425
426     // No match, check for UTF-8
427     // from http://w3.org/International/questions/qa-forms-utf-8.html
428     if (preg_match('/\A(
429         [\x09\x0A\x0D\x20-\x7E]
430         | [\xC2-\xDF][\x80-\xBF]
431         | \xE0[\xA0-\xBF][\x80-\xBF]
432         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
433         | \xED[\x80-\x9F][\x80-\xBF]
434         | \xF0[\x90-\xBF][\x80-\xBF]{2}
435         | [\xF1-\xF3][\x80-\xBF]{3}
436         | \xF4[\x80-\x8F][\x80-\xBF]{2}
437         )*\z/xs', substr($string, 0, 2048)))
438       return 'UTF-8';
439
440     return rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'); # fallback to Latin-1
441   }
442
443 }
444
445