PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/program/include/rcube_vcard.php

https://github.com/netconstructor/roundcubemail
PHP | 793 lines | 495 code | 119 blank | 179 comment | 141 complexity | 04a5cb3bcd6e72530fe36bc48c654360 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1
  1. <?php
  2. /*
  3. +-----------------------------------------------------------------------+
  4. | program/include/rcube_vcard.php |
  5. | |
  6. | This file is part of the Roundcube Webmail client |
  7. | Copyright (C) 2008-2012, The Roundcube Dev Team |
  8. | |
  9. | Licensed under the GNU General Public License version 3 or |
  10. | any later version with exceptions for skins & plugins. |
  11. | See the README file for a full license statement. |
  12. | |
  13. | PURPOSE: |
  14. | Logical representation of a vcard address record |
  15. +-----------------------------------------------------------------------+
  16. | Author: Thomas Bruederli <roundcube@gmail.com> |
  17. | Author: Aleksander Machniak <alec@alec.pl> |
  18. +-----------------------------------------------------------------------+
  19. */
  20. /**
  21. * Logical representation of a vcard-based address record
  22. * Provides functions to parse and export vCard data format
  23. *
  24. * @package Framework
  25. * @subpackage Addressbook
  26. */
  27. class rcube_vcard
  28. {
  29. private static $values_decoded = false;
  30. private $raw = array(
  31. 'FN' => array(),
  32. 'N' => array(array('','','','','')),
  33. );
  34. private static $fieldmap = array(
  35. 'phone' => 'TEL',
  36. 'birthday' => 'BDAY',
  37. 'website' => 'URL',
  38. 'notes' => 'NOTE',
  39. 'email' => 'EMAIL',
  40. 'address' => 'ADR',
  41. 'jobtitle' => 'TITLE',
  42. 'department' => 'X-DEPARTMENT',
  43. 'gender' => 'X-GENDER',
  44. 'maidenname' => 'X-MAIDENNAME',
  45. 'anniversary' => 'X-ANNIVERSARY',
  46. 'assistant' => 'X-ASSISTANT',
  47. 'manager' => 'X-MANAGER',
  48. 'spouse' => 'X-SPOUSE',
  49. 'edit' => 'X-AB-EDIT',
  50. );
  51. private $typemap = array('IPHONE' => 'mobile', 'CELL' => 'mobile', 'WORK,FAX' => 'workfax');
  52. private $phonetypemap = array('HOME1' => 'HOME', 'BUSINESS1' => 'WORK', 'BUSINESS2' => 'WORK2', 'BUSINESSFAX' => 'WORK,FAX');
  53. private $addresstypemap = array('BUSINESS' => 'WORK');
  54. private $immap = array('X-JABBER' => 'jabber', 'X-ICQ' => 'icq', 'X-MSN' => 'msn', 'X-AIM' => 'aim', 'X-YAHOO' => 'yahoo', 'X-SKYPE' => 'skype', 'X-SKYPE-USERNAME' => 'skype');
  55. public $business = false;
  56. public $displayname;
  57. public $surname;
  58. public $firstname;
  59. public $middlename;
  60. public $nickname;
  61. public $organization;
  62. public $email = array();
  63. public static $eol = "\r\n";
  64. /**
  65. * Constructor
  66. */
  67. public function __construct($vcard = null, $charset = RCMAIL_CHARSET, $detect = false, $fieldmap = array())
  68. {
  69. if (!empty($fielmap))
  70. $this->extend_fieldmap($fieldmap);
  71. if (!empty($vcard))
  72. $this->load($vcard, $charset, $detect);
  73. }
  74. /**
  75. * Load record from (internal, unfolded) vcard 3.0 format
  76. *
  77. * @param string vCard string to parse
  78. * @param string Charset of string values
  79. * @param boolean True if loading a 'foreign' vcard and extra heuristics for charset detection is required
  80. */
  81. public function load($vcard, $charset = RCMAIL_CHARSET, $detect = false)
  82. {
  83. self::$values_decoded = false;
  84. $this->raw = self::vcard_decode($vcard);
  85. // resolve charset parameters
  86. if ($charset == null) {
  87. $this->raw = self::charset_convert($this->raw);
  88. }
  89. // vcard has encoded values and charset should be detected
  90. else if ($detect && self::$values_decoded &&
  91. ($detected_charset = self::detect_encoding(self::vcard_encode($this->raw))) && $detected_charset != RCMAIL_CHARSET) {
  92. $this->raw = self::charset_convert($this->raw, $detected_charset);
  93. }
  94. // consider FN empty if the same as the primary e-mail address
  95. if ($this->raw['FN'][0][0] == $this->raw['EMAIL'][0][0])
  96. $this->raw['FN'][0][0] = '';
  97. // find well-known address fields
  98. $this->displayname = $this->raw['FN'][0][0];
  99. $this->surname = $this->raw['N'][0][0];
  100. $this->firstname = $this->raw['N'][0][1];
  101. $this->middlename = $this->raw['N'][0][2];
  102. $this->nickname = $this->raw['NICKNAME'][0][0];
  103. $this->organization = $this->raw['ORG'][0][0];
  104. $this->business = ($this->raw['X-ABSHOWAS'][0][0] == 'COMPANY') || (join('', (array)$this->raw['N'][0]) == '' && !empty($this->organization));
  105. foreach ((array)$this->raw['EMAIL'] as $i => $raw_email)
  106. $this->email[$i] = is_array($raw_email) ? $raw_email[0] : $raw_email;
  107. // make the pref e-mail address the first entry in $this->email
  108. $pref_index = $this->get_type_index('EMAIL', 'pref');
  109. if ($pref_index > 0) {
  110. $tmp = $this->email[0];
  111. $this->email[0] = $this->email[$pref_index];
  112. $this->email[$pref_index] = $tmp;
  113. }
  114. }
  115. /**
  116. * Return vCard data as associative array to be unsed in Roundcube address books
  117. *
  118. * @return array Hash array with key-value pairs
  119. */
  120. public function get_assoc()
  121. {
  122. $out = array('name' => $this->displayname);
  123. $typemap = $this->typemap;
  124. // copy name fields to output array
  125. foreach (array('firstname','surname','middlename','nickname','organization') as $col) {
  126. if (strlen($this->$col))
  127. $out[$col] = $this->$col;
  128. }
  129. if ($this->raw['N'][0][3])
  130. $out['prefix'] = $this->raw['N'][0][3];
  131. if ($this->raw['N'][0][4])
  132. $out['suffix'] = $this->raw['N'][0][4];
  133. // convert from raw vcard data into associative data for Roundcube
  134. foreach (array_flip(self::$fieldmap) as $tag => $col) {
  135. foreach ((array)$this->raw[$tag] as $i => $raw) {
  136. if (is_array($raw)) {
  137. $k = -1;
  138. $key = $col;
  139. $subtype = '';
  140. if (!empty($raw['type'])) {
  141. $combined = join(',', self::array_filter((array)$raw['type'], 'internet,pref', true));
  142. $combined = strtoupper($combined);
  143. if ($typemap[$combined]) {
  144. $subtype = $typemap[$combined];
  145. }
  146. else if ($typemap[$raw['type'][++$k]]) {
  147. $subtype = $typemap[$raw['type'][$k]];
  148. }
  149. else {
  150. $subtype = strtolower($raw['type'][$k]);
  151. }
  152. while ($k < count($raw['type']) && ($subtype == 'internet' || $subtype == 'pref'))
  153. $subtype = $typemap[$raw['type'][++$k]] ? $typemap[$raw['type'][$k]] : strtolower($raw['type'][$k]);
  154. }
  155. // read vcard 2.1 subtype
  156. if (!$subtype) {
  157. foreach ($raw as $k => $v) {
  158. if (!is_numeric($k) && $v === true && ($k = strtolower($k))
  159. && !in_array($k, array('pref','internet','voice','base64'))
  160. ) {
  161. $k_uc = strtoupper($k);
  162. $subtype = $typemap[$k_uc] ? $typemap[$k_uc] : $k;
  163. break;
  164. }
  165. }
  166. }
  167. // force subtype if none set
  168. if (!$subtype && preg_match('/^(email|phone|address|website)/', $key))
  169. $subtype = 'other';
  170. if ($subtype)
  171. $key .= ':' . $subtype;
  172. // split ADR values into assoc array
  173. if ($tag == 'ADR') {
  174. list(,, $value['street'], $value['locality'], $value['region'], $value['zipcode'], $value['country']) = $raw;
  175. $out[$key][] = $value;
  176. }
  177. else
  178. $out[$key][] = $raw[0];
  179. }
  180. else {
  181. $out[$col][] = $raw;
  182. }
  183. }
  184. }
  185. // handle special IM fields as used by Apple
  186. foreach ($this->immap as $tag => $type) {
  187. foreach ((array)$this->raw[$tag] as $i => $raw) {
  188. $out['im:'.$type][] = $raw[0];
  189. }
  190. }
  191. // copy photo data
  192. if ($this->raw['PHOTO'])
  193. $out['photo'] = $this->raw['PHOTO'][0][0];
  194. return $out;
  195. }
  196. /**
  197. * Convert the data structure into a vcard 3.0 string
  198. */
  199. public function export($folded = true)
  200. {
  201. $vcard = self::vcard_encode($this->raw);
  202. return $folded ? self::rfc2425_fold($vcard) : $vcard;
  203. }
  204. /**
  205. * Clear the given fields in the loaded vcard data
  206. *
  207. * @param array List of field names to be reset
  208. */
  209. public function reset($fields = null)
  210. {
  211. if (!$fields)
  212. $fields = array_merge(array_values(self::$fieldmap), array_keys($this->immap), array('FN','N','ORG','NICKNAME','EMAIL','ADR','BDAY'));
  213. foreach ($fields as $f)
  214. unset($this->raw[$f]);
  215. if (!$this->raw['N'])
  216. $this->raw['N'] = array(array('','','','',''));
  217. if (!$this->raw['FN'])
  218. $this->raw['FN'] = array();
  219. $this->email = array();
  220. }
  221. /**
  222. * Setter for address record fields
  223. *
  224. * @param string Field name
  225. * @param string Field value
  226. * @param string Type/section name
  227. */
  228. public function set($field, $value, $type = 'HOME')
  229. {
  230. $field = strtolower($field);
  231. $type_uc = strtoupper($type);
  232. switch ($field) {
  233. case 'name':
  234. case 'displayname':
  235. $this->raw['FN'][0][0] = $this->displayname = $value;
  236. break;
  237. case 'surname':
  238. $this->raw['N'][0][0] = $this->surname = $value;
  239. break;
  240. case 'firstname':
  241. $this->raw['N'][0][1] = $this->firstname = $value;
  242. break;
  243. case 'middlename':
  244. $this->raw['N'][0][2] = $this->middlename = $value;
  245. break;
  246. case 'prefix':
  247. $this->raw['N'][0][3] = $value;
  248. break;
  249. case 'suffix':
  250. $this->raw['N'][0][4] = $value;
  251. break;
  252. case 'nickname':
  253. $this->raw['NICKNAME'][0][0] = $this->nickname = $value;
  254. break;
  255. case 'organization':
  256. $this->raw['ORG'][0][0] = $this->organization = $value;
  257. break;
  258. case 'photo':
  259. if (strpos($value, 'http:') === 0) {
  260. // TODO: fetch file from URL and save it locally?
  261. $this->raw['PHOTO'][0] = array(0 => $value, 'url' => true);
  262. }
  263. else {
  264. $this->raw['PHOTO'][0] = array(0 => $value, 'base64' => (bool) preg_match('![^a-z0-9/=+-]!i', $value));
  265. }
  266. break;
  267. case 'email':
  268. $this->raw['EMAIL'][] = array(0 => $value, 'type' => array_filter(array('INTERNET', $type_uc)));
  269. $this->email[] = $value;
  270. break;
  271. case 'im':
  272. // save IM subtypes into extension fields
  273. $typemap = array_flip($this->immap);
  274. if ($field = $typemap[strtolower($type)])
  275. $this->raw[$field][] = array(0 => $value);
  276. break;
  277. case 'birthday':
  278. case 'anniversary':
  279. if (($val = rcube_utils::strtotime($value)) && ($fn = self::$fieldmap[$field]))
  280. $this->raw[$fn][] = array(0 => date('Y-m-d', $val), 'value' => array('date'));
  281. break;
  282. case 'address':
  283. if ($this->addresstypemap[$type_uc])
  284. $type = $this->addresstypemap[$type_uc];
  285. $value = $value[0] ? $value : array('', '', $value['street'], $value['locality'], $value['region'], $value['zipcode'], $value['country']);
  286. // fall through if not empty
  287. if (!strlen(join('', $value)))
  288. break;
  289. default:
  290. if ($field == 'phone' && $this->phonetypemap[$type_uc])
  291. $type = $this->phonetypemap[$type_uc];
  292. if (($tag = self::$fieldmap[$field]) && (is_array($value) || strlen($value))) {
  293. $index = count($this->raw[$tag]);
  294. $this->raw[$tag][$index] = (array)$value;
  295. if ($type) {
  296. $typemap = array_flip($this->typemap);
  297. $this->raw[$tag][$index]['type'] = explode(',', ($typemap[$type_uc] ? $typemap[$type_uc] : $type));
  298. }
  299. }
  300. break;
  301. }
  302. }
  303. /**
  304. * Setter for individual vcard properties
  305. *
  306. * @param string VCard tag name
  307. * @param array Value-set of this vcard property
  308. * @param boolean Set to true if the value-set should be appended instead of replacing any existing value-set
  309. */
  310. public function set_raw($tag, $value, $append = false)
  311. {
  312. $index = $append ? count($this->raw[$tag]) : 0;
  313. $this->raw[$tag][$index] = (array)$value;
  314. }
  315. /**
  316. * Find index with the '$type' attribute
  317. *
  318. * @param string Field name
  319. * @return int Field index having $type set
  320. */
  321. private function get_type_index($field, $type = 'pref')
  322. {
  323. $result = 0;
  324. if ($this->raw[$field]) {
  325. foreach ($this->raw[$field] as $i => $data) {
  326. if (is_array($data['type']) && in_array_nocase('pref', $data['type']))
  327. $result = $i;
  328. }
  329. }
  330. return $result;
  331. }
  332. /**
  333. * Convert a whole vcard (array) to UTF-8.
  334. * If $force_charset is null, each member value that has a charset parameter will be converted
  335. */
  336. private static function charset_convert($card, $force_charset = null)
  337. {
  338. foreach ($card as $key => $node) {
  339. foreach ($node as $i => $subnode) {
  340. if (is_array($subnode) && (($charset = $force_charset) || ($subnode['charset'] && ($charset = $subnode['charset'][0])))) {
  341. foreach ($subnode as $j => $value) {
  342. if (is_numeric($j) && is_string($value))
  343. $card[$key][$i][$j] = rcube_charset::convert($value, $charset);
  344. }
  345. unset($card[$key][$i]['charset']);
  346. }
  347. }
  348. }
  349. return $card;
  350. }
  351. /**
  352. * Extends fieldmap definition
  353. */
  354. public function extend_fieldmap($map)
  355. {
  356. if (is_array($map))
  357. self::$fieldmap = array_merge($map, self::$fieldmap);
  358. }
  359. /**
  360. * Factory method to import a vcard file
  361. *
  362. * @param string vCard file content
  363. * @return array List of rcube_vcard objects
  364. */
  365. public static function import($data)
  366. {
  367. $out = array();
  368. // check if charsets are specified (usually vcard version < 3.0 but this is not reliable)
  369. if (preg_match('/charset=/i', substr($data, 0, 2048)))
  370. $charset = null;
  371. // detect charset and convert to utf-8
  372. else if (($charset = self::detect_encoding($data)) && $charset != RCMAIL_CHARSET) {
  373. $data = rcube_charset::convert($data, $charset);
  374. $data = preg_replace(array('/^[\xFE\xFF]{2}/', '/^\xEF\xBB\xBF/', '/^\x00+/'), '', $data); // also remove BOM
  375. $charset = RCMAIL_CHARSET;
  376. }
  377. $vcard_block = '';
  378. $in_vcard_block = false;
  379. foreach (preg_split("/[\r\n]+/", $data) as $i => $line) {
  380. if ($in_vcard_block && !empty($line))
  381. $vcard_block .= $line . "\n";
  382. $line = trim($line);
  383. if (preg_match('/^END:VCARD$/i', $line)) {
  384. // parse vcard
  385. $obj = new rcube_vcard(self::cleanup($vcard_block), $charset, true, self::$fieldmap);
  386. if (!empty($obj->displayname) || !empty($obj->email))
  387. $out[] = $obj;
  388. $in_vcard_block = false;
  389. }
  390. else if (preg_match('/^BEGIN:VCARD$/i', $line)) {
  391. $vcard_block = $line . "\n";
  392. $in_vcard_block = true;
  393. }
  394. }
  395. return $out;
  396. }
  397. /**
  398. * Normalize vcard data for better parsing
  399. *
  400. * @param string vCard block
  401. * @return string Cleaned vcard block
  402. */
  403. private static function cleanup($vcard)
  404. {
  405. // Convert special types (like Skype) to normal type='skype' classes with this simple regex ;)
  406. $vcard = preg_replace(
  407. '/item(\d+)\.(TEL|EMAIL|URL)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
  408. '\2;type=\5\3:\4',
  409. $vcard);
  410. // convert Apple X-ABRELATEDNAMES into X-* fields for better compatibility
  411. $vcard = preg_replace_callback(
  412. '/item(\d+)\.(X-ABRELATEDNAMES)([^:]*?):(.*?)item\1.X-ABLabel:(?:_\$!<)?([\w-() ]*)(?:>!\$_)?./s',
  413. array('self', 'x_abrelatednames_callback'),
  414. $vcard);
  415. // Remove cruft like item1.X-AB*, item1.ADR instead of ADR, and empty lines
  416. $vcard = preg_replace(array('/^item\d*\.X-AB.*$/m', '/^item\d*\./m', "/\n+/"), array('', '', "\n"), $vcard);
  417. // convert X-WAB-GENDER to X-GENDER
  418. if (preg_match('/X-WAB-GENDER:(\d)/', $vcard, $matches)) {
  419. $value = $matches[1] == '2' ? 'male' : 'female';
  420. $vcard = preg_replace('/X-WAB-GENDER:\d/', 'X-GENDER:' . $value, $vcard);
  421. }
  422. // if N doesn't have any semicolons, add some
  423. $vcard = preg_replace('/^(N:[^;\R]*)$/m', '\1;;;;', $vcard);
  424. return $vcard;
  425. }
  426. private static function x_abrelatednames_callback($matches)
  427. {
  428. return 'X-' . strtoupper($matches[5]) . $matches[3] . ':'. $matches[4];
  429. }
  430. private static function rfc2425_fold_callback($matches)
  431. {
  432. // chunk_split string and avoid lines breaking multibyte characters
  433. $c = 71;
  434. $out .= substr($matches[1], 0, $c);
  435. for ($n = $c; $c < strlen($matches[1]); $c++) {
  436. // break if length > 75 or mutlibyte character starts after position 71
  437. if ($n > 75 || ($n > 71 && ord($matches[1][$c]) >> 6 == 3)) {
  438. $out .= "\r\n ";
  439. $n = 0;
  440. }
  441. $out .= $matches[1][$c];
  442. $n++;
  443. }
  444. return $out;
  445. }
  446. public static function rfc2425_fold($val)
  447. {
  448. return preg_replace_callback('/([^\n]{72,})/', array('self', 'rfc2425_fold_callback'), $val);
  449. }
  450. /**
  451. * Decodes a vcard block (vcard 3.0 format, unfolded)
  452. * into an array structure
  453. *
  454. * @param string vCard block to parse
  455. * @return array Raw data structure
  456. */
  457. private static function vcard_decode($vcard)
  458. {
  459. // Perform RFC2425 line unfolding and split lines
  460. $vcard = preg_replace(array("/\r/", "/\n\s+/"), '', $vcard);
  461. $lines = explode("\n", $vcard);
  462. $data = array();
  463. for ($i=0; $i < count($lines); $i++) {
  464. if (!preg_match('/^([^:]+):(.+)$/', $lines[$i], $line))
  465. continue;
  466. if (preg_match('/^(BEGIN|END)$/i', $line[1]))
  467. continue;
  468. // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet;TYPE=home:"
  469. if (($data['VERSION'][0] == "2.1") && preg_match('/^([^;]+);([^:]+)/', $line[1], $regs2) && !preg_match('/^TYPE=/i', $regs2[2])) {
  470. $line[1] = $regs2[1];
  471. foreach (explode(';', $regs2[2]) as $prop)
  472. $line[1] .= ';' . (strpos($prop, '=') ? $prop : 'TYPE='.$prop);
  473. }
  474. if (preg_match_all('/([^\\;]+);?/', $line[1], $regs2)) {
  475. $entry = array();
  476. $field = strtoupper($regs2[1][0]);
  477. $enc = null;
  478. foreach($regs2[1] as $attrid => $attr) {
  479. if ((list($key, $value) = explode('=', $attr)) && $value) {
  480. $value = trim($value);
  481. if ($key == 'ENCODING') {
  482. $value = strtoupper($value);
  483. // add next line(s) to value string if QP line end detected
  484. if ($value == 'QUOTED-PRINTABLE') {
  485. while (preg_match('/=$/', $lines[$i]))
  486. $line[2] .= "\n" . $lines[++$i];
  487. }
  488. $enc = $value;
  489. }
  490. else {
  491. $lc_key = strtolower($key);
  492. $entry[$lc_key] = array_merge((array)$entry[$lc_key], (array)self::vcard_unquote($value, ','));
  493. }
  494. }
  495. else if ($attrid > 0) {
  496. $entry[strtolower($key)] = true; // true means attr without =value
  497. }
  498. }
  499. // decode value
  500. if ($enc || !empty($entry['base64'])) {
  501. // save encoding type (#1488432)
  502. if ($enc == 'B') {
  503. $entry['encoding'] = 'B';
  504. // should we use vCard 3.0 instead?
  505. // $entry['base64'] = true;
  506. }
  507. $line[2] = self::decode_value($line[2], $enc ? $enc : 'base64');
  508. }
  509. if ($enc != 'B' && empty($entry['base64'])) {
  510. $line[2] = self::vcard_unquote($line[2]);
  511. }
  512. $entry = array_merge($entry, (array) $line[2]);
  513. $data[$field][] = $entry;
  514. }
  515. }
  516. unset($data['VERSION']);
  517. return $data;
  518. }
  519. /**
  520. * Decode a given string with the encoding rule from ENCODING attributes
  521. *
  522. * @param string String to decode
  523. * @param string Encoding type (quoted-printable and base64 supported)
  524. * @return string Decoded 8bit value
  525. */
  526. private static function decode_value($value, $encoding)
  527. {
  528. switch (strtolower($encoding)) {
  529. case 'quoted-printable':
  530. self::$values_decoded = true;
  531. return quoted_printable_decode($value);
  532. case 'base64':
  533. case 'b':
  534. self::$values_decoded = true;
  535. return base64_decode($value);
  536. default:
  537. return $value;
  538. }
  539. }
  540. /**
  541. * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
  542. *
  543. * @param array Raw data structure to encode
  544. * @return string vCard encoded string
  545. */
  546. static function vcard_encode($data)
  547. {
  548. foreach((array)$data as $type => $entries) {
  549. /* valid N has 5 properties */
  550. while ($type == "N" && is_array($entries[0]) && count($entries[0]) < 5)
  551. $entries[0][] = "";
  552. // make sure FN is not empty (required by RFC2426)
  553. if ($type == "FN" && empty($entries))
  554. $entries[0] = $data['EMAIL'][0][0];
  555. foreach((array)$entries as $entry) {
  556. $attr = '';
  557. if (is_array($entry)) {
  558. $value = array();
  559. foreach($entry as $attrname => $attrvalues) {
  560. if (is_int($attrname)) {
  561. if (!empty($entry['base64']) || $entry['encoding'] == 'B') {
  562. $attrvalues = base64_encode($attrvalues);
  563. }
  564. $value[] = $attrvalues;
  565. }
  566. else if (is_bool($attrvalues)) {
  567. if ($attrvalues) {
  568. $attr .= strtoupper(";$attrname"); // true means just tag, not tag=value, as in PHOTO;BASE64:...
  569. }
  570. }
  571. else {
  572. foreach((array)$attrvalues as $attrvalue)
  573. $attr .= strtoupper(";$attrname=") . self::vcard_quote($attrvalue, ',');
  574. }
  575. }
  576. }
  577. else {
  578. $value = $entry;
  579. }
  580. // skip empty entries
  581. if (self::is_empty($value))
  582. continue;
  583. $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . self::$eol;
  584. }
  585. }
  586. return 'BEGIN:VCARD' . self::$eol . 'VERSION:3.0' . self::$eol . $vcard . 'END:VCARD';
  587. }
  588. /**
  589. * Join indexed data array to a vcard quoted string
  590. *
  591. * @param array Field data
  592. * @param string Separator
  593. * @return string Joined and quoted string
  594. */
  595. private static function vcard_quote($s, $sep = ';')
  596. {
  597. if (is_array($s)) {
  598. foreach($s as $part) {
  599. $r[] = self::vcard_quote($part, $sep);
  600. }
  601. return(implode($sep, (array)$r));
  602. }
  603. else {
  604. return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', ',' => '\,', ';' => '\;'));
  605. }
  606. }
  607. /**
  608. * Split quoted string
  609. *
  610. * @param string vCard string to split
  611. * @param string Separator char/string
  612. * @return array List with splited values
  613. */
  614. private static function vcard_unquote($s, $sep = ';')
  615. {
  616. // break string into parts separated by $sep, but leave escaped $sep alone
  617. if (count($parts = explode($sep, strtr($s, array("\\$sep" => "\007")))) > 1) {
  618. foreach($parts as $s) {
  619. $result[] = self::vcard_unquote(strtr($s, array("\007" => "\\$sep")), $sep);
  620. }
  621. return $result;
  622. }
  623. else {
  624. return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\N' => "\n", '\,' => ',', '\;' => ';', '\:' => ':'));
  625. }
  626. }
  627. /**
  628. * Check if vCard entry is empty: empty string or an array with
  629. * all entries empty.
  630. *
  631. * @param mixed $value Attribute value (string or array)
  632. *
  633. * @return bool True if the value is empty, False otherwise
  634. */
  635. private static function is_empty($value)
  636. {
  637. foreach ((array)$value as $v) {
  638. if (((string)$v) !== '') {
  639. return false;
  640. }
  641. }
  642. return true;
  643. }
  644. /**
  645. * Extract array values by a filter
  646. *
  647. * @param array Array to filter
  648. * @param keys Array or comma separated list of values to keep
  649. * @param boolean Invert key selection: remove the listed values
  650. * @return array The filtered array
  651. */
  652. private static function array_filter($arr, $values, $inverse = false)
  653. {
  654. if (!is_array($values))
  655. $values = explode(',', $values);
  656. $result = array();
  657. $keep = array_flip((array)$values);
  658. foreach ($arr as $key => $val)
  659. if ($inverse != isset($keep[strtolower($val)]))
  660. $result[$key] = $val;
  661. return $result;
  662. }
  663. /**
  664. * Returns UNICODE type based on BOM (Byte Order Mark)
  665. *
  666. * @param string Input string to test
  667. * @return string Detected encoding
  668. */
  669. private static function detect_encoding($string)
  670. {
  671. $fallback = rcube::get_instance()->config->get('default_charset', 'ISO-8859-1'); // fallback to Latin-1
  672. return rcube_charset::detect($string, $fallback);
  673. }
  674. }