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 5011 2011-08-03 09:32: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;
46 private $table_cols = array('name', 'email', 'firstname', 'surname');
47 private $fulltext_cols = array('name', 'firstname', 'surname', 'middlename', 'nickname',
48 'jobtitle', 'organization', 'department', 'maidenname', 'email', 'phone',
49 'address', 'street', 'locality', 'zipcode', 'region', 'country', 'website', 'im', 'notes');
52 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 * List the current set of contact records
169 * @param array List of cols to show, Null means all
170 * @param int Only return this number of records, use negative values for tail
171 * @param boolean True to skip the count query (select only)
172 * @return array Indexed list of contact records, each a hash array
174 function list_records($cols=null, $subset=0, $nocount=false)
176 if ($nocount || $this->list_page <= 1) {
177 // create dummy result, we don't need a count now
178 $this->result = new rcube_result_set();
181 $this->result = $this->count();
184 $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
185 $length = $subset != 0 ? abs($subset) : $this->page_size;
188 $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
189 " ON (m.contact_id = c.".$this->primary_key.")";
191 $sql_result = $this->db->limitquery(
192 "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
196 ($this->group_id ? " AND m.contactgroup_id=?" : "").
197 ($this->filter ? " AND (".$this->filter.")" : "") .
198 " ORDER BY ". $this->db->concat('c.name', 'c.email'),
204 // determine whether we have to parse the vcard or if only db cols are requested
205 $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
207 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
208 $sql_arr['ID'] = $sql_arr[$this->primary_key];
211 $sql_arr = $this->convert_db_data($sql_arr);
213 $sql_arr['email'] = preg_split('/,\s*/', $sql_arr['email']);
215 // make sure we have a name to display
216 if (empty($sql_arr['name'])) {
217 if (empty($sql_arr['email']))
218 $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
219 $sql_arr['name'] = $sql_arr['email'][0];
222 $this->result->add($sql_arr);
225 $cnt = count($this->result->records);
229 $this->result->count = $cnt;
230 else if ($this->list_page <= 1) {
231 if ($cnt < $this->page_size && $subset == 0)
232 $this->result->count = $cnt;
233 else if (isset($this->cache['count']))
234 $this->result->count = $this->cache['count'];
236 $this->result->count = $this->_count();
239 return $this->result;
246 * @param mixed $fields The field name of array of field names to search in
247 * @param mixed $value Search value (or array of values when $fields is array)
248 * @param boolean $strict True for strict (=), False for partial (LIKE) matching
249 * @param boolean $select True if results are requested, False if count only
250 * @param boolean $nocount True to skip the count query (select only)
251 * @param array $required List of fields that cannot be empty
253 * @return object rcube_result_set Contact records and 'count' value
255 function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
257 if (!is_array($fields))
258 $fields = array($fields);
259 if (!is_array($required) && !empty($required))
260 $required = array($required);
262 $where = $and_where = array();
264 foreach ($fields as $idx => $col) {
266 if ($col == 'ID' || $col == $this->primary_key) {
267 $ids = !is_array($value) ? explode(',', $value) : $value;
268 $ids = $this->db->array2list($ids, 'integer');
269 $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
272 // fulltext search in all fields
273 else if ($col == '*') {
275 foreach (explode(" ", self::normalize_string($value)) as $word)
276 $words[] = $this->db->ilike('words', '%'.$word.'%');
277 $where[] = '(' . join(' AND ', $words) . ')';
280 $val = is_array($value) ? $value[$idx] : $value;
282 if (in_array($col, $this->table_cols)) {
284 $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($val);
287 $where[] = $this->db->ilike($col, '%'.$val.'%');
292 if (in_array($col, $this->fulltext_cols)) {
293 foreach (explode(" ", self::normalize_string($val)) as $word)
294 $words[] = $this->db->ilike('words', '%'.$word.'%');
295 $where[] = '(' . join(' AND ', $words) . ')';
297 if (is_array($value))
298 $post_search[$col] = mb_strtolower($val);
303 foreach (array_intersect($required, $this->table_cols) as $col) {
304 $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
307 if (!empty($where)) {
308 // use AND operator for advanced searches
309 $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
312 if (!empty($and_where))
313 $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
315 // Post-searching in vCard data fields
316 // we will search in all records and then build a where clause for their IDs
317 if (!empty($post_search)) {
319 // build key name regexp
320 $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
321 // use initial WHERE clause, to limit records number if possible
323 $this->set_search_set($where);
325 // count result pages
326 $cnt = $this->count();
327 $pages = ceil($cnt / $this->page_size);
328 $scnt = count($post_search);
330 // get (paged) result
331 for ($i=0; $i<$pages; $i++) {
332 $this->list_records(null, $i, true);
333 while ($row = $this->result->next()) {
334 $id = $row[$this->primary_key];
336 foreach (preg_grep($regexp, array_keys($row)) as $col) {
337 $pos = strpos($col, ':');
338 $colname = $pos ? substr($col, 0, $pos) : $col;
339 $search = $post_search[$colname];
340 foreach ((array)$row[$col] as $value) {
341 // composite field, e.g. address
342 if (is_array($value)) {
343 $value = implode($value);
345 $value = mb_strtolower($value);
346 if (($strict && $value == $search) || (!$strict && strpos($value, $search) !== false)) {
347 $found[$colname] = true;
353 if (count($found) >= $scnt) {
359 // build WHERE clause
360 $ids = $this->db->array2list($ids, 'integer');
361 $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
363 unset($this->cache['count']);
365 // when we know we have an empty result
367 $this->set_search_set($where);
368 return ($this->result = new rcube_result_set(0, 0));
372 if (!empty($where)) {
373 $this->set_search_set($where);
375 $this->list_records(null, 0, $nocount);
377 $this->result = $this->count();
380 return $this->result;
385 * Count number of available contacts in database
387 * @return rcube_result_set Result object
391 $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
393 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
398 * Count number of available contacts in database
400 * @return int Contacts count
402 private function _count()
405 $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
406 " ON (m.contact_id=c.".$this->primary_key.")";
408 // count contacts for this user
409 $sql_result = $this->db->query(
410 "SELECT COUNT(c.contact_id) AS rows".
411 " FROM ".get_table_name($this->db_name)." AS c".
415 ($this->group_id ? " AND m.contactgroup_id=?" : "").
416 ($this->filter ? " AND (".$this->filter.")" : ""),
421 $sql_arr = $this->db->fetch_assoc($sql_result);
423 $this->cache['count'] = (int) $sql_arr['rows'];
425 return $this->cache['count'];
430 * Return the last result set
432 * @return mixed Result array or NULL if nothing selected yet
434 function get_result()
436 return $this->result;
441 * Get a specific contact record
443 * @param mixed record identifier(s)
444 * @return mixed Result object with all record fields or False if not found
446 function get_record($id, $assoc=false)
448 // return cached result
449 if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
450 return $assoc ? $first : $this->result;
453 "SELECT * FROM ".get_table_name($this->db_name).
454 " WHERE contact_id=?".
461 if ($sql_arr = $this->db->fetch_assoc()) {
462 $record = $this->convert_db_data($sql_arr);
463 $this->result = new rcube_result_set(1);
464 $this->result->add($record);
467 return $assoc && $record ? $record : $this->result;
472 * Get group assignments of a specific contact record
474 * @param mixed Record identifier
475 * @return array List of assigned groups as ID=>Name pairs
477 function get_record_groups($id)
484 $sql_result = $this->db->query(
485 "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
486 " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
487 " WHERE cgm.contact_id=?",
490 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
491 $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
499 * Check the given data before saving.
500 * If input not valid, the message to display can be fetched using get_error()
502 * @param array Assoziative array with data to save
503 * @return boolean True if input is valid, False if not.
505 public function validate($save_data)
507 // validate e-mail addresses
508 $valid = parent::validate($save_data);
510 // require at least one e-mail address (syntax check is already done)
511 if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
512 $this->set_error('warning', 'noemailwarning');
521 * Create a new contact record
523 * @param array Associative array with save data
524 * @return integer|boolean The created record ID on success, False on error
526 function insert($save_data, $check=false)
528 if (!is_array($save_data))
531 $insert_id = $existing = false;
534 foreach ($save_data as $col => $values) {
535 if (strpos($col, 'email') === 0) {
536 foreach ((array)$values as $email) {
537 if ($existing = $this->search('email', $email, false, false))
544 $save_data = $this->convert_save_data($save_data);
545 $a_insert_cols = $a_insert_values = array();
547 foreach ($save_data as $col => $value) {
548 $a_insert_cols[] = $this->db->quoteIdentifier($col);
549 $a_insert_values[] = $this->db->quote($value);
552 if (!$existing->count && !empty($a_insert_cols)) {
554 "INSERT INTO ".get_table_name($this->db_name).
555 " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
556 " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
559 $insert_id = $this->db->insert_id($this->db_name);
562 // also add the newly created contact to the active group
563 if ($insert_id && $this->group_id)
564 $this->add_to_group($this->group_id, $insert_id);
573 * Update a specific contact record
575 * @param mixed Record identifier
576 * @param array Assoziative array with save data
577 * @return boolean True on success, False on error
579 function update($id, $save_cols)
582 $write_sql = array();
583 $record = $this->get_record($id, true);
584 $save_cols = $this->convert_save_data($save_cols, $record);
586 foreach ($save_cols as $col => $value) {
587 $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
590 if (!empty($write_sql)) {
592 "UPDATE ".get_table_name($this->db_name).
593 " SET changed=".$this->db->now().", ".join(', ', $write_sql).
594 " WHERE contact_id=?".
601 $updated = $this->db->affected_rows();
602 $this->result = null; // clear current result (from get_record())
609 private function convert_db_data($sql_arr)
612 $record['ID'] = $sql_arr[$this->primary_key];
614 if ($sql_arr['vcard']) {
615 unset($sql_arr['email']);
616 $vcard = new rcube_vcard($sql_arr['vcard']);
617 $record += $vcard->get_assoc() + $sql_arr;
621 $record['email'] = preg_split('/,\s*/', $record['email']);
628 private function convert_save_data($save_data, $record = array())
633 // copy values into vcard object
634 $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
636 foreach ($save_data as $key => $values) {
637 list($field, $section) = explode(':', $key);
638 $fulltext = in_array($field, $this->fulltext_cols);
639 foreach ((array)$values as $value) {
641 $vcard->set($field, $value, $section);
642 if ($fulltext && is_array($value))
643 $words .= ' ' . self::normalize_string(join(" ", $value));
644 else if ($fulltext && strlen($value) >= 3)
645 $words .= ' ' . self::normalize_string($value);
648 $out['vcard'] = $vcard->export(false);
650 foreach ($this->table_cols as $col) {
652 if (!isset($save_data[$key]))
654 if (isset($save_data[$key]))
655 $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
658 // save all e-mails in database column
659 $out['email'] = join(", ", $vcard->email);
661 // join words for fulltext search
662 $out['words'] = join(" ", array_unique(explode(" ", $words)));
669 * Mark one or more contact records as deleted
671 * @param array Record identifiers
672 * @param boolean Remove record(s) irreversible (unsupported)
674 function delete($ids, $force=true)
677 $ids = explode(',', $ids);
679 $ids = $this->db->array2list($ids, 'integer');
681 // flag record as deleted (always)
683 "UPDATE ".get_table_name($this->db_name).
684 " SET del=1, changed=".$this->db->now().
686 " AND contact_id IN ($ids)",
692 return $this->db->affected_rows();
697 * Undelete one or more contact records
699 * @param array Record identifiers
701 function undelete($ids)
704 $ids = explode(',', $ids);
706 $ids = $this->db->array2list($ids, 'integer');
708 // clear deleted flag
710 "UPDATE ".get_table_name($this->db_name).
711 " SET del=0, changed=".$this->db->now().
713 " AND contact_id IN ($ids)",
719 return $this->db->affected_rows();
724 * Remove all records from the database
726 function delete_all()
730 $this->db->query("UPDATE ".get_table_name($this->db_name).
731 " SET del=1, changed=".$this->db->now().
732 " WHERE user_id = ?", $this->user_id);
734 return $this->db->affected_rows();
739 * Create a contact group with the given name
741 * @param string The group name
742 * @return mixed False on error, array with record props in success
744 function create_group($name)
748 // make sure we have a unique name
749 $name = $this->unique_groupname($name);
752 "INSERT INTO ".get_table_name($this->db_groups).
753 " (user_id, changed, name)".
754 " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
757 if ($insert_id = $this->db->insert_id($this->db_groups))
758 $result = array('id' => $insert_id, 'name' => $name);
765 * Delete the given group (and all linked group members)
767 * @param string Group identifier
768 * @return boolean True on success, false if no data was changed
770 function delete_group($gid)
772 // flag group record as deleted
773 $sql_result = $this->db->query(
774 "UPDATE ".get_table_name($this->db_groups).
775 " SET del=1, changed=".$this->db->now().
776 " WHERE contactgroup_id=?",
782 return $this->db->affected_rows();
787 * Rename a specific contact group
789 * @param string Group identifier
790 * @param string New name to set for this group
791 * @return boolean New name on success, false if no data was changed
793 function rename_group($gid, $newname)
795 // make sure we have a unique name
796 $name = $this->unique_groupname($newname);
798 $sql_result = $this->db->query(
799 "UPDATE ".get_table_name($this->db_groups).
800 " SET name=?, changed=".$this->db->now().
801 " WHERE contactgroup_id=?",
805 return $this->db->affected_rows() ? $name : false;
810 * Add the given contact records the a certain group
812 * @param string Group identifier
813 * @param array List of contact identifiers to be added
814 * @return int Number of contacts added
816 function add_to_group($group_id, $ids)
819 $ids = explode(',', $ids);
824 // get existing assignments ...
825 $sql_result = $this->db->query(
826 "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
827 " WHERE contactgroup_id=?".
828 " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
831 while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
832 $exists[] = $sql_arr['contact_id'];
834 // ... and remove them from the list
835 $ids = array_diff($ids, $exists);
837 foreach ($ids as $contact_id) {
839 "INSERT INTO ".get_table_name($this->db_groupmembers).
840 " (contactgroup_id, contact_id, created)".
841 " VALUES (?, ?, ".$this->db->now().")",
846 if (!$this->db->db_error)
855 * Remove the given contact records from a certain group
857 * @param string Group identifier
858 * @param array List of contact identifiers to be removed
859 * @return int Number of deleted group members
861 function remove_from_group($group_id, $ids)
864 $ids = explode(',', $ids);
866 $ids = $this->db->array2list($ids, 'integer');
868 $sql_result = $this->db->query(
869 "DELETE FROM ".get_table_name($this->db_groupmembers).
870 " WHERE contactgroup_id=?".
871 " AND contact_id IN ($ids)",
875 return $this->db->affected_rows();
880 * Check for existing groups with the same name
882 * @param string Name to check
883 * @return string A group name which is unique for the current use
885 private function unique_groupname($name)
888 $num = 2; $hit = false;
891 $sql_result = $this->db->query(
892 "SELECT 1 FROM ".get_table_name($this->db_groups).
899 // append number to make name unique
900 if ($hit = $this->db->num_rows($sql_result))
901 $checkname = $name . ' ' . $num++;