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 5712 2012-01-05 08:50:07Z 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');
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 $sql_result = $this->db->limitquery(
217 "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
221 ($this->group_id ? " AND m.contactgroup_id=?" : "").
222 ($this->filter ? " AND (".$this->filter.")" : "") .
223 " ORDER BY ". $this->db->concat('c.name', 'c.email'),
229 // determine whether we have to parse the vcard or if only db cols are requested
230 $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
232 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
233 $sql_arr['ID'] = $sql_arr[$this->primary_key];
236 $sql_arr = $this->convert_db_data($sql_arr);
238 $sql_arr['email'] = explode(self::SEPARATOR, $sql_arr['email']);
239 $sql_arr['email'] = array_map('trim', $sql_arr['email']);
242 // make sure we have a name to display
243 if (empty($sql_arr['name'])) {
244 if (empty($sql_arr['email']))
245 $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
246 $sql_arr['name'] = $sql_arr['email'][0];
249 $this->result->add($sql_arr);
252 $cnt = count($this->result->records);
256 $this->result->count = $cnt;
257 else if ($this->list_page <= 1) {
258 if ($cnt < $this->page_size && $subset == 0)
259 $this->result->count = $cnt;
260 else if (isset($this->cache['count']))
261 $this->result->count = $this->cache['count'];
263 $this->result->count = $this->_count();
266 return $this->result;
273 * @param mixed $fields The field name of array of field names to search in
274 * @param mixed $value Search value (or array of values when $fields is array)
275 * @param int $mode Matching mode:
276 * 0 - partial (*abc*),
279 * @param boolean $select True if results are requested, False if count only
280 * @param boolean $nocount True to skip the count query (select only)
281 * @param array $required List of fields that cannot be empty
283 * @return object rcube_result_set Contact records and 'count' value
285 function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
287 if (!is_array($fields))
288 $fields = array($fields);
289 if (!is_array($required) && !empty($required))
290 $required = array($required);
292 $where = $and_where = array();
293 $mode = intval($mode);
295 $AS = self::SEPARATOR;
297 foreach ($fields as $idx => $col) {
299 if ($col == 'ID' || $col == $this->primary_key) {
300 $ids = !is_array($value) ? explode(self::SEPARATOR, $value) : $value;
301 $ids = $this->db->array2list($ids, 'integer');
302 $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
305 // fulltext search in all fields
306 else if ($col == '*') {
308 foreach (explode($WS, self::normalize_string($value)) as $word) {
311 $words[] = '(' . $this->db->ilike('words', $word . '%')
312 . ' OR ' . $this->db->ilike('words', '%' . $WS . $word . $WS . '%')
313 . ' OR ' . $this->db->ilike('words', '%' . $WS . $word) . ')';
316 $words[] = '(' . $this->db->ilike('words', $word . '%')
317 . ' OR ' . $this->db->ilike('words', '%' . $WS . $word . '%') . ')';
320 $words[] = $this->db->ilike('words', '%' . $word . '%');
323 $where[] = '(' . join(' AND ', $words) . ')';
326 $val = is_array($value) ? $value[$idx] : $value;
328 if (in_array($col, $this->table_cols)) {
331 $where[] = '(' . $this->db->quoteIdentifier($col) . ' = ' . $this->db->quote($val)
332 . ' OR ' . $this->db->ilike($col, $val . $AS . '%')
333 . ' OR ' . $this->db->ilike($col, '%' . $AS . $val . $AS . '%')
334 . ' OR ' . $this->db->ilike($col, '%' . $AS . $val) . ')';
337 $where[] = '(' . $this->db->ilike($col, $val . '%')
338 . ' OR ' . $this->db->ilike($col, $AS . $val . '%') . ')';
341 $where[] = $this->db->ilike($col, '%' . $val . '%');
346 if (in_array($col, $this->fulltext_cols)) {
347 foreach (explode(" ", self::normalize_string($val)) as $word) {
350 $words[] = '(' . $this->db->ilike('words', $word . $WS . '%')
351 . ' OR ' . $this->db->ilike('words', '%' . $AS . $word . $WS .'%')
352 . ' OR ' . $this->db->ilike('words', '%' . $AS . $word) . ')';
355 $words[] = '(' . $this->db->ilike('words', $word . '%')
356 . ' OR ' . $this->db->ilike('words', $AS . $word . '%') . ')';
359 $words[] = $this->db->ilike('words', '%' . $word . '%');
362 $where[] = '(' . join(' AND ', $words) . ')';
364 if (is_array($value))
365 $post_search[$col] = mb_strtolower($val);
370 foreach (array_intersect($required, $this->table_cols) as $col) {
371 $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
374 if (!empty($where)) {
375 // use AND operator for advanced searches
376 $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
379 if (!empty($and_where))
380 $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
382 // Post-searching in vCard data fields
383 // we will search in all records and then build a where clause for their IDs
384 if (!empty($post_search)) {
386 // build key name regexp
387 $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
388 // use initial WHERE clause, to limit records number if possible
390 $this->set_search_set($where);
392 // count result pages
393 $cnt = $this->count();
394 $pages = ceil($cnt / $this->page_size);
395 $scnt = count($post_search);
397 // get (paged) result
398 for ($i=0; $i<$pages; $i++) {
399 $this->list_records(null, $i, true);
400 while ($row = $this->result->next()) {
401 $id = $row[$this->primary_key];
403 foreach (preg_grep($regexp, array_keys($row)) as $col) {
404 $pos = strpos($col, ':');
405 $colname = $pos ? substr($col, 0, $pos) : $col;
406 $search = $post_search[$colname];
407 foreach ((array)$row[$col] as $value) {
408 // composite field, e.g. address
409 foreach ((array)$value as $val) {
410 $val = mb_strtolower($val);
413 $got = ($val == $search);
416 $got = ($search == substr($val, 0, strlen($search)));
419 $got = (strpos($val, $search) !== false);
424 $found[$colname] = true;
431 if (count($found) >= $scnt) {
437 // build WHERE clause
438 $ids = $this->db->array2list($ids, 'integer');
439 $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
441 unset($this->cache['count']);
443 // when we know we have an empty result
445 $this->set_search_set($where);
446 return ($this->result = new rcube_result_set(0, 0));
450 if (!empty($where)) {
451 $this->set_search_set($where);
453 $this->list_records(null, 0, $nocount);
455 $this->result = $this->count();
458 return $this->result;
463 * Count number of available contacts in database
465 * @return rcube_result_set Result object
469 $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
471 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
476 * Count number of available contacts in database
478 * @return int Contacts count
480 private function _count()
483 $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
484 " ON (m.contact_id=c.".$this->primary_key.")";
486 // count contacts for this user
487 $sql_result = $this->db->query(
488 "SELECT COUNT(c.contact_id) AS rows".
489 " FROM ".get_table_name($this->db_name)." AS c".
493 ($this->group_id ? " AND m.contactgroup_id=?" : "").
494 ($this->filter ? " AND (".$this->filter.")" : ""),
499 $sql_arr = $this->db->fetch_assoc($sql_result);
501 $this->cache['count'] = (int) $sql_arr['rows'];
503 return $this->cache['count'];
508 * Return the last result set
510 * @return mixed Result array or NULL if nothing selected yet
512 function get_result()
514 return $this->result;
519 * Get a specific contact record
521 * @param mixed record identifier(s)
522 * @return mixed Result object with all record fields or False if not found
524 function get_record($id, $assoc=false)
526 // return cached result
527 if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
528 return $assoc ? $first : $this->result;
531 "SELECT * FROM ".get_table_name($this->db_name).
532 " WHERE contact_id=?".
539 if ($sql_arr = $this->db->fetch_assoc()) {
540 $record = $this->convert_db_data($sql_arr);
541 $this->result = new rcube_result_set(1);
542 $this->result->add($record);
545 return $assoc && $record ? $record : $this->result;
550 * Get group assignments of a specific contact record
552 * @param mixed Record identifier
553 * @return array List of assigned groups as ID=>Name pairs
555 function get_record_groups($id)
562 $sql_result = $this->db->query(
563 "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
564 " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
565 " WHERE cgm.contact_id=?",
568 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
569 $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
577 * Check the given data before saving.
578 * If input not valid, the message to display can be fetched using get_error()
580 * @param array Assoziative array with data to save
581 * @param boolean Try to fix/complete record automatically
582 * @return boolean True if input is valid, False if not.
584 public function validate(&$save_data, $autofix = false)
586 // validate e-mail addresses
587 $valid = parent::validate($save_data, $autofix);
589 // require at least one e-mail address (syntax check is already done)
590 if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
591 $this->set_error(self::ERROR_VALIDATE, 'noemailwarning');
600 * Create a new contact record
602 * @param array Associative array with save data
603 * @return integer|boolean The created record ID on success, False on error
605 function insert($save_data, $check=false)
607 if (!is_array($save_data))
610 $insert_id = $existing = false;
613 foreach ($save_data as $col => $values) {
614 if (strpos($col, 'email') === 0) {
615 foreach ((array)$values as $email) {
616 if ($existing = $this->search('email', $email, false, false))
623 $save_data = $this->convert_save_data($save_data);
624 $a_insert_cols = $a_insert_values = array();
626 foreach ($save_data as $col => $value) {
627 $a_insert_cols[] = $this->db->quoteIdentifier($col);
628 $a_insert_values[] = $this->db->quote($value);
631 if (!$existing->count && !empty($a_insert_cols)) {
633 "INSERT INTO ".get_table_name($this->db_name).
634 " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
635 " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
638 $insert_id = $this->db->insert_id($this->db_name);
641 // also add the newly created contact to the active group
642 if ($insert_id && $this->group_id)
643 $this->add_to_group($this->group_id, $insert_id);
652 * Update a specific contact record
654 * @param mixed Record identifier
655 * @param array Assoziative array with save data
656 * @return boolean True on success, False on error
658 function update($id, $save_cols)
661 $write_sql = array();
662 $record = $this->get_record($id, true);
663 $save_cols = $this->convert_save_data($save_cols, $record);
665 foreach ($save_cols as $col => $value) {
666 $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
669 if (!empty($write_sql)) {
671 "UPDATE ".get_table_name($this->db_name).
672 " SET changed=".$this->db->now().", ".join(', ', $write_sql).
673 " WHERE contact_id=?".
680 $updated = $this->db->affected_rows();
681 $this->result = null; // clear current result (from get_record())
688 private function convert_db_data($sql_arr)
691 $record['ID'] = $sql_arr[$this->primary_key];
693 if ($sql_arr['vcard']) {
694 unset($sql_arr['email']);
695 $vcard = new rcube_vcard($sql_arr['vcard']);
696 $record += $vcard->get_assoc() + $sql_arr;
700 $record['email'] = explode(self::SEPARATOR, $record['email']);
701 $record['email'] = array_map('trim', $record['email']);
708 private function convert_save_data($save_data, $record = array())
713 // copy values into vcard object
714 $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
716 foreach ($save_data as $key => $values) {
717 list($field, $section) = explode(':', $key);
718 $fulltext = in_array($field, $this->fulltext_cols);
719 foreach ((array)$values as $value) {
721 $vcard->set($field, $value, $section);
722 if ($fulltext && is_array($value))
723 $words .= ' ' . self::normalize_string(join(" ", $value));
724 else if ($fulltext && strlen($value) >= 3)
725 $words .= ' ' . self::normalize_string($value);
728 $out['vcard'] = $vcard->export(false);
730 foreach ($this->table_cols as $col) {
732 if (!isset($save_data[$key]))
734 if (isset($save_data[$key])) {
735 if (is_array($save_data[$key]))
736 $out[$col] = join(self::SEPARATOR, $save_data[$key]);
738 $out[$col] = $save_data[$key];
742 // save all e-mails in database column
743 $out['email'] = join(self::SEPARATOR, $vcard->email);
745 // join words for fulltext search
746 $out['words'] = join(" ", array_unique(explode(" ", $words)));
753 * Mark one or more contact records as deleted
755 * @param array Record identifiers
756 * @param boolean Remove record(s) irreversible (unsupported)
758 function delete($ids, $force=true)
761 $ids = explode(self::SEPARATOR, $ids);
763 $ids = $this->db->array2list($ids, 'integer');
765 // flag record as deleted (always)
767 "UPDATE ".get_table_name($this->db_name).
768 " SET del=1, changed=".$this->db->now().
770 " AND contact_id IN ($ids)",
776 return $this->db->affected_rows();
781 * Undelete one or more contact records
783 * @param array Record identifiers
785 function undelete($ids)
788 $ids = explode(self::SEPARATOR, $ids);
790 $ids = $this->db->array2list($ids, 'integer');
792 // clear deleted flag
794 "UPDATE ".get_table_name($this->db_name).
795 " SET del=0, changed=".$this->db->now().
797 " AND contact_id IN ($ids)",
803 return $this->db->affected_rows();
808 * Remove all records from the database
810 function delete_all()
814 $this->db->query("UPDATE ".get_table_name($this->db_name).
815 " SET del=1, changed=".$this->db->now().
816 " WHERE user_id = ?", $this->user_id);
818 return $this->db->affected_rows();
823 * Create a contact group with the given name
825 * @param string The group name
826 * @return mixed False on error, array with record props in success
828 function create_group($name)
832 // make sure we have a unique name
833 $name = $this->unique_groupname($name);
836 "INSERT INTO ".get_table_name($this->db_groups).
837 " (user_id, changed, name)".
838 " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
841 if ($insert_id = $this->db->insert_id($this->db_groups))
842 $result = array('id' => $insert_id, 'name' => $name);
849 * Delete the given group (and all linked group members)
851 * @param string Group identifier
852 * @return boolean True on success, false if no data was changed
854 function delete_group($gid)
856 // flag group record as deleted
857 $sql_result = $this->db->query(
858 "UPDATE ".get_table_name($this->db_groups).
859 " SET del=1, changed=".$this->db->now().
860 " WHERE contactgroup_id=?".
867 return $this->db->affected_rows();
872 * Rename a specific contact group
874 * @param string Group identifier
875 * @param string New name to set for this group
876 * @return boolean New name on success, false if no data was changed
878 function rename_group($gid, $newname)
880 // make sure we have a unique name
881 $name = $this->unique_groupname($newname);
883 $sql_result = $this->db->query(
884 "UPDATE ".get_table_name($this->db_groups).
885 " SET name=?, changed=".$this->db->now().
886 " WHERE contactgroup_id=?".
888 $name, $gid, $this->user_id
891 return $this->db->affected_rows() ? $name : false;
896 * Add the given contact records the a certain group
898 * @param string Group identifier
899 * @param array List of contact identifiers to be added
900 * @return int Number of contacts added
902 function add_to_group($group_id, $ids)
905 $ids = explode(self::SEPARATOR, $ids);
910 // get existing assignments ...
911 $sql_result = $this->db->query(
912 "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
913 " WHERE contactgroup_id=?".
914 " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
917 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
918 $exists[] = $sql_arr['contact_id'];
920 // ... and remove them from the list
921 $ids = array_diff($ids, $exists);
923 foreach ($ids as $contact_id) {
925 "INSERT INTO ".get_table_name($this->db_groupmembers).
926 " (contactgroup_id, contact_id, created)".
927 " VALUES (?, ?, ".$this->db->now().")",
932 if (!$this->db->db_error)
941 * Remove the given contact records from a certain group
943 * @param string Group identifier
944 * @param array List of contact identifiers to be removed
945 * @return int Number of deleted group members
947 function remove_from_group($group_id, $ids)
950 $ids = explode(self::SEPARATOR, $ids);
952 $ids = $this->db->array2list($ids, 'integer');
954 $sql_result = $this->db->query(
955 "DELETE FROM ".get_table_name($this->db_groupmembers).
956 " WHERE contactgroup_id=?".
957 " AND contact_id IN ($ids)",
961 return $this->db->affected_rows();
966 * Check for existing groups with the same name
968 * @param string Name to check
969 * @return string A group name which is unique for the current use
971 private function unique_groupname($name)
974 $num = 2; $hit = false;
977 $sql_result = $this->db->query(
978 "SELECT 1 FROM ".get_table_name($this->db_groups).
985 // append number to make name unique
986 if ($hit = $this->db->num_rows($sql_result))
987 $checkname = $name . ' ' . $num++;