PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/etc/apps/webmail/program/lib/Roundcube/rcube_vcard.php

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