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 5873 2012-02-11 13:50:04Z thomasb $
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');
65 const SEPARATOR = ',';
71 * @param object Instance of the rcube_db class
72 * @param integer User-ID
74 function __construct($dbconn, $user)
77 $this->user_id = $user;
78 $this->ready = $this->db && !$this->db->is_error();
83 * Returns addressbook name
92 * Save a search string for future listings
94 * @param string SQL params to use in listing method
96 function set_search_set($filter)
98 $this->filter = $filter;
104 * Getter for saved search properties
106 * @return mixed Search properties used by this class
108 function get_search_set()
110 return $this->filter;
115 * Setter for the current group
116 * (empty, has to be re-implemented by extending class)
118 function set_group($gid)
120 $this->group_id = $gid;
126 * Reset all saved results and search parameters
130 $this->result = null;
131 $this->filter = null;
137 * List all active contact groups of this source
139 * @param string Search string to match group name
140 * @return array Indexed list of contact groups, each a hash array
142 function list_groups($search = null)
149 $sql_filter = $search ? " AND " . $this->db->ilike('name', '%'.$search.'%') : '';
151 $sql_result = $this->db->query(
152 "SELECT * FROM ".get_table_name($this->db_groups).
159 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
160 $sql_arr['ID'] = $sql_arr['contactgroup_id'];
161 $results[] = $sql_arr;
169 * Get group properties such as name and email address(es)
171 * @param string Group identifier
172 * @return array Group properties as hash array
174 function get_group($group_id)
176 $sql_result = $this->db->query(
177 "SELECT * FROM ".get_table_name($this->db_groups).
179 " AND contactgroup_id=?".
181 $group_id, $this->user_id);
183 if ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
184 $sql_arr['ID'] = $sql_arr['contactgroup_id'];
192 * List the current set of contact records
194 * @param array List of cols to show, Null means all
195 * @param int Only return this number of records, use negative values for tail
196 * @param boolean True to skip the count query (select only)
197 * @return array Indexed list of contact records, each a hash array
199 function list_records($cols=null, $subset=0, $nocount=false)
201 if ($nocount || $this->list_page <= 1) {
202 // create dummy result, we don't need a count now
203 $this->result = new rcube_result_set();
206 $this->result = $this->count();
209 $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
210 $length = $subset != 0 ? abs($subset) : $this->page_size;
213 $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
214 " ON (m.contact_id = c.".$this->primary_key.")";
216 $order_col = (in_array($this->sort_col, $this->table_cols) ? $this->sort_col : 'name');
217 $order_cols = array('c.'.$order_col);
218 if ($order_col == 'firstname')
219 $order_cols[] = 'c.surname';
220 else if ($order_col == 'surname')
221 $order_cols[] = 'c.firstname';
222 if ($order_col != 'name')
223 $order_cols[] = 'c.name';
224 $order_cols[] = 'c.email';
226 $sql_result = $this->db->limitquery(
227 "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
231 ($this->group_id ? " AND m.contactgroup_id=?" : "").
232 ($this->filter ? " AND (".$this->filter.")" : "") .
233 " ORDER BY ". $this->db->concat($order_cols) .
234 " " . $this->sort_order,
240 // determine whether we have to parse the vcard or if only db cols are requested
241 $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
243 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
244 $sql_arr['ID'] = $sql_arr[$this->primary_key];
247 $sql_arr = $this->convert_db_data($sql_arr);
249 $sql_arr['email'] = explode(self::SEPARATOR, $sql_arr['email']);
250 $sql_arr['email'] = array_map('trim', $sql_arr['email']);
253 $this->result->add($sql_arr);
256 $cnt = count($this->result->records);
260 $this->result->count = $cnt;
261 else if ($this->list_page <= 1) {
262 if ($cnt < $this->page_size && $subset == 0)
263 $this->result->count = $cnt;
264 else if (isset($this->cache['count']))
265 $this->result->count = $this->cache['count'];
267 $this->result->count = $this->_count();
270 return $this->result;
277 * @param mixed $fields The field name of array of field names to search in
278 * @param mixed $value Search value (or array of values when $fields is array)
279 * @param int $mode Matching mode:
280 * 0 - partial (*abc*),
283 * @param boolean $select True if results are requested, False if count only
284 * @param boolean $nocount True to skip the count query (select only)
285 * @param array $required List of fields that cannot be empty
287 * @return object rcube_result_set Contact records and 'count' value
289 function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
291 if (!is_array($fields))
292 $fields = array($fields);
293 if (!is_array($required) && !empty($required))
294 $required = array($required);
296 $where = $and_where = array();
297 $mode = intval($mode);
299 $AS = self::SEPARATOR;
301 foreach ($fields as $idx => $col) {
303 if ($col == 'ID' || $col == $this->primary_key) {
304 $ids = !is_array($value) ? explode(self::SEPARATOR, $value) : $value;
305 $ids = $this->db->array2list($ids, 'integer');
306 $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
309 // fulltext search in all fields
310 else if ($col == '*') {
312 foreach (explode($WS, self::normalize_string($value)) as $word) {
315 $words[] = '(' . $this->db->ilike('words', $word . '%')
316 . ' OR ' . $this->db->ilike('words', '%' . $WS . $word . $WS . '%')
317 . ' OR ' . $this->db->ilike('words', '%' . $WS . $word) . ')';
320 $words[] = '(' . $this->db->ilike('words', $word . '%')
321 . ' OR ' . $this->db->ilike('words', '%' . $WS . $word . '%') . ')';
324 $words[] = $this->db->ilike('words', '%' . $word . '%');
327 $where[] = '(' . join(' AND ', $words) . ')';
330 $val = is_array($value) ? $value[$idx] : $value;
332 if (in_array($col, $this->table_cols)) {
335 $where[] = '(' . $this->db->quoteIdentifier($col) . ' = ' . $this->db->quote($val)
336 . ' OR ' . $this->db->ilike($col, $val . $AS . '%')
337 . ' OR ' . $this->db->ilike($col, '%' . $AS . $val . $AS . '%')
338 . ' OR ' . $this->db->ilike($col, '%' . $AS . $val) . ')';
341 $where[] = '(' . $this->db->ilike($col, $val . '%')
342 . ' OR ' . $this->db->ilike($col, $AS . $val . '%') . ')';
345 $where[] = $this->db->ilike($col, '%' . $val . '%');
350 if (in_array($col, $this->fulltext_cols)) {
351 foreach (explode(" ", self::normalize_string($val)) as $word) {
354 $words[] = '(' . $this->db->ilike('words', $word . $WS . '%')
355 . ' OR ' . $this->db->ilike('words', '%' . $AS . $word . $WS .'%')
356 . ' OR ' . $this->db->ilike('words', '%' . $AS . $word) . ')';
359 $words[] = '(' . $this->db->ilike('words', $word . '%')
360 . ' OR ' . $this->db->ilike('words', $AS . $word . '%') . ')';
363 $words[] = $this->db->ilike('words', '%' . $word . '%');
366 $where[] = '(' . join(' AND ', $words) . ')';
368 if (is_array($value))
369 $post_search[$col] = mb_strtolower($val);
374 foreach (array_intersect($required, $this->table_cols) as $col) {
375 $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
378 if (!empty($where)) {
379 // use AND operator for advanced searches
380 $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
383 if (!empty($and_where))
384 $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
386 // Post-searching in vCard data fields
387 // we will search in all records and then build a where clause for their IDs
388 if (!empty($post_search)) {
390 // build key name regexp
391 $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
392 // use initial WHERE clause, to limit records number if possible
394 $this->set_search_set($where);
396 // count result pages
397 $cnt = $this->count();
398 $pages = ceil($cnt / $this->page_size);
399 $scnt = count($post_search);
401 // get (paged) result
402 for ($i=0; $i<$pages; $i++) {
403 $this->list_records(null, $i, true);
404 while ($row = $this->result->next()) {
405 $id = $row[$this->primary_key];
407 foreach (preg_grep($regexp, array_keys($row)) as $col) {
408 $pos = strpos($col, ':');
409 $colname = $pos ? substr($col, 0, $pos) : $col;
410 $search = $post_search[$colname];
411 foreach ((array)$row[$col] as $value) {
412 // composite field, e.g. address
413 foreach ((array)$value as $val) {
414 $val = mb_strtolower($val);
417 $got = ($val == $search);
420 $got = ($search == substr($val, 0, strlen($search)));
423 $got = (strpos($val, $search) !== false);
428 $found[$colname] = true;
435 if (count($found) >= $scnt) {
441 // build WHERE clause
442 $ids = $this->db->array2list($ids, 'integer');
443 $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
445 unset($this->cache['count']);
447 // when we know we have an empty result
449 $this->set_search_set($where);
450 return ($this->result = new rcube_result_set(0, 0));
454 if (!empty($where)) {
455 $this->set_search_set($where);
457 $this->list_records(null, 0, $nocount);
459 $this->result = $this->count();
462 return $this->result;
467 * Count number of available contacts in database
469 * @return rcube_result_set Result object
473 $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
475 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
480 * Count number of available contacts in database
482 * @return int Contacts count
484 private function _count()
487 $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
488 " ON (m.contact_id=c.".$this->primary_key.")";
490 // count contacts for this user
491 $sql_result = $this->db->query(
492 "SELECT COUNT(c.contact_id) AS rows".
493 " FROM ".get_table_name($this->db_name)." AS c".
497 ($this->group_id ? " AND m.contactgroup_id=?" : "").
498 ($this->filter ? " AND (".$this->filter.")" : ""),
503 $sql_arr = $this->db->fetch_assoc($sql_result);
505 $this->cache['count'] = (int) $sql_arr['rows'];
507 return $this->cache['count'];
512 * Return the last result set
514 * @return mixed Result array or NULL if nothing selected yet
516 function get_result()
518 return $this->result;
523 * Get a specific contact record
525 * @param mixed record identifier(s)
526 * @return mixed Result object with all record fields or False if not found
528 function get_record($id, $assoc=false)
530 // return cached result
531 if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
532 return $assoc ? $first : $this->result;
535 "SELECT * FROM ".get_table_name($this->db_name).
536 " WHERE contact_id=?".
543 if ($sql_arr = $this->db->fetch_assoc()) {
544 $record = $this->convert_db_data($sql_arr);
545 $this->result = new rcube_result_set(1);
546 $this->result->add($record);
549 return $assoc && $record ? $record : $this->result;
554 * Get group assignments of a specific contact record
556 * @param mixed Record identifier
557 * @return array List of assigned groups as ID=>Name pairs
559 function get_record_groups($id)
566 $sql_result = $this->db->query(
567 "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
568 " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
569 " WHERE cgm.contact_id=?",
572 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
573 $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
581 * Check the given data before saving.
582 * If input not valid, the message to display can be fetched using get_error()
584 * @param array Assoziative array with data to save
585 * @param boolean Try to fix/complete record automatically
586 * @return boolean True if input is valid, False if not.
588 public function validate(&$save_data, $autofix = false)
590 // validate e-mail addresses
591 $valid = parent::validate($save_data, $autofix);
593 // require at least one e-mail address (syntax check is already done)
594 if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
595 $this->set_error(self::ERROR_VALIDATE, 'noemailwarning');
604 * Create a new contact record
606 * @param array Associative array with save data
607 * @return integer|boolean The created record ID on success, False on error
609 function insert($save_data, $check=false)
611 if (!is_array($save_data))
614 $insert_id = $existing = false;
617 foreach ($save_data as $col => $values) {
618 if (strpos($col, 'email') === 0) {
619 foreach ((array)$values as $email) {
620 if ($existing = $this->search('email', $email, false, false))
627 $save_data = $this->convert_save_data($save_data);
628 $a_insert_cols = $a_insert_values = array();
630 foreach ($save_data as $col => $value) {
631 $a_insert_cols[] = $this->db->quoteIdentifier($col);
632 $a_insert_values[] = $this->db->quote($value);
635 if (!$existing->count && !empty($a_insert_cols)) {
637 "INSERT INTO ".get_table_name($this->db_name).
638 " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
639 " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
642 $insert_id = $this->db->insert_id($this->db_name);
645 // also add the newly created contact to the active group
646 if ($insert_id && $this->group_id)
647 $this->add_to_group($this->group_id, $insert_id);
656 * Update a specific contact record
658 * @param mixed Record identifier
659 * @param array Assoziative array with save data
660 * @return boolean True on success, False on error
662 function update($id, $save_cols)
665 $write_sql = array();
666 $record = $this->get_record($id, true);
667 $save_cols = $this->convert_save_data($save_cols, $record);
669 foreach ($save_cols as $col => $value) {
670 $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
673 if (!empty($write_sql)) {
675 "UPDATE ".get_table_name($this->db_name).
676 " SET changed=".$this->db->now().", ".join(', ', $write_sql).
677 " WHERE contact_id=?".
684 $updated = $this->db->affected_rows();
685 $this->result = null; // clear current result (from get_record())
692 private function convert_db_data($sql_arr)
695 $record['ID'] = $sql_arr[$this->primary_key];
697 if ($sql_arr['vcard']) {
698 unset($sql_arr['email']);
699 $vcard = new rcube_vcard($sql_arr['vcard']);
700 $record += $vcard->get_assoc() + $sql_arr;
704 $record['email'] = explode(self::SEPARATOR, $record['email']);
705 $record['email'] = array_map('trim', $record['email']);
712 private function convert_save_data($save_data, $record = array())
717 // copy values into vcard object
718 $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
720 foreach ($save_data as $key => $values) {
721 list($field, $section) = explode(':', $key);
722 $fulltext = in_array($field, $this->fulltext_cols);
723 foreach ((array)$values as $value) {
725 $vcard->set($field, $value, $section);
726 if ($fulltext && is_array($value))
727 $words .= ' ' . self::normalize_string(join(" ", $value));
728 else if ($fulltext && strlen($value) >= 3)
729 $words .= ' ' . self::normalize_string($value);
732 $out['vcard'] = $vcard->export(false);
734 foreach ($this->table_cols as $col) {
736 if (!isset($save_data[$key]))
738 if (isset($save_data[$key])) {
739 if (is_array($save_data[$key]))
740 $out[$col] = join(self::SEPARATOR, $save_data[$key]);
742 $out[$col] = $save_data[$key];
746 // save all e-mails in database column
747 $out['email'] = join(self::SEPARATOR, $vcard->email);
749 // join words for fulltext search
750 $out['words'] = join(" ", array_unique(explode(" ", $words)));
757 * Mark one or more contact records as deleted
759 * @param array Record identifiers
760 * @param boolean Remove record(s) irreversible (unsupported)
762 function delete($ids, $force=true)
765 $ids = explode(self::SEPARATOR, $ids);
767 $ids = $this->db->array2list($ids, 'integer');
769 // flag record as deleted (always)
771 "UPDATE ".get_table_name($this->db_name).
772 " SET del=1, changed=".$this->db->now().
774 " AND contact_id IN ($ids)",
780 return $this->db->affected_rows();
785 * Undelete one or more contact records
787 * @param array Record identifiers
789 function undelete($ids)
792 $ids = explode(self::SEPARATOR, $ids);
794 $ids = $this->db->array2list($ids, 'integer');
796 // clear deleted flag
798 "UPDATE ".get_table_name($this->db_name).
799 " SET del=0, changed=".$this->db->now().
801 " AND contact_id IN ($ids)",
807 return $this->db->affected_rows();
812 * Remove all records from the database
814 function delete_all()
818 $this->db->query("UPDATE ".get_table_name($this->db_name).
819 " SET del=1, changed=".$this->db->now().
820 " WHERE user_id = ?", $this->user_id);
822 return $this->db->affected_rows();
827 * Create a contact group with the given name
829 * @param string The group name
830 * @return mixed False on error, array with record props in success
832 function create_group($name)
836 // make sure we have a unique name
837 $name = $this->unique_groupname($name);
840 "INSERT INTO ".get_table_name($this->db_groups).
841 " (user_id, changed, name)".
842 " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
845 if ($insert_id = $this->db->insert_id($this->db_groups))
846 $result = array('id' => $insert_id, 'name' => $name);
853 * Delete the given group (and all linked group members)
855 * @param string Group identifier
856 * @return boolean True on success, false if no data was changed
858 function delete_group($gid)
860 // flag group record as deleted
861 $sql_result = $this->db->query(
862 "UPDATE ".get_table_name($this->db_groups).
863 " SET del=1, changed=".$this->db->now().
864 " WHERE contactgroup_id=?".
871 return $this->db->affected_rows();
876 * Rename a specific contact group
878 * @param string Group identifier
879 * @param string New name to set for this group
880 * @return boolean New name on success, false if no data was changed
882 function rename_group($gid, $newname)
884 // make sure we have a unique name
885 $name = $this->unique_groupname($newname);
887 $sql_result = $this->db->query(
888 "UPDATE ".get_table_name($this->db_groups).
889 " SET name=?, changed=".$this->db->now().
890 " WHERE contactgroup_id=?".
892 $name, $gid, $this->user_id
895 return $this->db->affected_rows() ? $name : false;
900 * Add the given contact records the a certain group
902 * @param string Group identifier
903 * @param array List of contact identifiers to be added
904 * @return int Number of contacts added
906 function add_to_group($group_id, $ids)
909 $ids = explode(self::SEPARATOR, $ids);
914 // get existing assignments ...
915 $sql_result = $this->db->query(
916 "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
917 " WHERE contactgroup_id=?".
918 " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
921 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
922 $exists[] = $sql_arr['contact_id'];
924 // ... and remove them from the list
925 $ids = array_diff($ids, $exists);
927 foreach ($ids as $contact_id) {
929 "INSERT INTO ".get_table_name($this->db_groupmembers).
930 " (contactgroup_id, contact_id, created)".
931 " VALUES (?, ?, ".$this->db->now().")",
936 if (!$this->db->db_error)
945 * Remove the given contact records from a certain group
947 * @param string Group identifier
948 * @param array List of contact identifiers to be removed
949 * @return int Number of deleted group members
951 function remove_from_group($group_id, $ids)
954 $ids = explode(self::SEPARATOR, $ids);
956 $ids = $this->db->array2list($ids, 'integer');
958 $sql_result = $this->db->query(
959 "DELETE FROM ".get_table_name($this->db_groupmembers).
960 " WHERE contactgroup_id=?".
961 " AND contact_id IN ($ids)",
965 return $this->db->affected_rows();
970 * Check for existing groups with the same name
972 * @param string Name to check
973 * @return string A group name which is unique for the current use
975 private function unique_groupname($name)
978 $num = 2; $hit = false;
981 $sql_result = $this->db->query(
982 "SELECT 1 FROM ".get_table_name($this->db_groups).
989 // append number to make name unique
990 if ($hit = $this->db->num_rows($sql_result))
991 $checkname = $name . ' ' . $num++;