4 +-----------------------------------------------------------------------+
5 | program/include/rcube_vcard.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2008-2009, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Logical representation of a vcard address record |
13 +-----------------------------------------------------------------------+
14 | Author: Thomas Bruederli <roundcube@gmail.com> |
15 +-----------------------------------------------------------------------+
17 $Id: rcube_vcard.php 4393 2011-01-04 22:00:35Z thomasb $
23 * Logical representation of a vcard-based address record
24 * Provides functions to parse and export vCard data format
26 * @package Addressbook
27 * @author Thomas Bruederli <roundcube@gmail.com>
31 private static $values_decoded = false;
34 'N' => array(array('','','','','')),
37 public $business = false;
45 public $email = array();
51 public function __construct($vcard = null, $charset = RCMAIL_CHARSET, $detect = false)
54 $this->load($vcard, $charset, $detect);
59 * Load record from (internal, unfolded) vcard 3.0 format
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
65 public function load($vcard, $charset = RCMAIL_CHARSET, $detect = false)
67 self::$values_decoded = false;
68 $this->raw = self::vcard_decode($vcard);
70 // resolve charset parameters
71 if ($charset == null) {
72 $this->raw = self::charset_convert($this->raw);
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);
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));
89 foreach ((array)$this->raw['EMAIL'] as $i => $raw_email)
90 $this->email[$i] = is_array($raw_email) ? $raw_email[0] : $raw_email;
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;
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], '@'))));
110 * Convert the data structure into a vcard 3.0 string
112 public function export()
114 return self::rfc2425_fold(self::vcard_encode($this->raw));
119 * Setter for address record fields
121 * @param string Field name
122 * @param string Field value
123 * @param string Section name
125 public function set($field, $value, $section = 'HOME')
130 $this->raw['FN'][0][0] = $value;
134 $this->raw['N'][0][1] = $value;
138 $this->raw['N'][0][0] = $value;
142 $this->raw['NICKNAME'][0][0] = $value;
146 $this->raw['ORG'][0][0] = $value;
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'));
155 $this->raw['EMAIL'][$index][0] = $value;
163 * Find index with the '$type' attribute
165 * @param string Field name
166 * @return int Field index having $type set
168 private function get_type_index($field, $type = 'pref')
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']))
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
186 private static function charset_convert($card, $force_charset = null)
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);
195 unset($card[$key][$i]['charset']);
205 * Factory method to import a vcard file
207 * @param string vCard file content
208 * @return array List of rcube_vcard objects
210 public static function import($data)
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)))
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;
225 $in_vcard_block = false;
227 foreach (preg_split("/[\r\n]+/", $data) as $i => $line) {
228 if ($in_vcard_block && !empty($line))
229 $vcard_block .= $line . "\n";
233 if (preg_match('/^END:VCARD$/i', $line)) {
235 $obj = new rcube_vcard(self::cleanup($vcard_block), $charset, true);
236 if (!empty($obj->displayname))
239 $in_vcard_block = false;
241 else if (preg_match('/^BEGIN:VCARD$/i', $line)) {
242 $vcard_block = $line . "\n";
243 $in_vcard_block = true;
252 * Normalize vcard data for better parsing
254 * @param string vCard block
255 * @return string Cleaned vcard block
257 private static function cleanup($vcard)
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',
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);
268 // if N doesn't have any semicolons, add some
269 $vcard = preg_replace('/^(N:[^;\R]*)$/m', '\1;;;;', $vcard);
274 private static function rfc2425_fold_callback($matches)
276 return ":\n ".rtrim(chunk_split($matches[1], 72, "\n "));
279 private static function rfc2425_fold($val)
281 return preg_replace_callback('/:([^\n]{72,})/', array('self', 'rfc2425_fold_callback'), $val) . "\n";
286 * Decodes a vcard block (vcard 3.0 format, unfolded)
287 * into an array structure
289 * @param string vCard block to parse
290 * @return array Raw data structure
292 private static function vcard_decode($vcard)
294 // Perform RFC2425 line unfolding
295 $vcard = preg_replace(array("/\r/", "/\n\s+/"), '', $vcard);
297 $lines = preg_split('/\r?\n/', $vcard);
300 for ($i=0; $i < count($lines); $i++) {
301 if (!preg_match('/^([^\\:]*):(.+)$/', $lines[$i], $line))
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);
311 if (!preg_match('/^(BEGIN|END)$/i', $line[1]) && preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
313 $field = strtoupper($regs2[1][0]);
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];
323 $line[2] = self::decode_value($line[2], $value);
326 $entry[strtolower($key)] = array_merge((array)$entry[strtolower($key)], (array)self::vcard_unquote($value, ','));
328 else if ($attrid > 0) {
329 $entry[$key] = true; // true means attr without =value
333 $entry = array_merge($entry, (array)self::vcard_unquote($line[2]));
334 $data[$field][] = $entry;
338 unset($data['VERSION']);
344 * Split quoted string
346 * @param string vCard string to split
347 * @param string Separator char/string
348 * @return array List with splitted values
350 private static function vcard_unquote($s, $sep = ';')
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);
360 return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\,' => ',', '\;' => ';', '\:' => ':'));
366 * Decode a given string with the encoding rule from ENCODING attributes
368 * @param string String to decode
369 * @param string Encoding type (quoted-printable and base64 supported)
370 * @return string Decoded 8bit value
372 private static function decode_value($value, $encoding)
374 switch (strtolower($encoding)) {
375 case 'quoted-printable':
376 self::$values_decoded = true;
377 return quoted_printable_decode($value);
380 self::$values_decoded = true;
381 return base64_decode($value);
390 * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
392 * @param array Raw data structure to encode
393 * @return string vCard encoded string
395 static function vcard_encode($data)
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)
402 foreach((array)$entries as $entry) {
404 if (is_array($entry)) {
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:...
412 foreach((array)$attrvalues as $attrvalue)
413 $attr .= ";$attrname=" . self::vcard_quote($attrvalue, ',');
421 $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . "\n";
425 return "BEGIN:VCARD\nVERSION:3.0\n{$vcard}END:VCARD";
430 * Join indexed data array to a vcard quoted string
432 * @param array Field data
433 * @param string Separator
434 * @return string Joined and quoted string
436 private static function vcard_quote($s, $sep = ';')
439 foreach($s as $part) {
440 $r[] = self::vcard_quote($part, $sep);
442 return(implode($sep, (array)$r));
445 return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ';' => '\;', ':' => '\:'));
451 * Returns UNICODE type based on BOM (Byte Order Mark)
453 * @param string Input string to test
454 * @return string Detected encoding
456 private static function detect_encoding($string)
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';
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');
470 if (function_exists('mb_detect_encoding') && ($enc = mb_detect_encoding($string, $encodings)))
473 // No match, check for UTF-8
474 // from http://w3.org/International/questions/qa-forms-utf-8.html
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)))
487 return rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'); # fallback to Latin-1