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_contacts.php 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2006-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. | Interface to the local address book database |
  13. +-----------------------------------------------------------------------+
  14. | Author: Thomas Bruederli <roundcube@gmail.com> |
  15. +-----------------------------------------------------------------------+
  16. */
  17. /**
  18. * Model class for the local address book database
  19. *
  20. * @package Framework
  21. * @subpackage Addressbook
  22. */
  23. class rcube_contacts extends rcube_addressbook
  24. {
  25. // protected for backward compat. with some plugins
  26. protected $db_name = 'contacts';
  27. protected $db_groups = 'contactgroups';
  28. protected $db_groupmembers = 'contactgroupmembers';
  29. protected $vcard_fieldmap = array();
  30. /**
  31. * Store database connection.
  32. *
  33. * @var rcube_db
  34. */
  35. private $db = null;
  36. private $user_id = 0;
  37. private $filter = null;
  38. private $result = null;
  39. private $cache;
  40. private $table_cols = array('name', 'email', 'firstname', 'surname');
  41. private $fulltext_cols = array('name', 'firstname', 'surname', 'middlename', 'nickname',
  42. 'jobtitle', 'organization', 'department', 'maidenname', 'email', 'phone',
  43. 'address', 'street', 'locality', 'zipcode', 'region', 'country', 'website', 'im', 'notes');
  44. // public properties
  45. public $primary_key = 'contact_id';
  46. public $name;
  47. public $readonly = false;
  48. public $groups = true;
  49. public $undelete = true;
  50. public $list_page = 1;
  51. public $page_size = 10;
  52. public $group_id = 0;
  53. public $ready = false;
  54. public $coltypes = array('name', 'firstname', 'surname', 'middlename', 'prefix', 'suffix', 'nickname',
  55. 'jobtitle', 'organization', 'department', 'assistant', 'manager',
  56. 'gender', 'maidenname', 'spouse', 'email', 'phone', 'address',
  57. 'birthday', 'anniversary', 'website', 'im', 'notes', 'photo');
  58. public $date_cols = array('birthday', 'anniversary');
  59. const SEPARATOR = ',';
  60. /**
  61. * Object constructor
  62. *
  63. * @param object $dbconn Instance of the rcube_db class
  64. * @param integer $user User-ID
  65. */
  66. function __construct($dbconn, $user)
  67. {
  68. $this->db = $dbconn;
  69. $this->user_id = $user;
  70. $this->ready = $this->db && !$this->db->is_error();
  71. }
  72. /**
  73. * Returns addressbook name
  74. */
  75. function get_name()
  76. {
  77. return $this->name;
  78. }
  79. /**
  80. * Save a search string for future listings
  81. *
  82. * @param string SQL params to use in listing method
  83. */
  84. function set_search_set($filter)
  85. {
  86. $this->filter = $filter;
  87. $this->cache = null;
  88. }
  89. /**
  90. * Getter for saved search properties
  91. *
  92. * @return mixed Search properties used by this class
  93. */
  94. function get_search_set()
  95. {
  96. return $this->filter;
  97. }
  98. /**
  99. * Setter for the current group
  100. * (empty, has to be re-implemented by extending class)
  101. */
  102. function set_group($gid)
  103. {
  104. $this->group_id = $gid;
  105. $this->cache = null;
  106. }
  107. /**
  108. * Reset all saved results and search parameters
  109. */
  110. function reset()
  111. {
  112. $this->result = null;
  113. $this->filter = null;
  114. $this->cache = null;
  115. }
  116. /**
  117. * List all active contact groups of this source
  118. *
  119. * @param string $search Search string to match group name
  120. * @param int $mode Matching mode:
  121. * 0 - partial (*abc*),
  122. * 1 - strict (=),
  123. * 2 - prefix (abc*)
  124. *
  125. * @return array Indexed list of contact groups, each a hash array
  126. */
  127. function list_groups($search = null, $mode = 0)
  128. {
  129. $results = array();
  130. if (!$this->groups)
  131. return $results;
  132. if ($search) {
  133. switch (intval($mode)) {
  134. case 1:
  135. $sql_filter = $this->db->ilike('name', $search);
  136. break;
  137. case 2:
  138. $sql_filter = $this->db->ilike('name', $search . '%');
  139. break;
  140. default:
  141. $sql_filter = $this->db->ilike('name', '%' . $search . '%');
  142. }
  143. $sql_filter = " AND $sql_filter";
  144. }
  145. $sql_result = $this->db->query(
  146. "SELECT * FROM " . $this->db->table_name($this->db_groups, true)
  147. . " WHERE `del` <> 1 AND `user_id` = ?" . $sql_filter
  148. . " ORDER BY `name`",
  149. $this->user_id);
  150. while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
  151. $sql_arr['ID'] = $sql_arr['contactgroup_id'];
  152. $results[] = $sql_arr;
  153. }
  154. return $results;
  155. }
  156. /**
  157. * Get group properties such as name and email address(es)
  158. *
  159. * @param string $group_id Group identifier
  160. *
  161. * @return array Group properties as hash array
  162. */
  163. function get_group($group_id)
  164. {
  165. $sql_result = $this->db->query(
  166. "SELECT * FROM " . $this->db->table_name($this->db_groups, true)
  167. . " WHERE `del` <> 1 AND `contactgroup_id` = ? AND `user_id` = ?",
  168. $group_id, $this->user_id);
  169. if ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
  170. $sql_arr['ID'] = $sql_arr['contactgroup_id'];
  171. return $sql_arr;
  172. }
  173. return null;
  174. }
  175. /**
  176. * List the current set of contact records
  177. *
  178. * @param array List of cols to show, Null means all
  179. * @param int Only return this number of records, use negative values for tail
  180. * @param boolean True to skip the count query (select only)
  181. *
  182. * @return array Indexed list of contact records, each a hash array
  183. */
  184. function list_records($cols = null, $subset = 0, $nocount = false)
  185. {
  186. if ($nocount || $this->list_page <= 1) {
  187. // create dummy result, we don't need a count now
  188. $this->result = new rcube_result_set();
  189. } else {
  190. // count all records
  191. $this->result = $this->count();
  192. }
  193. $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
  194. $length = $subset != 0 ? abs($subset) : $this->page_size;
  195. if ($this->group_id)
  196. $join = " LEFT JOIN " . $this->db->table_name($this->db_groupmembers, true) . " AS m".
  197. " ON (m.`contact_id` = c.`".$this->primary_key."`)";
  198. $order_col = (in_array($this->sort_col, $this->table_cols) ? $this->sort_col : 'name');
  199. $order_cols = array("c.`$order_col`");
  200. if ($order_col == 'firstname')
  201. $order_cols[] = 'c.`surname`';
  202. else if ($order_col == 'surname')
  203. $order_cols[] = 'c.`firstname`';
  204. if ($order_col != 'name')
  205. $order_cols[] = 'c.`name`';
  206. $order_cols[] = 'c.`email`';
  207. $sql_result = $this->db->limitquery(
  208. "SELECT * FROM " . $this->db->table_name($this->db_name, true) . " AS c" .
  209. $join .
  210. " WHERE c.`del` <> 1" .
  211. " AND c.`user_id` = ?" .
  212. ($this->group_id ? " AND m.`contactgroup_id` = ?" : "").
  213. ($this->filter ? " AND (".$this->filter.")" : "") .
  214. " ORDER BY ". $this->db->concat($order_cols) .
  215. " " . $this->sort_order,
  216. $start_row,
  217. $length,
  218. $this->user_id,
  219. $this->group_id);
  220. // determine whether we have to parse the vcard or if only db cols are requested
  221. $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
  222. while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
  223. $sql_arr['ID'] = $sql_arr[$this->primary_key];
  224. if ($read_vcard)
  225. $sql_arr = $this->convert_db_data($sql_arr);
  226. else {
  227. $sql_arr['email'] = $sql_arr['email'] ? explode(self::SEPARATOR, $sql_arr['email']) : array();
  228. $sql_arr['email'] = array_map('trim', $sql_arr['email']);
  229. }
  230. $this->result->add($sql_arr);
  231. }
  232. $cnt = count($this->result->records);
  233. // update counter
  234. if ($nocount)
  235. $this->result->count = $cnt;
  236. else if ($this->list_page <= 1) {
  237. if ($cnt < $this->page_size && $subset == 0)
  238. $this->result->count = $cnt;
  239. else if (isset($this->cache['count']))
  240. $this->result->count = $this->cache['count'];
  241. else
  242. $this->result->count = $this->_count();
  243. }
  244. return $this->result;
  245. }
  246. /**
  247. * Search contacts
  248. *
  249. * @param mixed $fields The field name or array of field names to search in
  250. * @param mixed $value Search value (or array of values when $fields is array)
  251. * @param int $mode Matching mode:
  252. * 0 - partial (*abc*),
  253. * 1 - strict (=),
  254. * 2 - prefix (abc*)
  255. * @param boolean $select True if results are requested, False if count only
  256. * @param boolean $nocount True to skip the count query (select only)
  257. * @param array $required List of fields that cannot be empty
  258. *
  259. * @return object rcube_result_set Contact records and 'count' value
  260. */
  261. function search($fields, $value, $mode = 0, $select = true, $nocount = false, $required = array())
  262. {
  263. if (!is_array($required) && !empty($required)) {
  264. $required = array($required);
  265. }
  266. $where = $and_where = $post_search = array();
  267. $mode = intval($mode);
  268. $WS = ' ';
  269. $AS = self::SEPARATOR;
  270. // direct ID search
  271. if ($fields == 'ID' || $fields == $this->primary_key) {
  272. $ids = !is_array($value) ? explode(self::SEPARATOR, $value) : $value;
  273. $ids = $this->db->array2list($ids, 'integer');
  274. $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
  275. }
  276. else if (is_array($value)) {
  277. foreach ((array)$fields as $idx => $col) {
  278. $val = $value[$idx];
  279. if (!strlen($val))
  280. continue;
  281. // table column
  282. if (in_array($col, $this->table_cols)) {
  283. switch ($mode) {
  284. case 1: // strict
  285. $where[] = '(' . $this->db->quote_identifier($col) . ' = ' . $this->db->quote($val)
  286. . ' OR ' . $this->db->ilike($col, $val . $AS . '%')
  287. . ' OR ' . $this->db->ilike($col, '%' . $AS . $val . $AS . '%')
  288. . ' OR ' . $this->db->ilike($col, '%' . $AS . $val) . ')';
  289. break;
  290. case 2: // prefix
  291. $where[] = '(' . $this->db->ilike($col, $val . '%')
  292. . ' OR ' . $this->db->ilike($col, $AS . $val . '%') . ')';
  293. break;
  294. default: // partial
  295. $where[] = $this->db->ilike($col, '%' . $val . '%');
  296. }
  297. }
  298. // vCard field
  299. else {
  300. if (in_array($col, $this->fulltext_cols)) {
  301. $where[] = $this->fulltext_sql_where($val, $mode, 'words');
  302. }
  303. $post_search[$col] = mb_strtolower($val);
  304. }
  305. }
  306. }
  307. // fulltext search in all fields
  308. else if ($fields == '*') {
  309. $where[] = $this->fulltext_sql_where($value, $mode, 'words');
  310. }
  311. else {
  312. // require each word in to be present in one of the fields
  313. $words = $mode == 1 ? array($value) : rcube_utils::tokenize_string($value, 1);
  314. foreach ($words as $word) {
  315. $groups = array();
  316. foreach ((array)$fields as $idx => $col) {
  317. $groups[] = $this->fulltext_sql_where($word, $mode, $col);
  318. }
  319. $where[] = '(' . join(' OR ', $groups) . ')';
  320. }
  321. }
  322. foreach (array_intersect($required, $this->table_cols) as $col) {
  323. $and_where[] = $this->db->quote_identifier($col).' <> '.$this->db->quote('');
  324. }
  325. $required = array_diff($required, $this->table_cols);
  326. if (!empty($where)) {
  327. // use AND operator for advanced searches
  328. $where = join(" AND ", $where);
  329. }
  330. if (!empty($and_where))
  331. $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
  332. // Post-searching in vCard data fields
  333. // we will search in all records and then build a where clause for their IDs
  334. if (!empty($post_search) || !empty($required)) {
  335. $ids = array(0);
  336. // build key name regexp
  337. $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
  338. // use initial WHERE clause, to limit records number if possible
  339. if (!empty($where))
  340. $this->set_search_set($where);
  341. // count result pages
  342. $cnt = $this->count()->count;
  343. $pages = ceil($cnt / $this->page_size);
  344. $scnt = count($post_search);
  345. // get (paged) result
  346. for ($i=0; $i<$pages; $i++) {
  347. $this->list_records(null, $i, true);
  348. while ($row = $this->result->next()) {
  349. $id = $row[$this->primary_key];
  350. $found = array();
  351. if (!empty($post_search)) {
  352. foreach (preg_grep($regexp, array_keys($row)) as $col) {
  353. $pos = strpos($col, ':');
  354. $colname = $pos ? substr($col, 0, $pos) : $col;
  355. $search = $post_search[$colname];
  356. foreach ((array)$row[$col] as $value) {
  357. if ($this->compare_search_value($colname, $value, $search, $mode)) {
  358. $found[$colname] = true;
  359. break 2;
  360. }
  361. }
  362. }
  363. }
  364. // check if required fields are present
  365. if (!empty($required)) {
  366. foreach ($required as $req) {
  367. $hit = false;
  368. foreach ($row as $c => $values) {
  369. if ($c === $req || strpos($c, $req.':') === 0) {
  370. if ((is_string($row[$c]) && strlen($row[$c])) || !empty($row[$c])) {
  371. $hit = true;
  372. break;
  373. }
  374. }
  375. }
  376. if (!$hit) {
  377. continue 2;
  378. }
  379. }
  380. }
  381. // all fields match
  382. if (count($found) >= $scnt) {
  383. $ids[] = $id;
  384. }
  385. }
  386. }
  387. // build WHERE clause
  388. $ids = $this->db->array2list($ids, 'integer');
  389. $where = 'c.`' . $this->primary_key.'` IN ('.$ids.')';
  390. // reset counter
  391. unset($this->cache['count']);
  392. // when we know we have an empty result
  393. if ($ids == '0') {
  394. $this->set_search_set($where);
  395. return ($this->result = new rcube_result_set(0, 0));
  396. }
  397. }
  398. if (!empty($where)) {
  399. $this->set_search_set($where);
  400. if ($select)
  401. $this->list_records(null, 0, $nocount);
  402. else
  403. $this->result = $this->count();
  404. }
  405. return $this->result;
  406. }
  407. /**
  408. * Helper method to compose SQL where statements for fulltext searching
  409. */
  410. private function fulltext_sql_where($value, $mode, $col = 'words', $bool = 'AND')
  411. {
  412. $WS = ' ';
  413. $AS = $col == 'words' ? $WS : self::SEPARATOR;
  414. $words = $col == 'words' ? rcube_utils::normalize_string($value, true) : array($value);
  415. $where = array();
  416. foreach ($words as $word) {
  417. switch ($mode) {
  418. case 1: // strict
  419. $where[] = '(' . $this->db->ilike($col, $word)
  420. . ' OR ' . $this->db->ilike($col, $word . $AS . '%')
  421. . ' OR ' . $this->db->ilike($col, '%' . $AS . $word . $AS . '%')
  422. . ' OR ' . $this->db->ilike($col, '%' . $AS . $word) . ')';
  423. break;
  424. case 2: // prefix
  425. $where[] = '(' . $this->db->ilike($col, $word . '%')
  426. . ' OR ' . $this->db->ilike($col, '%' . $AS . $word . '%') . ')';
  427. break;
  428. default: // partial
  429. $where[] = $this->db->ilike($col, '%' . $word . '%');
  430. }
  431. }
  432. return count($where) ? '(' . join(" $bool ", $where) . ')' : '';
  433. }
  434. /**
  435. * Count number of available contacts in database
  436. *
  437. * @return rcube_result_set Result object
  438. */
  439. function count()
  440. {
  441. $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
  442. return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
  443. }
  444. /**
  445. * Count number of available contacts in database
  446. *
  447. * @return int Contacts count
  448. */
  449. private function _count()
  450. {
  451. if ($this->group_id)
  452. $join = " LEFT JOIN " . $this->db->table_name($this->db_groupmembers, true) . " AS m".
  453. " ON (m.`contact_id` = c.`".$this->primary_key."`)";
  454. // count contacts for this user
  455. $sql_result = $this->db->query(
  456. "SELECT COUNT(c.`contact_id`) AS rows".
  457. " FROM " . $this->db->table_name($this->db_name, true) . " AS c".
  458. $join.
  459. " WHERE c.`del` <> 1".
  460. " AND c.`user_id` = ?".
  461. ($this->group_id ? " AND m.`contactgroup_id` = ?" : "").
  462. ($this->filter ? " AND (".$this->filter.")" : ""),
  463. $this->user_id,
  464. $this->group_id
  465. );
  466. $sql_arr = $this->db->fetch_assoc($sql_result);
  467. $this->cache['count'] = (int) $sql_arr['rows'];
  468. return $this->cache['count'];
  469. }
  470. /**
  471. * Return the last result set
  472. *
  473. * @return mixed Result array or NULL if nothing selected yet
  474. */
  475. function get_result()
  476. {
  477. return $this->result;
  478. }
  479. /**
  480. * Get a specific contact record
  481. *
  482. * @param mixed $id Record identifier(s)
  483. * @param bool $assoc Enables returning associative array
  484. *
  485. * @return rcube_result_set|array Result object with all record fields
  486. */
  487. function get_record($id, $assoc = false)
  488. {
  489. // return cached result
  490. if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id) {
  491. return $assoc ? $first : $this->result;
  492. }
  493. $this->db->query(
  494. "SELECT * FROM " . $this->db->table_name($this->db_name, true).
  495. " WHERE `contact_id` = ?".
  496. " AND `user_id` = ?".
  497. " AND `del` <> 1",
  498. $id,
  499. $this->user_id
  500. );
  501. $this->result = null;
  502. if ($sql_arr = $this->db->fetch_assoc()) {
  503. $record = $this->convert_db_data($sql_arr);
  504. $this->result = new rcube_result_set(1);
  505. $this->result->add($record);
  506. }
  507. return $assoc && $record ? $record : $this->result;
  508. }
  509. /**
  510. * Get group assignments of a specific contact record
  511. *
  512. * @param mixed $id Record identifier
  513. *
  514. * @return array List of assigned groups as ID=>Name pairs
  515. */
  516. function get_record_groups($id)
  517. {
  518. $results = array();
  519. if (!$this->groups) {
  520. return $results;
  521. }
  522. $sql_result = $this->db->query(
  523. "SELECT cgm.`contactgroup_id`, cg.`name` "
  524. . " FROM " . $this->db->table_name($this->db_groupmembers, true) . " AS cgm"
  525. . " LEFT JOIN " . $this->db->table_name($this->db_groups, true) . " AS cg"
  526. . " ON (cgm.`contactgroup_id` = cg.`contactgroup_id` AND cg.`del` <> 1)"
  527. . " WHERE cgm.`contact_id` = ?",
  528. $id
  529. );
  530. while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
  531. $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
  532. }
  533. return $results;
  534. }
  535. /**
  536. * Check the given data before saving.
  537. * If input not valid, the message to display can be fetched using get_error()
  538. *
  539. * @param array $save_data Associative array with data to save
  540. * @param boolean $autofix Try to fix/complete record automatically
  541. *
  542. * @return boolean True if input is valid, False if not.
  543. */
  544. public function validate(&$save_data, $autofix = false)
  545. {
  546. // validate e-mail addresses
  547. $valid = parent::validate($save_data, $autofix);
  548. // require at least one email address or a name
  549. if ($valid && !strlen($save_data['firstname'].$save_data['surname'].$save_data['name']) && !array_filter($this->get_col_values('email', $save_data, true))) {
  550. $this->set_error(self::ERROR_VALIDATE, 'noemailwarning');
  551. $valid = false;
  552. }
  553. return $valid;
  554. }
  555. /**
  556. * Create a new contact record
  557. *
  558. * @param array $save_data Associative array with save data
  559. * @param bool $check Enables validity checks
  560. *
  561. * @return integer|boolean The created record ID on success, False on error
  562. */
  563. function insert($save_data, $check = false)
  564. {
  565. if (!is_array($save_data)) {
  566. return false;
  567. }
  568. $insert_id = $existing = false;
  569. if ($check) {
  570. foreach ($save_data as $col => $values) {
  571. if (strpos($col, 'email') === 0) {
  572. foreach ((array)$values as $email) {
  573. if ($existing = $this->search('email', $email, false, false))
  574. break 2;
  575. }
  576. }
  577. }
  578. }
  579. $save_data = $this->convert_save_data($save_data);
  580. $a_insert_cols = $a_insert_values = array();
  581. foreach ($save_data as $col => $value) {
  582. $a_insert_cols[] = $this->db->quote_identifier($col);
  583. $a_insert_values[] = $this->db->quote($value);
  584. }
  585. if (!$existing->count && !empty($a_insert_cols)) {
  586. $this->db->query(
  587. "INSERT INTO " . $this->db->table_name($this->db_name, true).
  588. " (`user_id`, `changed`, `del`, ".join(', ', $a_insert_cols).")".
  589. " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
  590. );
  591. $insert_id = $this->db->insert_id($this->db_name);
  592. }
  593. $this->cache = null;
  594. return $insert_id;
  595. }
  596. /**
  597. * Update a specific contact record
  598. *
  599. * @param mixed $id Record identifier
  600. * @param array $save_cols Associative array with save data
  601. *
  602. * @return boolean True on success, False on error
  603. */
  604. function update($id, $save_cols)
  605. {
  606. $updated = false;
  607. $write_sql = array();
  608. $record = $this->get_record($id, true);
  609. $save_cols = $this->convert_save_data($save_cols, $record);
  610. foreach ($save_cols as $col => $value) {
  611. $write_sql[] = sprintf("%s=%s", $this->db->quote_identifier($col), $this->db->quote($value));
  612. }
  613. if (!empty($write_sql)) {
  614. $this->db->query(
  615. "UPDATE " . $this->db->table_name($this->db_name, true).
  616. " SET `changed` = ".$this->db->now().", ".join(', ', $write_sql).
  617. " WHERE `contact_id` = ?".
  618. " AND `user_id` = ?".
  619. " AND `del` <> 1",
  620. $id,
  621. $this->user_id
  622. );
  623. $updated = $this->db->affected_rows();
  624. $this->result = null; // clear current result (from get_record())
  625. }
  626. return !empty($updated);
  627. }
  628. /**
  629. * Convert data stored in the database into output format
  630. */
  631. private function convert_db_data($sql_arr)
  632. {
  633. $record = array();
  634. $record['ID'] = $sql_arr[$this->primary_key];
  635. if ($sql_arr['vcard']) {
  636. unset($sql_arr['email']);
  637. $vcard = new rcube_vcard($sql_arr['vcard'], RCUBE_CHARSET, false, $this->vcard_fieldmap);
  638. $record += $vcard->get_assoc() + $sql_arr;
  639. }
  640. else {
  641. $record += $sql_arr;
  642. $record['email'] = explode(self::SEPARATOR, $record['email']);
  643. $record['email'] = array_map('trim', $record['email']);
  644. }
  645. return $record;
  646. }
  647. /**
  648. * Convert input data for storing in the database
  649. */
  650. private function convert_save_data($save_data, $record = array())
  651. {
  652. $out = array();
  653. $words = '';
  654. // copy values into vcard object
  655. $vcard = new rcube_vcard($record['vcard'] ?: $save_data['vcard'], RCUBE_CHARSET, false, $this->vcard_fieldmap);
  656. $vcard->reset();
  657. // don't store groups in vCard (#1490277)
  658. $vcard->set('groups', null);
  659. unset($save_data['groups']);
  660. foreach ($save_data as $key => $values) {
  661. list($field, $section) = explode(':', $key);
  662. $fulltext = in_array($field, $this->fulltext_cols);
  663. // avoid casting DateTime objects to array
  664. if (is_object($values) && is_a($values, 'DateTime')) {
  665. $values = array(0 => $values);
  666. }
  667. foreach ((array)$values as $value) {
  668. if (isset($value))
  669. $vcard->set($field, $value, $section);
  670. if ($fulltext && is_array($value))
  671. $words .= ' ' . rcube_utils::normalize_string(join(" ", $value));
  672. else if ($fulltext && strlen($value) >= 3)
  673. $words .= ' ' . rcube_utils::normalize_string($value);
  674. }
  675. }
  676. $out['vcard'] = $vcard->export(false);
  677. foreach ($this->table_cols as $col) {
  678. $key = $col;
  679. if (!isset($save_data[$key]))
  680. $key .= ':home';
  681. if (isset($save_data[$key])) {
  682. if (is_array($save_data[$key]))
  683. $out[$col] = join(self::SEPARATOR, $save_data[$key]);
  684. else
  685. $out[$col] = $save_data[$key];
  686. }
  687. }
  688. // save all e-mails in database column
  689. $out['email'] = join(self::SEPARATOR, $vcard->email);
  690. // join words for fulltext search
  691. $out['words'] = join(" ", array_unique(explode(" ", $words)));
  692. return $out;
  693. }
  694. /**
  695. * Mark one or more contact records as deleted
  696. *
  697. * @param array $ids Record identifiers
  698. * @param boolean $force Remove record(s) irreversible (unsupported)
  699. */
  700. function delete($ids, $force = true)
  701. {
  702. if (!is_array($ids)) {
  703. $ids = explode(self::SEPARATOR, $ids);
  704. }
  705. $ids = $this->db->array2list($ids, 'integer');
  706. // flag record as deleted (always)
  707. $this->db->query(
  708. "UPDATE " . $this->db->table_name($this->db_name, true).
  709. " SET `del` = 1, `changed` = ".$this->db->now().
  710. " WHERE `user_id` = ?".
  711. " AND `contact_id` IN ($ids)",
  712. $this->user_id
  713. );
  714. $this->cache = null;
  715. return $this->db->affected_rows();
  716. }
  717. /**
  718. * Undelete one or more contact records
  719. *
  720. * @param array $ids Record identifiers
  721. */
  722. function undelete($ids)
  723. {
  724. if (!is_array($ids)) {
  725. $ids = explode(self::SEPARATOR, $ids);
  726. }
  727. $ids = $this->db->array2list($ids, 'integer');
  728. // clear deleted flag
  729. $this->db->query(
  730. "UPDATE " . $this->db->table_name($this->db_name, true).
  731. " SET `del` = 0, `changed` = ".$this->db->now().
  732. " WHERE `user_id` = ?".
  733. " AND `contact_id` IN ($ids)",
  734. $this->user_id
  735. );
  736. $this->cache = null;
  737. return $this->db->affected_rows();
  738. }
  739. /**
  740. * Remove all records from the database
  741. *
  742. * @param bool $with_groups Remove also groups
  743. *
  744. * @return int Number of removed records
  745. */
  746. function delete_all($with_groups = false)
  747. {
  748. $this->cache = null;
  749. $now = $this->db->now();
  750. $this->db->query("UPDATE " . $this->db->table_name($this->db_name, true)
  751. . " SET `del` = 1, `changed` = $now"
  752. . " WHERE `user_id` = ?", $this->user_id);
  753. $count = $this->db->affected_rows();
  754. if ($with_groups) {
  755. $this->db->query("UPDATE " . $this->db->table_name($this->db_groups, true)
  756. . " SET `del` = 1, `changed` = $now"
  757. . " WHERE `user_id` = ?", $this->user_id);
  758. $count += $this->db->affected_rows();
  759. }
  760. return $count;
  761. }
  762. /**
  763. * Create a contact group with the given name
  764. *
  765. * @param string $name The group name
  766. *
  767. * @return mixed False on error, array with record props in success
  768. */
  769. function create_group($name)
  770. {
  771. $result = false;
  772. // make sure we have a unique name
  773. $name = $this->unique_groupname($name);
  774. $this->db->query(
  775. "INSERT INTO " . $this->db->table_name($this->db_groups, true).
  776. " (`user_id`, `changed`, `name`)".
  777. " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
  778. );
  779. if ($insert_id = $this->db->insert_id($this->db_groups)) {
  780. $result = array('id' => $insert_id, 'name' => $name);
  781. }
  782. return $result;
  783. }
  784. /**
  785. * Delete the given group (and all linked group members)
  786. *
  787. * @param string $gid Group identifier
  788. *
  789. * @return boolean True on success, false if no data was changed
  790. */
  791. function delete_group($gid)
  792. {
  793. // flag group record as deleted
  794. $this->db->query(
  795. "UPDATE " . $this->db->table_name($this->db_groups, true)
  796. . " SET `del` = 1, `changed` = " . $this->db->now()
  797. . " WHERE `contactgroup_id` = ?"
  798. . " AND `user_id` = ?",
  799. $gid, $this->user_id
  800. );
  801. $this->cache = null;
  802. return $this->db->affected_rows();
  803. }
  804. /**
  805. * Rename a specific contact group
  806. *
  807. * @param string $gid Group identifier
  808. * @param string $name New name to set for this group
  809. * @param string $new_gid (not used)
  810. *
  811. * @return boolean New name on success, false if no data was changed
  812. */
  813. function rename_group($gid, $name, &$new_gid)
  814. {
  815. // make sure we have a unique name
  816. $name = $this->unique_groupname($name);
  817. $sql_result = $this->db->query(
  818. "UPDATE " . $this->db->table_name($this->db_groups, true).
  819. " SET `name` = ?, `changed` = ".$this->db->now().
  820. " WHERE `contactgroup_id` = ?".
  821. " AND `user_id` = ?",
  822. $name, $gid, $this->user_id
  823. );
  824. return $this->db->affected_rows($sql_result) ? $name : false;
  825. }
  826. /**
  827. * Add the given contact records the a certain group
  828. *
  829. * @param string Group identifier
  830. * @param array|string List of contact identifiers to be added
  831. *
  832. * @return int Number of contacts added
  833. */
  834. function add_to_group($group_id, $ids)
  835. {
  836. if (!is_array($ids)) {
  837. $ids = explode(self::SEPARATOR, $ids);
  838. }
  839. $added = 0;
  840. $exists = array();
  841. // get existing assignments ...
  842. $sql_result = $this->db->query(
  843. "SELECT `contact_id` FROM " . $this->db->table_name($this->db_groupmembers, true).
  844. " WHERE `contactgroup_id` = ?".
  845. " AND `contact_id` IN (".$this->db->array2list($ids, 'integer').")",
  846. $group_id
  847. );
  848. while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
  849. $exists[] = $sql_arr['contact_id'];
  850. }
  851. // ... and remove them from the list
  852. $ids = array_diff($ids, $exists);
  853. foreach ($ids as $contact_id) {
  854. $this->db->query(
  855. "INSERT INTO " . $this->db->table_name($this->db_groupmembers, true).
  856. " (`contactgroup_id`, `contact_id`, `created`)".
  857. " VALUES (?, ?, ".$this->db->now().")",
  858. $group_id,
  859. $contact_id
  860. );
  861. if ($error = $this->db->is_error()) {
  862. $this->set_error(self::ERROR_SAVING, $error);
  863. }
  864. else {
  865. $added++;
  866. }
  867. }
  868. return $added;
  869. }
  870. /**
  871. * Remove the given contact records from a certain group
  872. *
  873. * @param string Group identifier
  874. * @param array|string List of contact identifiers to be removed
  875. *
  876. * @return int Number of deleted group members
  877. */
  878. function remove_from_group($group_id, $ids)
  879. {
  880. if (!is_array($ids))
  881. $ids = explode(self::SEPARATOR, $ids);
  882. $ids = $this->db->array2list($ids, 'integer');
  883. $sql_result = $this->db->query(
  884. "DELETE FROM " . $this->db->table_name($this->db_groupmembers, true).
  885. " WHERE `contactgroup_id` = ?".
  886. " AND `contact_id` IN ($ids)",
  887. $group_id
  888. );
  889. return $this->db->affected_rows($sql_result);
  890. }
  891. /**
  892. * Check for existing groups with the same name
  893. *
  894. * @param string $name Name to check
  895. *
  896. * @return string A group name which is unique for the current use
  897. */
  898. private function unique_groupname($name)
  899. {
  900. $checkname = $name;
  901. $num = 2;
  902. $hit = false;
  903. do {
  904. $sql_result = $this->db->query(
  905. "SELECT 1 FROM " . $this->db->table_name($this->db_groups, true).
  906. " WHERE `del` <> 1".
  907. " AND `user_id` = ?".
  908. " AND `name` = ?",
  909. $this->user_id,
  910. $checkname);
  911. // append number to make name unique
  912. if ($hit = $this->db->fetch_array($sql_result)) {
  913. $checkname = $name . ' ' . $num++;
  914. }
  915. }
  916. while ($hit);
  917. return $checkname;
  918. }
  919. }