alecpl
2011-05-21 bc8c2c57880523472b30f475d566a8133e2d2e20
commit | author | age
f11541 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
47124c 5  | program/include/rcube_contacts.php                                    |
f11541 6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
3e2637 8  | Copyright (C) 2006-2011, The Roundcube Dev Team                       |
f11541 9  | Licensed under the GNU GPL                                            |
T 10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Interface to the local address book database                        |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
638fb8 18  $Id$
f11541 19
T 20 */
21
6d969b 22
T 23 /**
24  * Model class for the local address book database
25  *
26  * @package Addressbook
27  */
cc97ea 28 class rcube_contacts extends rcube_addressbook
f11541 29 {
495c0e 30     // protected for backward compat. with some plugins
982e0b 31     protected $db_name = 'contacts';
A 32     protected $db_groups = 'contactgroups';
33     protected $db_groupmembers = 'contactgroupmembers';
34
5c461b 35     /**
A 36      * Store database connection.
37      *
38      * @var rcube_mdb2
39      */
3d6c04 40     private $db = null;
A 41     private $user_id = 0;
42     private $filter = null;
43     private $result = null;
566b14 44     private $cache;
3e2637 45     private $table_cols = array('name', 'email', 'firstname', 'surname');
T 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');
25fdec 49
982e0b 50     // public properties
0501b6 51     public $primary_key = 'contact_id';
T 52     public $readonly = false;
53     public $groups = true;
54     public $list_page = 1;
55     public $page_size = 10;
56     public $group_id = 0;
57     public $ready = false;
58     public $coltypes = array('name', 'firstname', 'surname', 'middlename', 'prefix', 'suffix', 'nickname',
59       'jobtitle', 'organization', 'department', 'assistant', 'manager',
60       'gender', 'maidenname', 'spouse', 'email', 'phone', 'address',
61       'birthday', 'anniversary', 'website', 'im', 'notes', 'photo');
f11541 62
25fdec 63
3d6c04 64     /**
A 65      * Object constructor
66      *
67      * @param object  Instance of the rcube_db class
68      * @param integer User-ID
69      */
70     function __construct($dbconn, $user)
f11541 71     {
3d6c04 72         $this->db = $dbconn;
A 73         $this->user_id = $user;
74         $this->ready = $this->db && !$this->db->is_error();
f11541 75     }
T 76
77
3d6c04 78     /**
A 79      * Save a search string for future listings
80      *
81      * @param  string SQL params to use in listing method
82      */
83     function set_search_set($filter)
f11541 84     {
3d6c04 85         $this->filter = $filter;
566b14 86         $this->cache = null;
3d6c04 87     }
A 88
25fdec 89
3d6c04 90     /**
A 91      * Getter for saved search properties
92      *
93      * @return mixed Search properties used by this class
94      */
95     function get_search_set()
96     {
97         return $this->filter;
98     }
99
100
101     /**
102      * Setter for the current group
103      * (empty, has to be re-implemented by extending class)
104      */
105     function set_group($gid)
106     {
107         $this->group_id = $gid;
566b14 108         $this->cache = null;
3d6c04 109     }
A 110
111
112     /**
113      * Reset all saved results and search parameters
114      */
115     function reset()
116     {
117         $this->result = null;
118         $this->filter = null;
566b14 119         $this->cache = null;
3d6c04 120     }
25fdec 121
3d6c04 122
A 123     /**
124      * List all active contact groups of this source
125      *
126      * @param string  Search string to match group name
127      * @return array  Indexed list of contact groups, each a hash array
128      */
129     function list_groups($search = null)
130     {
131         $results = array();
25fdec 132
3d6c04 133         if (!$this->groups)
A 134             return $results;
d17a7f 135
631967 136         $sql_filter = $search ? " AND " . $this->db->ilike('name', '%'.$search.'%') : '';
3d6c04 137
A 138         $sql_result = $this->db->query(
982e0b 139             "SELECT * FROM ".get_table_name($this->db_groups).
3d6c04 140             " WHERE del<>1".
A 141             " AND user_id=?".
142             $sql_filter.
143             " ORDER BY name",
144             $this->user_id);
145
146         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
147             $sql_arr['ID'] = $sql_arr['contactgroup_id'];
148             $results[]     = $sql_arr;
149         }
150
151         return $results;
152     }
153
154
155     /**
156      * List the current set of contact records
157      *
0501b6 158      * @param  array   List of cols to show, Null means all
3d6c04 159      * @param  int     Only return this number of records, use negative values for tail
A 160      * @param  boolean True to skip the count query (select only)
161      * @return array  Indexed list of contact records, each a hash array
162      */
163     function list_records($cols=null, $subset=0, $nocount=false)
164     {
165         if ($nocount || $this->list_page <= 1) {
166             // create dummy result, we don't need a count now
167             $this->result = new rcube_result_set();
168         } else {
169             // count all records
170             $this->result = $this->count();
171         }
172
173         $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
174         $length = $subset != 0 ? abs($subset) : $this->page_size;
175
176         if ($this->group_id)
982e0b 177             $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
3d6c04 178                 " ON (m.contact_id = c.".$this->primary_key.")";
A 179
180         $sql_result = $this->db->limitquery(
982e0b 181             "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
821a56 182             $join .
3d6c04 183             " WHERE c.del<>1" .
566b14 184                 " AND c.user_id=?" .
A 185                 ($this->group_id ? " AND m.contactgroup_id=?" : "").
186                 ($this->filter ? " AND (".$this->filter.")" : "") .
0ec7fe 187             " ORDER BY ". $this->db->concat('c.name', 'c.email'),
3d6c04 188             $start_row,
A 189             $length,
190             $this->user_id,
191             $this->group_id);
192
0501b6 193         // determine whether we have to parse the vcard or if only db cols are requested
T 194         $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
195         
3d6c04 196         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
A 197             $sql_arr['ID'] = $sql_arr[$this->primary_key];
0501b6 198
T 199             if ($read_vcard)
200                 $sql_arr = $this->convert_db_data($sql_arr);
201             else
202                 $sql_arr['email'] = preg_split('/,\s*/', $sql_arr['email']);
445a4c 203
3d6c04 204             // make sure we have a name to display
445a4c 205             if (empty($sql_arr['name'])) {
T 206                 if (empty($sql_arr['email']))
207                   $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
0501b6 208                 $sql_arr['name'] = $sql_arr['email'][0];
445a4c 209             }
0501b6 210
3d6c04 211             $this->result->add($sql_arr);
A 212         }
25fdec 213
3d6c04 214         $cnt = count($this->result->records);
A 215
216         // update counter
217         if ($nocount)
218             $this->result->count = $cnt;
219         else if ($this->list_page <= 1) {
220             if ($cnt < $this->page_size && $subset == 0)
221                 $this->result->count = $cnt;
821a56 222             else if (isset($this->cache['count']))
A 223                 $this->result->count = $this->cache['count'];
3d6c04 224             else
A 225                 $this->result->count = $this->_count();
226         }
25fdec 227
3d6c04 228         return $this->result;
A 229     }
230
231
232     /**
233      * Search contacts
234      *
235      * @param array   List of fields to search in
236      * @param string  Search value
237      * @param boolean True for strict (=), False for partial (LIKE) matching
238      * @param boolean True if results are requested, False if count only
239      * @param boolean True to skip the count query (select only)
25fdec 240      * @param array   List of fields that cannot be empty
0501b6 241      * @return object rcube_result_set Contact records and 'count' value
3d6c04 242      */
25fdec 243     function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
3d6c04 244     {
A 245         if (!is_array($fields))
246             $fields = array($fields);
25fdec 247         if (!is_array($required) && !empty($required))
A 248             $required = array($required);
566b14 249
25fdec 250         $where = $and_where = array();
A 251
3d6c04 252         foreach ($fields as $col) {
A 253             if ($col == 'ID' || $col == $this->primary_key) {
25fdec 254                 $ids     = !is_array($value) ? explode(',', $value) : $value;
A 255                 $ids     = $this->db->array2list($ids, 'integer');
256                 $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
3d6c04 257             }
3e2637 258             else if ($strict) {
25fdec 259                 $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($value);
3e2637 260             }
T 261             else if ($col == '*') {
262                 $words = array();
263                 foreach(explode(" ", self::normalize_string($value)) as $word)
264                     $words[] = $this->db->ilike('words', '%'.$word.'%');
265                 $where[] = '(' . join(' AND ', $words) . ')';
266               }
3d6c04 267             else
25fdec 268                 $where[] = $this->db->ilike($col, '%'.$value.'%');
3d6c04 269         }
25fdec 270
A 271         foreach ($required as $col) {
272             $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
273         }
274
275         if (!empty($where))
276             $where = join(' OR ', $where);
277
278         if (!empty($and_where))
279             $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
280
281         if (!empty($where)) {
282             $this->set_search_set($where);
3d6c04 283             if ($select)
A 284                 $this->list_records(null, 0, $nocount);
285             else
286                 $this->result = $this->count();
287         }
288
289         return $this->result; 
290     }
291
292
293     /**
294      * Count number of available contacts in database
295      *
296      * @return rcube_result_set Result object
297      */
298     function count()
299     {
566b14 300         $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
25fdec 301
566b14 302         return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
3d6c04 303     }
A 304
305
306     /**
307      * Count number of available contacts in database
308      *
309      * @return int Contacts count
310      */
311     private function _count()
312     {
313         if ($this->group_id)
982e0b 314             $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
3d6c04 315                 " ON (m.contact_id=c.".$this->primary_key.")";
25fdec 316
3d6c04 317         // count contacts for this user
A 318         $sql_result = $this->db->query(
319             "SELECT COUNT(c.contact_id) AS rows".
982e0b 320             " FROM ".get_table_name($this->db_name)." AS c".
821a56 321                 $join.
A 322             " WHERE c.del<>1".
3d6c04 323             " AND c.user_id=?".
A 324             ($this->group_id ? " AND m.contactgroup_id=?" : "").
325             ($this->filter ? " AND (".$this->filter.")" : ""),
326             $this->user_id,
327             $this->group_id
4307cc 328         );
3d6c04 329
A 330         $sql_arr = $this->db->fetch_assoc($sql_result);
566b14 331
A 332         $this->cache['count'] = (int) $sql_arr['rows'];
333
334         return $this->cache['count'];
f11541 335     }
T 336
337
3d6c04 338     /**
A 339      * Return the last result set
340      *
5c461b 341      * @return mixed Result array or NULL if nothing selected yet
3d6c04 342      */
A 343     function get_result()
f11541 344     {
3d6c04 345         return $this->result;
f11541 346     }
25fdec 347
A 348
3d6c04 349     /**
A 350      * Get a specific contact record
351      *
352      * @param mixed record identifier(s)
5c461b 353      * @return mixed Result object with all record fields or False if not found
3d6c04 354      */
A 355     function get_record($id, $assoc=false)
f11541 356     {
3d6c04 357         // return cached result
A 358         if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
359             return $assoc ? $first : $this->result;
25fdec 360
a61bbb 361         $this->db->query(
982e0b 362             "SELECT * FROM ".get_table_name($this->db_name).
3d6c04 363             " WHERE contact_id=?".
A 364                 " AND user_id=?".
365                 " AND del<>1",
366             $id,
367             $this->user_id
a61bbb 368         );
3d6c04 369
A 370         if ($sql_arr = $this->db->fetch_assoc()) {
0501b6 371             $record = $this->convert_db_data($sql_arr);
3d6c04 372             $this->result = new rcube_result_set(1);
0501b6 373             $this->result->add($record);
3d6c04 374         }
A 375
0501b6 376         return $assoc && $record ? $record : $this->result;
a61bbb 377     }
3d6c04 378
A 379
380     /**
b393e5 381      * Get group assignments of a specific contact record
cb7d32 382      *
T 383      * @param mixed Record identifier
b393e5 384      * @return array List of assigned groups as ID=>Name pairs
cb7d32 385      */
T 386     function get_record_groups($id)
387     {
388       $results = array();
389
390       if (!$this->groups)
391           return $results;
392
393       $sql_result = $this->db->query(
394         "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
395         " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
396         " WHERE cgm.contact_id=?",
397         $id
398       );
399       while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
400         $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
401       }
402
403       return $results;
404     }
405
406
407     /**
07b95d 408      * Check the given data before saving.
T 409      * If input not valid, the message to display can be fetched using get_error()
410      *
411      * @param array Assoziative array with data to save
412      * @return boolean True if input is valid, False if not.
413      */
414     public function validate($save_data)
415     {
e84818 416         // validate e-mail addresses
07b95d 417         $valid = parent::validate($save_data);
T 418
e84818 419         // require at least one e-mail address (syntax check is already done)
07b95d 420         if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
T 421             $this->set_error('warning', 'noemailwarning');
422             $valid = false;
423         }
424
425         return $valid;
426     }
427
428
429     /**
3d6c04 430      * Create a new contact record
A 431      *
b393e5 432      * @param array Associative array with save data
5c461b 433      * @return integer|boolean The created record ID on success, False on error
3d6c04 434      */
A 435     function insert($save_data, $check=false)
436     {
0501b6 437         if (!is_array($save_data))
T 438             return false;
3d6c04 439
A 440         $insert_id = $existing = false;
441
0501b6 442         if ($check) {
T 443             foreach ($save_data as $col => $values) {
444                 if (strpos($col, 'email') === 0) {
445                     foreach ((array)$values as $email) {
715c79 446                         if ($existing = $this->search('email', $email, false, false))
0501b6 447                             break 2;
T 448                     }
449                 }
450             }
451         }
3d6c04 452
0501b6 453         $save_data = $this->convert_save_data($save_data);
3d6c04 454         $a_insert_cols = $a_insert_values = array();
A 455
0501b6 456         foreach ($save_data as $col => $value) {
T 457             $a_insert_cols[]   = $this->db->quoteIdentifier($col);
458             $a_insert_values[] = $this->db->quote($value);
459         }
3d6c04 460
A 461         if (!$existing->count && !empty($a_insert_cols)) {
462             $this->db->query(
982e0b 463                 "INSERT INTO ".get_table_name($this->db_name).
3d6c04 464                 " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
A 465                 " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
466             );
467
982e0b 468             $insert_id = $this->db->insert_id($this->db_name);
3d6c04 469         }
A 470
471         // also add the newly created contact to the active group
472         if ($insert_id && $this->group_id)
473             $this->add_to_group($this->group_id, $insert_id);
474
566b14 475         $this->cache = null;
A 476
3d6c04 477         return $insert_id;
A 478     }
479
480
481     /**
482      * Update a specific contact record
483      *
484      * @param mixed Record identifier
485      * @param array Assoziative array with save data
5c461b 486      * @return boolean True on success, False on error
3d6c04 487      */
A 488     function update($id, $save_cols)
489     {
490         $updated = false;
491         $write_sql = array();
0501b6 492         $record = $this->get_record($id, true);
T 493         $save_cols = $this->convert_save_data($save_cols, $record);
3d6c04 494
0501b6 495         foreach ($save_cols as $col => $value) {
T 496             $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
497         }
3d6c04 498
A 499         if (!empty($write_sql)) {
500             $this->db->query(
982e0b 501                 "UPDATE ".get_table_name($this->db_name).
3d6c04 502                 " SET changed=".$this->db->now().", ".join(', ', $write_sql).
A 503                 " WHERE contact_id=?".
504                     " AND user_id=?".
505                     " AND del<>1",
506                 $id,
507                 $this->user_id
508             );
509
510             $updated = $this->db->affected_rows();
0501b6 511             $this->result = null;  // clear current result (from get_record())
3d6c04 512         }
25fdec 513
3d6c04 514         return $updated;
A 515     }
0501b6 516     
T 517     
518     private function convert_db_data($sql_arr)
519     {
520         $record = array();
521         $record['ID'] = $sql_arr[$this->primary_key];
522         
523         if ($sql_arr['vcard']) {
524             unset($sql_arr['email']);
525             $vcard = new rcube_vcard($sql_arr['vcard']);
526             $record += $vcard->get_assoc() + $sql_arr;
527         }
528         else {
529             $record += $sql_arr;
530             $record['email'] = preg_split('/,\s*/', $record['email']);
531         }
532         
533         return $record;
534     }
535
536
537     private function convert_save_data($save_data, $record = array())
538     {
539         $out = array();
3e2637 540         $words = '';
0501b6 541
T 542         // copy values into vcard object
543         $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
544         $vcard->reset();
545         foreach ($save_data as $key => $values) {
546             list($field, $section) = explode(':', $key);
3e2637 547             $fulltext = in_array($field, $this->fulltext_cols);
0501b6 548             foreach ((array)$values as $value) {
T 549                 if (isset($value))
550                     $vcard->set($field, $value, $section);
3e2637 551                 if ($fulltext && is_array($value))
T 552                     $words .= ' ' . self::normalize_string(join(" ", $value));
553                 else if ($fulltext && strlen($value) >= 3)
554                     $words .= ' ' . self::normalize_string($value);
0501b6 555             }
T 556         }
569f83 557         $out['vcard'] = $vcard->export(false);
0501b6 558
T 559         foreach ($this->table_cols as $col) {
560             $key = $col;
561             if (!isset($save_data[$key]))
562                 $key .= ':home';
563             if (isset($save_data[$key]))
564                 $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
565         }
566
567         // save all e-mails in database column
568         $out['email'] = join(", ", $vcard->email);
569
3e2637 570         // join words for fulltext search
T 571         $out['words'] = join(" ", array_unique(explode(" ", $words)));
572
0501b6 573         return $out;
T 574     }
3d6c04 575
A 576
577     /**
578      * Mark one or more contact records as deleted
579      *
580      * @param array  Record identifiers
581      */
582     function delete($ids)
583     {
566b14 584         if (!is_array($ids))
A 585             $ids = explode(',', $ids);
3d6c04 586
a004bb 587         $ids = $this->db->array2list($ids, 'integer');
3d6c04 588
A 589         // flag record as deleted
590         $this->db->query(
982e0b 591             "UPDATE ".get_table_name($this->db_name).
3d6c04 592             " SET del=1, changed=".$this->db->now().
A 593             " WHERE user_id=?".
594                 " AND contact_id IN ($ids)",
595             $this->user_id
596         );
597
566b14 598         $this->cache = null;
A 599
3d6c04 600         return $this->db->affected_rows();
A 601     }
602
603
604     /**
605      * Remove all records from the database
606      */
607     function delete_all()
608     {
982e0b 609         $this->db->query("DELETE FROM ".get_table_name($this->db_name)." WHERE user_id = ?", $this->user_id);
566b14 610         $this->cache = null;
3d6c04 611         return $this->db->affected_rows();
A 612     }
613
614
615     /**
616      * Create a contact group with the given name
617      *
618      * @param string The group name
5c461b 619      * @return mixed False on error, array with record props in success
3d6c04 620      */
A 621     function create_group($name)
622     {
623         $result = false;
624
625         // make sure we have a unique name
626         $name = $this->unique_groupname($name);
25fdec 627
3d6c04 628         $this->db->query(
982e0b 629             "INSERT INTO ".get_table_name($this->db_groups).
3d6c04 630             " (user_id, changed, name)".
A 631             " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
632         );
25fdec 633
982e0b 634         if ($insert_id = $this->db->insert_id($this->db_groups))
3d6c04 635             $result = array('id' => $insert_id, 'name' => $name);
25fdec 636
3d6c04 637         return $result;
A 638     }
639
640
641     /**
642      * Delete the given group (and all linked group members)
643      *
644      * @param string Group identifier
645      * @return boolean True on success, false if no data was changed
646      */
647     function delete_group($gid)
648     {
649         // flag group record as deleted
650         $sql_result = $this->db->query(
982e0b 651             "UPDATE ".get_table_name($this->db_groups).
3d6c04 652             " SET del=1, changed=".$this->db->now().
A 653             " WHERE contactgroup_id=?",
654             $gid
655         );
656
566b14 657         $this->cache = null;
A 658
3d6c04 659         return $this->db->affected_rows();
A 660     }
661
662
663     /**
664      * Rename a specific contact group
665      *
666      * @param string Group identifier
667      * @param string New name to set for this group
668      * @return boolean New name on success, false if no data was changed
669      */
670     function rename_group($gid, $newname)
671     {
672         // make sure we have a unique name
673         $name = $this->unique_groupname($newname);
25fdec 674
3d6c04 675         $sql_result = $this->db->query(
982e0b 676             "UPDATE ".get_table_name($this->db_groups).
3d6c04 677             " SET name=?, changed=".$this->db->now().
A 678             " WHERE contactgroup_id=?",
679             $name, $gid
680         );
681
682         return $this->db->affected_rows() ? $name : false;
683     }
684
685
686     /**
687      * Add the given contact records the a certain group
688      *
689      * @param string  Group identifier
690      * @param array   List of contact identifiers to be added
691      * @return int    Number of contacts added 
692      */
693     function add_to_group($group_id, $ids)
694     {
695         if (!is_array($ids))
696             $ids = explode(',', $ids);
25fdec 697
3d6c04 698         $added = 0;
1126fc 699         $exists = array();
A 700
701         // get existing assignments ...
702         $sql_result = $this->db->query(
703             "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
704             " WHERE contactgroup_id=?".
705                 " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
706             $group_id
707         );
708         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
709             $exists[] = $sql_arr['contact_id'];
710         }
711         // ... and remove them from the list
712         $ids = array_diff($ids, $exists);
25fdec 713
3d6c04 714         foreach ($ids as $contact_id) {
1126fc 715             $this->db->query(
A 716                 "INSERT INTO ".get_table_name($this->db_groupmembers).
717                 " (contactgroup_id, contact_id, created)".
718                 " VALUES (?, ?, ".$this->db->now().")",
3d6c04 719                 $group_id,
A 720                 $contact_id
721             );
722
1126fc 723             if (!$this->db->db_error)
A 724                 $added++;
3d6c04 725         }
A 726
727         return $added;
728     }
729
730
731     /**
732      * Remove the given contact records from a certain group
733      *
734      * @param string  Group identifier
735      * @param array   List of contact identifiers to be removed
736      * @return int    Number of deleted group members
737      */
738     function remove_from_group($group_id, $ids)
739     {
740         if (!is_array($ids))
741             $ids = explode(',', $ids);
742
a004bb 743         $ids = $this->db->array2list($ids, 'integer');
A 744
3d6c04 745         $sql_result = $this->db->query(
982e0b 746             "DELETE FROM ".get_table_name($this->db_groupmembers).
3d6c04 747             " WHERE contactgroup_id=?".
A 748                 " AND contact_id IN ($ids)",
749             $group_id
750         );
751
752         return $this->db->affected_rows();
753     }
754
755
756     /**
757      * Check for existing groups with the same name
758      *
759      * @param string Name to check
760      * @return string A group name which is unique for the current use
761      */
762     private function unique_groupname($name)
763     {
764         $checkname = $name;
765         $num = 2; $hit = false;
25fdec 766
3d6c04 767         do {
A 768             $sql_result = $this->db->query(
982e0b 769                 "SELECT 1 FROM ".get_table_name($this->db_groups).
3d6c04 770                 " WHERE del<>1".
A 771                     " AND user_id=?".
3e696d 772                     " AND name=?",
3d6c04 773                 $this->user_id,
A 774                 $checkname);
25fdec 775
3d6c04 776             // append number to make name unique
A 777             if ($hit = $this->db->num_rows($sql_result))
778                 $checkname = $name . ' ' . $num++;
779         } while ($hit > 0);
25fdec 780
3d6c04 781         return $checkname;
3b67e3 782     }
T 783
f11541 784 }