PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/program/lib/Roundcube/rcube_vcard.php

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