PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/program/lib/Roundcube/rcube_vcard.php

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