4 +-----------------------------------------------------------------------+
5 | program/include/rcube_contacts.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2006-2011, The Roundcube Dev Team |
9 | Licensed under the GNU GPL |
12 | Interface to the local address book database |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: rcube_contacts.php 5415 2011-11-11 15:04:45Z alec $
24 * Model class for the local address book database
26 * @package Addressbook
28 class rcube_contacts extends rcube_addressbook
30 // protected for backward compat. with some plugins
31 protected $db_name = 'contacts';
32 protected $db_groups = 'contactgroups';
33 protected $db_groupmembers = 'contactgroupmembers';
36 * Store database connection.
42 private $filter = null;
43 private $result = null;
45 private $table_cols = array('name', 'email', 'firstname', 'surname');
46 private $fulltext_cols = array('name', 'firstname', 'surname', 'middlename', 'nickname',
47 'jobtitle', 'organization', 'department', 'maidenname', 'email', 'phone',
48 'address', 'street', 'locality', 'zipcode', 'region', 'country', 'website', 'im', 'notes');
51 public $primary_key = 'contact_id';
53 public $readonly = false;
54 public $groups = true;
55 public $undelete = true;
56 public $list_page = 1;
57 public $page_size = 10;
59 public $ready = false;
60 public $coltypes = array('name', 'firstname', 'surname', 'middlename', 'prefix', 'suffix', 'nickname',
61 'jobtitle', 'organization', 'department', 'assistant', 'manager',
62 'gender', 'maidenname', 'spouse', 'email', 'phone', 'address',
63 'birthday', 'anniversary', 'website', 'im', 'notes', 'photo');
69 * @param object Instance of the rcube_db class
70 * @param integer User-ID
72 function __construct($dbconn, $user)
75 $this->user_id = $user;
76 $this->ready = $this->db && !$this->db->is_error();
81 * Returns addressbook name
90 * Save a search string for future listings
92 * @param string SQL params to use in listing method
94 function set_search_set($filter)
96 $this->filter = $filter;
102 * Getter for saved search properties
104 * @return mixed Search properties used by this class
106 function get_search_set()
108 return $this->filter;
113 * Setter for the current group
114 * (empty, has to be re-implemented by extending class)
116 function set_group($gid)
118 $this->group_id = $gid;
124 * Reset all saved results and search parameters
128 $this->result = null;
129 $this->filter = null;
135 * List all active contact groups of this source
137 * @param string Search string to match group name
138 * @return array Indexed list of contact groups, each a hash array
140 function list_groups($search = null)
147 $sql_filter = $search ? " AND " . $this->db->ilike('name', '%'.$search.'%') : '';
149 $sql_result = $this->db->query(
150 "SELECT * FROM ".get_table_name($this->db_groups).
157 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
158 $sql_arr['ID'] = $sql_arr['contactgroup_id'];
159 $results[] = $sql_arr;
167 * Get group properties such as name and email address(es)
169 * @param string Group identifier
170 * @return array Group properties as hash array
172 function get_group($group_id)
174 $sql_result = $this->db->query(
175 "SELECT * FROM ".get_table_name($this->db_groups).
177 " AND contactgroup_id=?".
179 $group_id, $this->user_id);
181 if ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
182 $sql_arr['ID'] = $sql_arr['contactgroup_id'];
190 * List the current set of contact records
192 * @param array List of cols to show, Null means all
193 * @param int Only return this number of records, use negative values for tail
194 * @param boolean True to skip the count query (select only)
195 * @return array Indexed list of contact records, each a hash array
197 function list_records($cols=null, $subset=0, $nocount=false)
199 if ($nocount || $this->list_page <= 1) {
200 // create dummy result, we don't need a count now
201 $this->result = new rcube_result_set();
204 $this->result = $this->count();
207 $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
208 $length = $subset != 0 ? abs($subset) : $this->page_size;
211 $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
212 " ON (m.contact_id = c.".$this->primary_key.")";
214 $sql_result = $this->db->limitquery(
215 "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
219 ($this->group_id ? " AND m.contactgroup_id=?" : "").
220 ($this->filter ? " AND (".$this->filter.")" : "") .
221 " ORDER BY ". $this->db->concat('c.name', 'c.email'),
227 // determine whether we have to parse the vcard or if only db cols are requested
228 $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
230 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
231 $sql_arr['ID'] = $sql_arr[$this->primary_key];
234 $sql_arr = $this->convert_db_data($sql_arr);
236 $sql_arr['email'] = preg_split('/,\s*/', $sql_arr['email']);
238 // make sure we have a name to display
239 if (empty($sql_arr['name'])) {
240 if (empty($sql_arr['email']))
241 $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
242 $sql_arr['name'] = $sql_arr['email'][0];
245 $this->result->add($sql_arr);
248 $cnt = count($this->result->records);
252 $this->result->count = $cnt;
253 else if ($this->list_page <= 1) {
254 if ($cnt < $this->page_size && $subset == 0)
255 $this->result->count = $cnt;
256 else if (isset($this->cache['count']))
257 $this->result->count = $this->cache['count'];
259 $this->result->count = $this->_count();
262 return $this->result;
269 * @param mixed $fields The field name of array of field names to search in
270 * @param mixed $value Search value (or array of values when $fields is array)
271 * @param int $mode Matching mode:
272 * 0 - partial (*abc*),
275 * @param boolean $select True if results are requested, False if count only
276 * @param boolean $nocount True to skip the count query (select only)
277 * @param array $required List of fields that cannot be empty
279 * @return object rcube_result_set Contact records and 'count' value
281 function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
283 if (!is_array($fields))
284 $fields = array($fields);
285 if (!is_array($required) && !empty($required))
286 $required = array($required);
288 $where = $and_where = array();
289 $mode = intval($mode);
291 foreach ($fields as $idx => $col) {
293 if ($col == 'ID' || $col == $this->primary_key) {
294 $ids = !is_array($value) ? explode(',', $value) : $value;
295 $ids = $this->db->array2list($ids, 'integer');
296 $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
299 // fulltext search in all fields
300 else if ($col == '*') {
302 foreach (explode(" ", self::normalize_string($value)) as $word) {
305 $words[] = '(' . $this->db->ilike('words', $word.' %')
306 . ' OR ' . $this->db->ilike('words', '% '.$word.' %')
307 . ' OR ' . $this->db->ilike('words', '% '.$word) . ')';
310 $words[] = '(' . $this->db->ilike('words', $word.'%')
311 . ' OR ' . $this->db->ilike('words', '% '.$word.'%') . ')';
314 $words[] = $this->db->ilike('words', '%'.$word.'%');
317 $where[] = '(' . join(' AND ', $words) . ')';
320 $val = is_array($value) ? $value[$idx] : $value;
322 if (in_array($col, $this->table_cols)) {
325 $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($val);
328 $where[] = $this->db->ilike($col, $val.'%');
331 $where[] = $this->db->ilike($col, '%'.$val.'%');
336 if (in_array($col, $this->fulltext_cols)) {
337 foreach (explode(" ", self::normalize_string($val)) as $word) {
340 $words[] = '(' . $this->db->ilike('words', $word.' %')
341 . ' OR ' . $this->db->ilike('words', '% '.$word.' %')
342 . ' OR ' . $this->db->ilike('words', '% '.$word) . ')';
345 $words[] = '(' . $this->db->ilike('words', $word.'%')
346 . ' OR ' . $this->db->ilike('words', ' '.$word.'%') . ')';
349 $words[] = $this->db->ilike('words', '%'.$word.'%');
352 $where[] = '(' . join(' AND ', $words) . ')';
354 if (is_array($value))
355 $post_search[$col] = mb_strtolower($val);
360 foreach (array_intersect($required, $this->table_cols) as $col) {
361 $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
364 if (!empty($where)) {
365 // use AND operator for advanced searches
366 $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
369 if (!empty($and_where))
370 $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
372 // Post-searching in vCard data fields
373 // we will search in all records and then build a where clause for their IDs
374 if (!empty($post_search)) {
376 // build key name regexp
377 $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
378 // use initial WHERE clause, to limit records number if possible
380 $this->set_search_set($where);
382 // count result pages
383 $cnt = $this->count();
384 $pages = ceil($cnt / $this->page_size);
385 $scnt = count($post_search);
387 // get (paged) result
388 for ($i=0; $i<$pages; $i++) {
389 $this->list_records(null, $i, true);
390 while ($row = $this->result->next()) {
391 $id = $row[$this->primary_key];
393 foreach (preg_grep($regexp, array_keys($row)) as $col) {
394 $pos = strpos($col, ':');
395 $colname = $pos ? substr($col, 0, $pos) : $col;
396 $search = $post_search[$colname];
397 foreach ((array)$row[$col] as $value) {
398 // composite field, e.g. address
399 foreach ((array)$value as $val) {
400 $val = mb_strtolower($val);
403 $got = ($val == $search);
406 $got = ($search == substr($val, 0, strlen($search)));
409 $got = (strpos($val, $search) !== false);
414 $found[$colname] = true;
421 if (count($found) >= $scnt) {
427 // build WHERE clause
428 $ids = $this->db->array2list($ids, 'integer');
429 $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
431 unset($this->cache['count']);
433 // when we know we have an empty result
435 $this->set_search_set($where);
436 return ($this->result = new rcube_result_set(0, 0));
440 if (!empty($where)) {
441 $this->set_search_set($where);
443 $this->list_records(null, 0, $nocount);
445 $this->result = $this->count();
448 return $this->result;
453 * Count number of available contacts in database
455 * @return rcube_result_set Result object
459 $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
461 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
466 * Count number of available contacts in database
468 * @return int Contacts count
470 private function _count()
473 $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
474 " ON (m.contact_id=c.".$this->primary_key.")";
476 // count contacts for this user
477 $sql_result = $this->db->query(
478 "SELECT COUNT(c.contact_id) AS rows".
479 " FROM ".get_table_name($this->db_name)." AS c".
483 ($this->group_id ? " AND m.contactgroup_id=?" : "").
484 ($this->filter ? " AND (".$this->filter.")" : ""),
489 $sql_arr = $this->db->fetch_assoc($sql_result);
491 $this->cache['count'] = (int) $sql_arr['rows'];
493 return $this->cache['count'];
498 * Return the last result set
500 * @return mixed Result array or NULL if nothing selected yet
502 function get_result()
504 return $this->result;
509 * Get a specific contact record
511 * @param mixed record identifier(s)
512 * @return mixed Result object with all record fields or False if not found
514 function get_record($id, $assoc=false)
516 // return cached result
517 if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
518 return $assoc ? $first : $this->result;
521 "SELECT * FROM ".get_table_name($this->db_name).
522 " WHERE contact_id=?".
529 if ($sql_arr = $this->db->fetch_assoc()) {
530 $record = $this->convert_db_data($sql_arr);
531 $this->result = new rcube_result_set(1);
532 $this->result->add($record);
535 return $assoc && $record ? $record : $this->result;
540 * Get group assignments of a specific contact record
542 * @param mixed Record identifier
543 * @return array List of assigned groups as ID=>Name pairs
545 function get_record_groups($id)
552 $sql_result = $this->db->query(
553 "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
554 " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
555 " WHERE cgm.contact_id=?",
558 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
559 $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
567 * Check the given data before saving.
568 * If input not valid, the message to display can be fetched using get_error()
570 * @param array Assoziative array with data to save
571 * @param boolean Try to fix/complete record automatically
572 * @return boolean True if input is valid, False if not.
574 public function validate(&$save_data, $autofix = false)
576 // validate e-mail addresses
577 $valid = parent::validate($save_data, $autofix);
579 // require at least one e-mail address (syntax check is already done)
580 if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
581 $this->set_error(self::ERROR_VALIDATE, 'noemailwarning');
590 * Create a new contact record
592 * @param array Associative array with save data
593 * @return integer|boolean The created record ID on success, False on error
595 function insert($save_data, $check=false)
597 if (!is_array($save_data))
600 $insert_id = $existing = false;
603 foreach ($save_data as $col => $values) {
604 if (strpos($col, 'email') === 0) {
605 foreach ((array)$values as $email) {
606 if ($existing = $this->search('email', $email, false, false))
613 $save_data = $this->convert_save_data($save_data);
614 $a_insert_cols = $a_insert_values = array();
616 foreach ($save_data as $col => $value) {
617 $a_insert_cols[] = $this->db->quoteIdentifier($col);
618 $a_insert_values[] = $this->db->quote($value);
621 if (!$existing->count && !empty($a_insert_cols)) {
623 "INSERT INTO ".get_table_name($this->db_name).
624 " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
625 " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
628 $insert_id = $this->db->insert_id($this->db_name);
631 // also add the newly created contact to the active group
632 if ($insert_id && $this->group_id)
633 $this->add_to_group($this->group_id, $insert_id);
642 * Update a specific contact record
644 * @param mixed Record identifier
645 * @param array Assoziative array with save data
646 * @return boolean True on success, False on error
648 function update($id, $save_cols)
651 $write_sql = array();
652 $record = $this->get_record($id, true);
653 $save_cols = $this->convert_save_data($save_cols, $record);
655 foreach ($save_cols as $col => $value) {
656 $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
659 if (!empty($write_sql)) {
661 "UPDATE ".get_table_name($this->db_name).
662 " SET changed=".$this->db->now().", ".join(', ', $write_sql).
663 " WHERE contact_id=?".
670 $updated = $this->db->affected_rows();
671 $this->result = null; // clear current result (from get_record())
678 private function convert_db_data($sql_arr)
681 $record['ID'] = $sql_arr[$this->primary_key];
683 if ($sql_arr['vcard']) {
684 unset($sql_arr['email']);
685 $vcard = new rcube_vcard($sql_arr['vcard']);
686 $record += $vcard->get_assoc() + $sql_arr;
690 $record['email'] = preg_split('/,\s*/', $record['email']);
697 private function convert_save_data($save_data, $record = array())
702 // copy values into vcard object
703 $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
705 foreach ($save_data as $key => $values) {
706 list($field, $section) = explode(':', $key);
707 $fulltext = in_array($field, $this->fulltext_cols);
708 foreach ((array)$values as $value) {
710 $vcard->set($field, $value, $section);
711 if ($fulltext && is_array($value))
712 $words .= ' ' . self::normalize_string(join(" ", $value));
713 else if ($fulltext && strlen($value) >= 3)
714 $words .= ' ' . self::normalize_string($value);
717 $out['vcard'] = $vcard->export(false);
719 foreach ($this->table_cols as $col) {
721 if (!isset($save_data[$key]))
723 if (isset($save_data[$key]))
724 $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
727 // save all e-mails in database column
728 $out['email'] = join(", ", $vcard->email);
730 // join words for fulltext search
731 $out['words'] = join(" ", array_unique(explode(" ", $words)));
738 * Mark one or more contact records as deleted
740 * @param array Record identifiers
741 * @param boolean Remove record(s) irreversible (unsupported)
743 function delete($ids, $force=true)
746 $ids = explode(',', $ids);
748 $ids = $this->db->array2list($ids, 'integer');
750 // flag record as deleted (always)
752 "UPDATE ".get_table_name($this->db_name).
753 " SET del=1, changed=".$this->db->now().
755 " AND contact_id IN ($ids)",
761 return $this->db->affected_rows();
766 * Undelete one or more contact records
768 * @param array Record identifiers
770 function undelete($ids)
773 $ids = explode(',', $ids);
775 $ids = $this->db->array2list($ids, 'integer');
777 // clear deleted flag
779 "UPDATE ".get_table_name($this->db_name).
780 " SET del=0, changed=".$this->db->now().
782 " AND contact_id IN ($ids)",
788 return $this->db->affected_rows();
793 * Remove all records from the database
795 function delete_all()
799 $this->db->query("UPDATE ".get_table_name($this->db_name).
800 " SET del=1, changed=".$this->db->now().
801 " WHERE user_id = ?", $this->user_id);
803 return $this->db->affected_rows();
808 * Create a contact group with the given name
810 * @param string The group name
811 * @return mixed False on error, array with record props in success
813 function create_group($name)
817 // make sure we have a unique name
818 $name = $this->unique_groupname($name);
821 "INSERT INTO ".get_table_name($this->db_groups).
822 " (user_id, changed, name)".
823 " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
826 if ($insert_id = $this->db->insert_id($this->db_groups))
827 $result = array('id' => $insert_id, 'name' => $name);
834 * Delete the given group (and all linked group members)
836 * @param string Group identifier
837 * @return boolean True on success, false if no data was changed
839 function delete_group($gid)
841 // flag group record as deleted
842 $sql_result = $this->db->query(
843 "UPDATE ".get_table_name($this->db_groups).
844 " SET del=1, changed=".$this->db->now().
845 " WHERE contactgroup_id=?".
852 return $this->db->affected_rows();
857 * Rename a specific contact group
859 * @param string Group identifier
860 * @param string New name to set for this group
861 * @return boolean New name on success, false if no data was changed
863 function rename_group($gid, $newname)
865 // make sure we have a unique name
866 $name = $this->unique_groupname($newname);
868 $sql_result = $this->db->query(
869 "UPDATE ".get_table_name($this->db_groups).
870 " SET name=?, changed=".$this->db->now().
871 " WHERE contactgroup_id=?".
873 $name, $gid, $this->user_id
876 return $this->db->affected_rows() ? $name : false;
881 * Add the given contact records the a certain group
883 * @param string Group identifier
884 * @param array List of contact identifiers to be added
885 * @return int Number of contacts added
887 function add_to_group($group_id, $ids)
890 $ids = explode(',', $ids);
895 // get existing assignments ...
896 $sql_result = $this->db->query(
897 "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
898 " WHERE contactgroup_id=?".
899 " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
902 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
903 $exists[] = $sql_arr['contact_id'];
905 // ... and remove them from the list
906 $ids = array_diff($ids, $exists);
908 foreach ($ids as $contact_id) {
910 "INSERT INTO ".get_table_name($this->db_groupmembers).
911 " (contactgroup_id, contact_id, created)".
912 " VALUES (?, ?, ".$this->db->now().")",
917 if (!$this->db->db_error)
926 * Remove the given contact records from a certain group
928 * @param string Group identifier
929 * @param array List of contact identifiers to be removed
930 * @return int Number of deleted group members
932 function remove_from_group($group_id, $ids)
935 $ids = explode(',', $ids);
937 $ids = $this->db->array2list($ids, 'integer');
939 $sql_result = $this->db->query(
940 "DELETE FROM ".get_table_name($this->db_groupmembers).
941 " WHERE contactgroup_id=?".
942 " AND contact_id IN ($ids)",
946 return $this->db->affected_rows();
951 * Check for existing groups with the same name
953 * @param string Name to check
954 * @return string A group name which is unique for the current use
956 private function unique_groupname($name)
959 $num = 2; $hit = false;
962 $sql_result = $this->db->query(
963 "SELECT 1 FROM ".get_table_name($this->db_groups).
970 // append number to make name unique
971 if ($hit = $this->db->num_rows($sql_result))
972 $checkname = $name . ' ' . $num++;