You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_vcard.php 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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(self::cleanup($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. // find well-known address fields
  118. $this->displayname = $this->raw['FN'][0][0];
  119. $this->surname = $this->raw['N'][0][0];
  120. $this->firstname = $this->raw['N'][0][1];
  121. $this->middlename = $this->raw['N'][0][2];
  122. $this->nickname = $this->raw['NICKNAME'][0][0];
  123. $this->organization = $this->raw['ORG'][0][0];
  124. $this->business = ($this->raw['X-ABSHOWAS'][0][0] == 'COMPANY') || (join('', (array)$this->raw['N'][0]) == '' && !empty($this->organization));
  125. foreach ((array)$this->raw['EMAIL'] as $i => $raw_email) {
  126. $this->email[$i] = is_array($raw_email) ? $raw_email[0] : $raw_email;
  127. }
  128. // make the pref e-mail address the first entry in $this->email
  129. $pref_index = $this->get_type_index('EMAIL', 'pref');
  130. if ($pref_index > 0) {
  131. $tmp = $this->email[0];
  132. $this->email[0] = $this->email[$pref_index];
  133. $this->email[$pref_index] = $tmp;
  134. }
  135. // fix broken vcards from Outlook that only supply ORG but not the required N or FN properties
  136. if (!strlen(trim($this->displayname . $this->surname . $this->firstname)) && strlen($this->organization)) {
  137. $this->displayname = $this->organization;
  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]] ?: 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] ?: $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. $this->raw[$tag][] = (array) $value;
  335. if ($type) {
  336. $index = count($this->raw[$tag]) - 1;
  337. $typemap = array_flip($this->typemap);
  338. $this->raw[$tag][$index]['type'] = explode(',', $typemap[$type_uc] ?: $type);
  339. }
  340. }
  341. else {
  342. unset($this->raw[$tag]);
  343. }
  344. break;
  345. }
  346. }
  347. /**
  348. * Setter for individual vcard properties
  349. *
  350. * @param string VCard tag name
  351. * @param array Value-set of this vcard property
  352. * @param boolean Set to true if the value-set should be appended instead of replacing any existing value-set
  353. */
  354. public function set_raw($tag, $value, $append = false)
  355. {
  356. $index = $append && isset($this->raw[$tag]) ? count($this->raw[$tag]) : 0;
  357. $this->raw[$tag][$index] = (array)$value;
  358. }
  359. /**
  360. * Find index with the '$type' attribute
  361. *
  362. * @param string Field name
  363. *
  364. * @return int Field index having $type set
  365. */
  366. private function get_type_index($field)
  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($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-() ]*)(?:>!\$_)?./si',
  469. '/^item\d*\.X-AB.*$/mi', // remove cruft like item1.X-AB*
  470. '/^item\d*\./mi', // 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. $result = array();
  526. for ($i=0; $i < count($lines); $i++) {
  527. if (!($pos = strpos($lines[$i], ':'))) {
  528. continue;
  529. }
  530. $prefix = substr($lines[$i], 0, $pos);
  531. $data = substr($lines[$i], $pos+1);
  532. if (preg_match('/^(BEGIN|END)$/i', $prefix)) {
  533. continue;
  534. }
  535. // convert 2.1-style "EMAIL;internet;home:" to 3.0-style "EMAIL;TYPE=internet;TYPE=home:"
  536. if ($result['VERSION'][0] == "2.1"
  537. && preg_match('/^([^;]+);([^:]+)/', $prefix, $regs2)
  538. && !preg_match('/^TYPE=/i', $regs2[2])
  539. ) {
  540. $prefix = $regs2[1];
  541. foreach (explode(';', $regs2[2]) as $prop) {
  542. $prefix .= ';' . (strpos($prop, '=') ? $prop : 'TYPE='.$prop);
  543. }
  544. }
  545. if (preg_match_all('/([^\\;]+);?/', $prefix, $regs2)) {
  546. $entry = array();
  547. $field = strtoupper($regs2[1][0]);
  548. $enc = null;
  549. foreach ($regs2[1] as $attrid => $attr) {
  550. $attr = preg_replace('/[\s\t\n\r\0\x0B]/', '', $attr);
  551. if ((list($key, $value) = explode('=', $attr)) && $value) {
  552. if ($key == 'ENCODING') {
  553. $value = strtoupper($value);
  554. // add next line(s) to value string if QP line end detected
  555. if ($value == 'QUOTED-PRINTABLE') {
  556. while (preg_match('/=$/', $lines[$i])) {
  557. $data .= "\n" . $lines[++$i];
  558. }
  559. }
  560. $enc = $value == 'BASE64' ? 'B' : $value;
  561. }
  562. else {
  563. $lc_key = strtolower($key);
  564. $entry[$lc_key] = array_merge((array)$entry[$lc_key], (array)self::vcard_unquote($value, ','));
  565. }
  566. }
  567. else if ($attrid > 0) {
  568. $entry[strtolower($key)] = true; // true means attr without =value
  569. }
  570. }
  571. // decode value
  572. if ($enc || !empty($entry['base64'])) {
  573. // save encoding type (#1488432)
  574. if ($enc == 'B') {
  575. $entry['encoding'] = 'B';
  576. // should we use vCard 3.0 instead?
  577. // $entry['base64'] = true;
  578. }
  579. $data = self::decode_value($data, $enc ?: 'base64');
  580. }
  581. else if ($field == 'PHOTO') {
  582. // vCard 4.0 data URI, "PHOTO:data:image/jpeg;base64,..."
  583. if (preg_match('/^data:[a-z\/_-]+;base64,/i', $data, $m)) {
  584. $entry['encoding'] = $enc = 'B';
  585. $data = substr($data, strlen($m[0]));
  586. $data = self::decode_value($data, 'base64');
  587. }
  588. }
  589. if ($enc != 'B' && empty($entry['base64'])) {
  590. $data = self::vcard_unquote($data);
  591. }
  592. $entry = array_merge($entry, (array) $data);
  593. $result[$field][] = $entry;
  594. }
  595. }
  596. unset($result['VERSION']);
  597. return $result;
  598. }
  599. /**
  600. * Decode a given string with the encoding rule from ENCODING attributes
  601. *
  602. * @param string String to decode
  603. * @param string Encoding type (quoted-printable and base64 supported)
  604. *
  605. * @return string Decoded 8bit value
  606. */
  607. private static function decode_value($value, $encoding)
  608. {
  609. switch (strtolower($encoding)) {
  610. case 'quoted-printable':
  611. self::$values_decoded = true;
  612. return quoted_printable_decode($value);
  613. case 'base64':
  614. case 'b':
  615. self::$values_decoded = true;
  616. return base64_decode($value);
  617. default:
  618. return $value;
  619. }
  620. }
  621. /**
  622. * Encodes an entry for storage in our database (vcard 3.0 format, unfolded)
  623. *
  624. * @param array Raw data structure to encode
  625. *
  626. * @return string vCard encoded string
  627. */
  628. static function vcard_encode($data)
  629. {
  630. foreach ((array)$data as $type => $entries) {
  631. // valid N has 5 properties
  632. while ($type == "N" && is_array($entries[0]) && count($entries[0]) < 5) {
  633. $entries[0][] = "";
  634. }
  635. // make sure FN is not empty (required by RFC2426)
  636. if ($type == "FN" && empty($entries)) {
  637. $entries[0] = $data['EMAIL'][0][0];
  638. }
  639. foreach ((array)$entries as $entry) {
  640. $attr = '';
  641. if (is_array($entry)) {
  642. $value = array();
  643. foreach ($entry as $attrname => $attrvalues) {
  644. if (is_int($attrname)) {
  645. if (!empty($entry['base64']) || $entry['encoding'] == 'B') {
  646. $attrvalues = base64_encode($attrvalues);
  647. }
  648. $value[] = $attrvalues;
  649. }
  650. else if (is_bool($attrvalues)) {
  651. // true means just a tag, not tag=value, as in PHOTO;BASE64:...
  652. if ($attrvalues) {
  653. // vCard v3 uses ENCODING=b (#1489183)
  654. if ($attrname == 'base64') {
  655. $attr .= ";ENCODING=b";
  656. }
  657. else {
  658. $attr .= strtoupper(";$attrname");
  659. }
  660. }
  661. }
  662. else {
  663. foreach ((array)$attrvalues as $attrvalue) {
  664. $attr .= strtoupper(";$attrname=") . self::vcard_quote($attrvalue, ',');
  665. }
  666. }
  667. }
  668. }
  669. else {
  670. $value = $entry;
  671. }
  672. // skip empty entries
  673. if (self::is_empty($value)) {
  674. continue;
  675. }
  676. $vcard .= self::vcard_quote($type) . $attr . ':' . self::vcard_quote($value) . self::$eol;
  677. }
  678. }
  679. return 'BEGIN:VCARD' . self::$eol . 'VERSION:3.0' . self::$eol . $vcard . 'END:VCARD';
  680. }
  681. /**
  682. * Join indexed data array to a vcard quoted string
  683. *
  684. * @param array Field data
  685. * @param string Separator
  686. *
  687. * @return string Joined and quoted string
  688. */
  689. public static function vcard_quote($s, $sep = ';')
  690. {
  691. if (is_array($s)) {
  692. foreach ($s as $part) {
  693. $r[] = self::vcard_quote($part, $sep);
  694. }
  695. return(implode($sep, (array)$r));
  696. }
  697. return strtr($s, array('\\' => '\\\\', "\r" => '', "\n" => '\n', $sep => '\\'.$sep));
  698. }
  699. /**
  700. * Split quoted string
  701. *
  702. * @param string vCard string to split
  703. * @param string Separator char/string
  704. *
  705. * @return array List with splited values
  706. */
  707. private static function vcard_unquote($s, $sep = ';')
  708. {
  709. // break string into parts separated by $sep
  710. if (!empty($sep)) {
  711. // Handle properly backslash escaping (#1488896)
  712. $rep1 = array("\\\\" => "\010", "\\$sep" => "\007");
  713. $rep2 = array("\007" => "\\$sep", "\010" => "\\\\");
  714. if (count($parts = explode($sep, strtr($s, $rep1))) > 1) {
  715. foreach ($parts as $s) {
  716. $result[] = self::vcard_unquote(strtr($s, $rep2));
  717. }
  718. return $result;
  719. }
  720. $s = trim(strtr($s, $rep2));
  721. }
  722. // some implementations (GMail) use non-standard backslash before colon (#1489085)
  723. // we will handle properly any backslashed character - removing dummy backslahes
  724. // return strtr($s, array("\r" => '', '\\\\' => '\\', '\n' => "\n", '\N' => "\n", '\,' => ',', '\;' => ';'));
  725. $s = str_replace("\r", '', $s);
  726. $pos = 0;
  727. while (($pos = strpos($s, '\\', $pos)) !== false) {
  728. $next = substr($s, $pos + 1, 1);
  729. if ($next == 'n' || $next == 'N') {
  730. $s = substr_replace($s, "\n", $pos, 2);
  731. }
  732. else {
  733. $s = substr_replace($s, '', $pos, 1);
  734. }
  735. $pos += 1;
  736. }
  737. return $s;
  738. }
  739. /**
  740. * Check if vCard entry is empty: empty string or an array with
  741. * all entries empty.
  742. *
  743. * @param mixed $value Attribute value (string or array)
  744. *
  745. * @return bool True if the value is empty, False otherwise
  746. */
  747. private static function is_empty($value)
  748. {
  749. foreach ((array)$value as $v) {
  750. if (((string)$v) !== '') {
  751. return false;
  752. }
  753. }
  754. return true;
  755. }
  756. /**
  757. * Extract array values by a filter
  758. *
  759. * @param array Array to filter
  760. * @param keys Array or comma separated list of values to keep
  761. * @param boolean Invert key selection: remove the listed values
  762. *
  763. * @return array The filtered array
  764. */
  765. private static function array_filter($arr, $values, $inverse = false)
  766. {
  767. if (!is_array($values)) {
  768. $values = explode(',', $values);
  769. }
  770. $result = array();
  771. $keep = array_flip((array)$values);
  772. foreach ($arr as $key => $val) {
  773. if ($inverse != isset($keep[strtolower($val)])) {
  774. $result[$key] = $val;
  775. }
  776. }
  777. return $result;
  778. }
  779. /**
  780. * Returns UNICODE type based on BOM (Byte Order Mark)
  781. *
  782. * @param string Input string to test
  783. *
  784. * @return string Detected encoding
  785. */
  786. private static function detect_encoding($string)
  787. {
  788. $fallback = rcube::get_instance()->config->get('default_charset', 'ISO-8859-1'); // fallback to Latin-1
  789. return rcube_charset::detect($string, $fallback);
  790. }
  791. }