]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_contacts.php
af07b32bedd9d91bf07c2ed3f1b3dc20afa22320
[roundcube.git] / program / include / rcube_contacts.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_contacts.php                                    |
6  |                                                                       |
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                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Interface to the local address book database                        |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: rcube_contacts.php 5011 2011-08-03 09:32:45Z alec $
19
20 */
21
22
23 /**
24  * Model class for the local address book database
25  *
26  * @package Addressbook
27  */
28 class rcube_contacts extends rcube_addressbook
29 {
30     // protected for backward compat. with some plugins
31     protected $db_name = 'contacts';
32     protected $db_groups = 'contactgroups';
33     protected $db_groupmembers = 'contactgroupmembers';
34
35     /**
36      * Store database connection.
37      *
38      * @var rcube_mdb2
39      */
40     private $db = null;
41     private $user_id = 0;
42     private $filter = null;
43     private $result = null;
44     private $name;
45     private $cache;
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');
50
51     // public properties
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;
58     public $group_id = 0;
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');
64
65
66     /**
67      * Object constructor
68      *
69      * @param object  Instance of the rcube_db class
70      * @param integer User-ID
71      */
72     function __construct($dbconn, $user)
73     {
74         $this->db = $dbconn;
75         $this->user_id = $user;
76         $this->ready = $this->db && !$this->db->is_error();
77     }
78
79
80     /**
81      * Returns addressbook name
82      */
83      function get_name()
84      {
85         return $this->name;
86      }
87
88
89     /**
90      * Save a search string for future listings
91      *
92      * @param string SQL params to use in listing method
93      */
94     function set_search_set($filter)
95     {
96         $this->filter = $filter;
97         $this->cache = null;
98     }
99
100
101     /**
102      * Getter for saved search properties
103      *
104      * @return mixed Search properties used by this class
105      */
106     function get_search_set()
107     {
108         return $this->filter;
109     }
110
111
112     /**
113      * Setter for the current group
114      * (empty, has to be re-implemented by extending class)
115      */
116     function set_group($gid)
117     {
118         $this->group_id = $gid;
119         $this->cache = null;
120     }
121
122
123     /**
124      * Reset all saved results and search parameters
125      */
126     function reset()
127     {
128         $this->result = null;
129         $this->filter = null;
130         $this->cache = null;
131     }
132
133
134     /**
135      * List all active contact groups of this source
136      *
137      * @param string  Search string to match group name
138      * @return array  Indexed list of contact groups, each a hash array
139      */
140     function list_groups($search = null)
141     {
142         $results = array();
143
144         if (!$this->groups)
145             return $results;
146
147         $sql_filter = $search ? " AND " . $this->db->ilike('name', '%'.$search.'%') : '';
148
149         $sql_result = $this->db->query(
150             "SELECT * FROM ".get_table_name($this->db_groups).
151             " WHERE del<>1".
152             " AND user_id=?".
153             $sql_filter.
154             " ORDER BY name",
155             $this->user_id);
156
157         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
158             $sql_arr['ID'] = $sql_arr['contactgroup_id'];
159             $results[]     = $sql_arr;
160         }
161
162         return $results;
163     }
164
165
166     /**
167      * List the current set of contact records
168      *
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
173      */
174     function list_records($cols=null, $subset=0, $nocount=false)
175     {
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();
179         } else {
180             // count all records
181             $this->result = $this->count();
182         }
183
184         $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
185         $length = $subset != 0 ? abs($subset) : $this->page_size;
186
187         if ($this->group_id)
188             $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
189                 " ON (m.contact_id = c.".$this->primary_key.")";
190
191         $sql_result = $this->db->limitquery(
192             "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
193             $join .
194             " WHERE c.del<>1" .
195                 " AND c.user_id=?" .
196                 ($this->group_id ? " AND m.contactgroup_id=?" : "").
197                 ($this->filter ? " AND (".$this->filter.")" : "") .
198             " ORDER BY ". $this->db->concat('c.name', 'c.email'),
199             $start_row,
200             $length,
201             $this->user_id,
202             $this->group_id);
203
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);
206
207         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
208             $sql_arr['ID'] = $sql_arr[$this->primary_key];
209
210             if ($read_vcard)
211                 $sql_arr = $this->convert_db_data($sql_arr);
212             else
213                 $sql_arr['email'] = preg_split('/,\s*/', $sql_arr['email']);
214
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];
220             }
221
222             $this->result->add($sql_arr);
223         }
224
225         $cnt = count($this->result->records);
226
227         // update counter
228         if ($nocount)
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'];
235             else
236                 $this->result->count = $this->_count();
237         }
238
239         return $this->result;
240     }
241
242
243     /**
244      * Search contacts
245      *
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
252      *
253      * @return object rcube_result_set Contact records and 'count' value
254      */
255     function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
256     {
257         if (!is_array($fields))
258             $fields = array($fields);
259         if (!is_array($required) && !empty($required))
260             $required = array($required);
261
262         $where = $and_where = array();
263
264         foreach ($fields as $idx => $col) {
265             // direct ID search
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.')';
270                 continue;
271             }
272             // fulltext search in all fields
273             else if ($col == '*') {
274                 $words = array();
275                 foreach (explode(" ", self::normalize_string($value)) as $word)
276                     $words[] = $this->db->ilike('words', '%'.$word.'%');
277                 $where[] = '(' . join(' AND ', $words) . ')';
278             }
279             else {
280                 $val = is_array($value) ? $value[$idx] : $value;
281                 // table column
282                 if (in_array($col, $this->table_cols)) {
283                     if ($strict) {
284                         $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($val);
285                     }
286                     else {
287                         $where[] = $this->db->ilike($col, '%'.$val.'%');
288                     }
289                 }
290                 // vCard field
291                 else {
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) . ')';
296                     }
297                     if (is_array($value))
298                         $post_search[$col] = mb_strtolower($val);
299                 }
300             }
301         }
302
303         foreach (array_intersect($required, $this->table_cols) as $col) {
304             $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
305         }
306
307         if (!empty($where)) {
308             // use AND operator for advanced searches
309             $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
310         }
311
312         if (!empty($and_where))
313             $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
314
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)) {
318             $ids = array(0);
319             // build key name regexp
320             $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
321             // use initial WHERE clause, to limit records number if possible
322             if (!empty($where))
323                 $this->set_search_set($where);
324
325             // count result pages
326             $cnt   = $this->count();
327             $pages = ceil($cnt / $this->page_size);
328             $scnt  = count($post_search);
329
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];
335                     $found = array();
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);
344                             }
345                             $value = mb_strtolower($value);
346                             if (($strict && $value == $search) || (!$strict && strpos($value, $search) !== false)) {
347                                 $found[$colname] = true;
348                                 break;
349                             }
350                         }
351                     }
352                     // all fields match
353                     if (count($found) >= $scnt) {
354                         $ids[] = $id;
355                     }
356                 }
357             }
358
359             // build WHERE clause
360             $ids = $this->db->array2list($ids, 'integer');
361             $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
362             // reset counter
363             unset($this->cache['count']);
364
365             // when we know we have an empty result
366             if ($ids == '0') {
367                 $this->set_search_set($where);
368                 return ($this->result = new rcube_result_set(0, 0));
369             }
370         }
371
372         if (!empty($where)) {
373             $this->set_search_set($where);
374             if ($select)
375                 $this->list_records(null, 0, $nocount);
376             else
377                 $this->result = $this->count();
378         }
379
380         return $this->result;
381     }
382
383
384     /**
385      * Count number of available contacts in database
386      *
387      * @return rcube_result_set Result object
388      */
389     function count()
390     {
391         $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
392
393         return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
394     }
395
396
397     /**
398      * Count number of available contacts in database
399      *
400      * @return int Contacts count
401      */
402     private function _count()
403     {
404         if ($this->group_id)
405             $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
406                 " ON (m.contact_id=c.".$this->primary_key.")";
407
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".
412                 $join.
413             " WHERE c.del<>1".
414             " AND c.user_id=?".
415             ($this->group_id ? " AND m.contactgroup_id=?" : "").
416             ($this->filter ? " AND (".$this->filter.")" : ""),
417             $this->user_id,
418             $this->group_id
419         );
420
421         $sql_arr = $this->db->fetch_assoc($sql_result);
422
423         $this->cache['count'] = (int) $sql_arr['rows'];
424
425         return $this->cache['count'];
426     }
427
428
429     /**
430      * Return the last result set
431      *
432      * @return mixed Result array or NULL if nothing selected yet
433      */
434     function get_result()
435     {
436         return $this->result;
437     }
438
439
440     /**
441      * Get a specific contact record
442      *
443      * @param mixed record identifier(s)
444      * @return mixed Result object with all record fields or False if not found
445      */
446     function get_record($id, $assoc=false)
447     {
448         // return cached result
449         if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
450             return $assoc ? $first : $this->result;
451
452         $this->db->query(
453             "SELECT * FROM ".get_table_name($this->db_name).
454             " WHERE contact_id=?".
455                 " AND user_id=?".
456                 " AND del<>1",
457             $id,
458             $this->user_id
459         );
460
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);
465         }
466
467         return $assoc && $record ? $record : $this->result;
468     }
469
470
471     /**
472      * Get group assignments of a specific contact record
473      *
474      * @param mixed Record identifier
475      * @return array List of assigned groups as ID=>Name pairs
476      */
477     function get_record_groups($id)
478     {
479       $results = array();
480
481       if (!$this->groups)
482           return $results;
483
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=?",
488         $id
489       );
490       while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
491         $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
492       }
493
494       return $results;
495     }
496
497
498     /**
499      * Check the given data before saving.
500      * If input not valid, the message to display can be fetched using get_error()
501      *
502      * @param array Assoziative array with data to save
503      * @return boolean True if input is valid, False if not.
504      */
505     public function validate($save_data)
506     {
507         // validate e-mail addresses
508         $valid = parent::validate($save_data);
509
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');
513             $valid = false;
514         }
515
516         return $valid;
517     }
518
519
520     /**
521      * Create a new contact record
522      *
523      * @param array Associative array with save data
524      * @return integer|boolean The created record ID on success, False on error
525      */
526     function insert($save_data, $check=false)
527     {
528         if (!is_array($save_data))
529             return false;
530
531         $insert_id = $existing = false;
532
533         if ($check) {
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))
538                             break 2;
539                     }
540                 }
541             }
542         }
543
544         $save_data = $this->convert_save_data($save_data);
545         $a_insert_cols = $a_insert_values = array();
546
547         foreach ($save_data as $col => $value) {
548             $a_insert_cols[]   = $this->db->quoteIdentifier($col);
549             $a_insert_values[] = $this->db->quote($value);
550         }
551
552         if (!$existing->count && !empty($a_insert_cols)) {
553             $this->db->query(
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).")"
557             );
558
559             $insert_id = $this->db->insert_id($this->db_name);
560         }
561
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);
565
566         $this->cache = null;
567
568         return $insert_id;
569     }
570
571
572     /**
573      * Update a specific contact record
574      *
575      * @param mixed Record identifier
576      * @param array Assoziative array with save data
577      * @return boolean True on success, False on error
578      */
579     function update($id, $save_cols)
580     {
581         $updated = false;
582         $write_sql = array();
583         $record = $this->get_record($id, true);
584         $save_cols = $this->convert_save_data($save_cols, $record);
585
586         foreach ($save_cols as $col => $value) {
587             $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
588         }
589
590         if (!empty($write_sql)) {
591             $this->db->query(
592                 "UPDATE ".get_table_name($this->db_name).
593                 " SET changed=".$this->db->now().", ".join(', ', $write_sql).
594                 " WHERE contact_id=?".
595                     " AND user_id=?".
596                     " AND del<>1",
597                 $id,
598                 $this->user_id
599             );
600
601             $updated = $this->db->affected_rows();
602             $this->result = null;  // clear current result (from get_record())
603         }
604
605         return $updated;
606     }
607
608
609     private function convert_db_data($sql_arr)
610     {
611         $record = array();
612         $record['ID'] = $sql_arr[$this->primary_key];
613
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;
618         }
619         else {
620             $record += $sql_arr;
621             $record['email'] = preg_split('/,\s*/', $record['email']);
622         }
623
624         return $record;
625     }
626
627
628     private function convert_save_data($save_data, $record = array())
629     {
630         $out = array();
631         $words = '';
632
633         // copy values into vcard object
634         $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
635         $vcard->reset();
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) {
640                 if (isset($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);
646             }
647         }
648         $out['vcard'] = $vcard->export(false);
649
650         foreach ($this->table_cols as $col) {
651             $key = $col;
652             if (!isset($save_data[$key]))
653                 $key .= ':home';
654             if (isset($save_data[$key]))
655                 $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
656         }
657
658         // save all e-mails in database column
659         $out['email'] = join(", ", $vcard->email);
660
661         // join words for fulltext search
662         $out['words'] = join(" ", array_unique(explode(" ", $words)));
663
664         return $out;
665     }
666
667
668     /**
669      * Mark one or more contact records as deleted
670      *
671      * @param array   Record identifiers
672      * @param boolean Remove record(s) irreversible (unsupported)
673      */
674     function delete($ids, $force=true)
675     {
676         if (!is_array($ids))
677             $ids = explode(',', $ids);
678
679         $ids = $this->db->array2list($ids, 'integer');
680
681         // flag record as deleted (always)
682         $this->db->query(
683             "UPDATE ".get_table_name($this->db_name).
684             " SET del=1, changed=".$this->db->now().
685             " WHERE user_id=?".
686                 " AND contact_id IN ($ids)",
687             $this->user_id
688         );
689
690         $this->cache = null;
691
692         return $this->db->affected_rows();
693     }
694
695
696     /**
697      * Undelete one or more contact records
698      *
699      * @param array  Record identifiers
700      */
701     function undelete($ids)
702     {
703         if (!is_array($ids))
704             $ids = explode(',', $ids);
705
706         $ids = $this->db->array2list($ids, 'integer');
707
708         // clear deleted flag
709         $this->db->query(
710             "UPDATE ".get_table_name($this->db_name).
711             " SET del=0, changed=".$this->db->now().
712             " WHERE user_id=?".
713                 " AND contact_id IN ($ids)",
714             $this->user_id
715         );
716
717         $this->cache = null;
718
719         return $this->db->affected_rows();
720     }
721
722
723     /**
724      * Remove all records from the database
725      */
726     function delete_all()
727     {
728         $this->cache = null;
729
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);
733
734         return $this->db->affected_rows();
735     }
736
737
738     /**
739      * Create a contact group with the given name
740      *
741      * @param string The group name
742      * @return mixed False on error, array with record props in success
743      */
744     function create_group($name)
745     {
746         $result = false;
747
748         // make sure we have a unique name
749         $name = $this->unique_groupname($name);
750
751         $this->db->query(
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).")"
755         );
756
757         if ($insert_id = $this->db->insert_id($this->db_groups))
758             $result = array('id' => $insert_id, 'name' => $name);
759
760         return $result;
761     }
762
763
764     /**
765      * Delete the given group (and all linked group members)
766      *
767      * @param string Group identifier
768      * @return boolean True on success, false if no data was changed
769      */
770     function delete_group($gid)
771     {
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=?",
777             $gid
778         );
779
780         $this->cache = null;
781
782         return $this->db->affected_rows();
783     }
784
785
786     /**
787      * Rename a specific contact group
788      *
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
792      */
793     function rename_group($gid, $newname)
794     {
795         // make sure we have a unique name
796         $name = $this->unique_groupname($newname);
797
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=?",
802             $name, $gid
803         );
804
805         return $this->db->affected_rows() ? $name : false;
806     }
807
808
809     /**
810      * Add the given contact records the a certain group
811      *
812      * @param string  Group identifier
813      * @param array   List of contact identifiers to be added
814      * @return int    Number of contacts added 
815      */
816     function add_to_group($group_id, $ids)
817     {
818         if (!is_array($ids))
819             $ids = explode(',', $ids);
820
821         $added = 0;
822         $exists = array();
823
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').")",
829             $group_id
830         );
831         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
832             $exists[] = $sql_arr['contact_id'];
833         }
834         // ... and remove them from the list
835         $ids = array_diff($ids, $exists);
836
837         foreach ($ids as $contact_id) {
838             $this->db->query(
839                 "INSERT INTO ".get_table_name($this->db_groupmembers).
840                 " (contactgroup_id, contact_id, created)".
841                 " VALUES (?, ?, ".$this->db->now().")",
842                 $group_id,
843                 $contact_id
844             );
845
846             if (!$this->db->db_error)
847                 $added++;
848         }
849
850         return $added;
851     }
852
853
854     /**
855      * Remove the given contact records from a certain group
856      *
857      * @param string  Group identifier
858      * @param array   List of contact identifiers to be removed
859      * @return int    Number of deleted group members
860      */
861     function remove_from_group($group_id, $ids)
862     {
863         if (!is_array($ids))
864             $ids = explode(',', $ids);
865
866         $ids = $this->db->array2list($ids, 'integer');
867
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)",
872             $group_id
873         );
874
875         return $this->db->affected_rows();
876     }
877
878
879     /**
880      * Check for existing groups with the same name
881      *
882      * @param string Name to check
883      * @return string A group name which is unique for the current use
884      */
885     private function unique_groupname($name)
886     {
887         $checkname = $name;
888         $num = 2; $hit = false;
889
890         do {
891             $sql_result = $this->db->query(
892                 "SELECT 1 FROM ".get_table_name($this->db_groups).
893                 " WHERE del<>1".
894                     " AND user_id=?".
895                     " AND name=?",
896                 $this->user_id,
897                 $checkname);
898
899             // append number to make name unique
900             if ($hit = $this->db->num_rows($sql_result))
901                 $checkname = $name . ' ' . $num++;
902         } while ($hit > 0);
903
904         return $checkname;
905     }
906
907 }