source: github/program/include/rcube_contacts.php @ 62e2254

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 62e2254 was 62e2254, checked in by alecpl <alec@…>, 2 years ago
  • Fix regexp matching field names
  • Property mode set to 100644
File size: 27.1 KB
Line 
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$
19
20*/
21
22
23/**
24 * Model class for the local address book database
25 *
26 * @package Addressbook
27 */
28class 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 $cache;
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');
49
50    // public properties
51    public $primary_key = 'contact_id';
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');
62
63
64    /**
65     * Object constructor
66     *
67     * @param object  Instance of the rcube_db class
68     * @param integer User-ID
69     */
70    function __construct($dbconn, $user)
71    {
72        $this->db = $dbconn;
73        $this->user_id = $user;
74        $this->ready = $this->db && !$this->db->is_error();
75    }
76
77
78    /**
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)
84    {
85        $this->filter = $filter;
86        $this->cache = null;
87    }
88
89
90    /**
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;
108        $this->cache = null;
109    }
110
111
112    /**
113     * Reset all saved results and search parameters
114     */
115    function reset()
116    {
117        $this->result = null;
118        $this->filter = null;
119        $this->cache = null;
120    }
121
122
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();
132
133        if (!$this->groups)
134            return $results;
135
136        $sql_filter = $search ? " AND " . $this->db->ilike('name', '%'.$search.'%') : '';
137
138        $sql_result = $this->db->query(
139            "SELECT * FROM ".get_table_name($this->db_groups).
140            " WHERE del<>1".
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     *
158     * @param  array   List of cols to show, Null means all
159     * @param  int     Only return this number of records, use negative values for tail
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)
177            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
178                " ON (m.contact_id = c.".$this->primary_key.")";
179
180        $sql_result = $this->db->limitquery(
181            "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
182            $join .
183            " WHERE c.del<>1" .
184                " AND c.user_id=?" .
185                ($this->group_id ? " AND m.contactgroup_id=?" : "").
186                ($this->filter ? " AND (".$this->filter.")" : "") .
187            " ORDER BY ". $this->db->concat('c.name', 'c.email'),
188            $start_row,
189            $length,
190            $this->user_id,
191            $this->group_id);
192
193        // determine whether we have to parse the vcard or if only db cols are requested
194        $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
195
196        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
197            $sql_arr['ID'] = $sql_arr[$this->primary_key];
198
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']);
203
204            // make sure we have a name to display
205            if (empty($sql_arr['name'])) {
206                if (empty($sql_arr['email']))
207                  $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
208                $sql_arr['name'] = $sql_arr['email'][0];
209            }
210
211            $this->result->add($sql_arr);
212        }
213
214        $cnt = count($this->result->records);
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;
222            else if (isset($this->cache['count']))
223                $this->result->count = $this->cache['count'];
224            else
225                $this->result->count = $this->_count();
226        }
227
228        return $this->result;
229    }
230
231
232    /**
233     * Search contacts
234     *
235     * @param mixed   $fields   The field name of array of field names to search in
236     * @param mixed   $value    Search value (or array of values when $fields is array)
237     * @param boolean $strict   True for strict (=), False for partial (LIKE) matching
238     * @param boolean $select   True if results are requested, False if count only
239     * @param boolean $nocount  True to skip the count query (select only)
240     * @param array   $required List of fields that cannot be empty
241     *
242     * @return object rcube_result_set Contact records and 'count' value
243     */
244    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
245    {
246        if (!is_array($fields))
247            $fields = array($fields);
248        if (!is_array($required) && !empty($required))
249            $required = array($required);
250
251        $where = $and_where = array();
252
253        foreach ($fields as $idx => $col) {
254            // direct ID search
255            if ($col == 'ID' || $col == $this->primary_key) {
256                $ids     = !is_array($value) ? explode(',', $value) : $value;
257                $ids     = $this->db->array2list($ids, 'integer');
258                $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
259                continue;
260            }
261            // fulltext search in all fields
262            else if ($col == '*') {
263                $words = array();
264                foreach (explode(" ", self::normalize_string($value)) as $word)
265                    $words[] = $this->db->ilike('words', '%'.$word.'%');
266                $where[] = '(' . join(' AND ', $words) . ')';
267            }
268            else {
269                $val = is_array($value) ? $value[$idx] : $value;
270                // table column
271                if (in_array($col, $this->table_cols)) {
272                    if ($strict) {
273                        $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($val);
274                    }
275                    else {
276                        $where[] = $this->db->ilike($col, '%'.$val.'%');
277                    }
278                }
279                // vCard field
280                else {
281                    if (in_array($col, $this->fulltext_cols)) {
282                        foreach (explode(" ", self::normalize_string($val)) as $word)
283                            $words[] = $this->db->ilike('words', '%'.$word.'%');
284                        $where[] = '(' . join(' AND ', $words) . ')';
285                    }
286                    if (is_array($value))
287                        $post_search[$col] = mb_strtolower($val);
288                }
289            }
290        }
291
292        foreach ($required as $col) {
293            $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
294        }
295
296        if (!empty($where)) {
297            // use AND operator for advanced searches
298            $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
299        }
300
301        if (!empty($and_where))
302            $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
303
304        // Post-searching in vCard data fields
305        // we will search in all records and then build a where clause for their IDs
306        if (!empty($post_search)) {
307            $ids = array(0);
308            // build key name regexp
309            $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
310            // use initial WHERE clause, to limit records number if possible
311            if (!empty($where))
312                $this->set_search_set($where);
313
314            // count result pages
315            $cnt   = $this->count();
316            $pages = ceil($cnt / $this->page_size);
317            $scnt  = count($post_search);
318
319            // get (paged) result
320            for ($i=0; $i<$pages; $i++) {
321                $this->list_records(null, $i, true);
322                while ($row = $this->result->next()) {
323                    $id = $row[$this->primary_key];
324                    $found = array();
325                    foreach (preg_grep($regexp, array_keys($row)) as $col) {
326                        $pos     = strpos($col, ':');
327                        $colname = $pos ? substr($col, 0, $pos) : $col;
328                        $search  = $post_search[$colname];
329                        foreach ((array)$row[$col] as $value) {
330                            // composite field, e.g. address
331                            if (is_array($value)) {
332                                $value = implode($value);
333                            }
334                            $value = mb_strtolower($value);
335                            if (($strict && $value == $search) || (!$strict && strpos($value, $search) !== false)) {
336                                $found[$colname] = true;
337                                break;
338                            }
339                        }
340                    }
341                    // all fields match
342                    if (count($found) >= $scnt) {
343                        $ids[] = $id;
344                    }
345                }
346            }
347
348            // build WHERE clause
349            $ids = $this->db->array2list($ids, 'integer');
350            $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
351            // reset counter
352            unset($this->cache['count']);
353
354            // when we know we have an empty result
355            if ($ids == '0') {
356                $this->set_search_set($where);
357                return ($this->result = new rcube_result_set(0, 0));
358            }
359        }
360
361        if (!empty($where)) {
362            $this->set_search_set($where);
363            if ($select)
364                $this->list_records(null, 0, $nocount);
365            else
366                $this->result = $this->count();
367        }
368
369        return $this->result;
370    }
371
372
373    /**
374     * Count number of available contacts in database
375     *
376     * @return rcube_result_set Result object
377     */
378    function count()
379    {
380        $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
381
382        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
383    }
384
385
386    /**
387     * Count number of available contacts in database
388     *
389     * @return int Contacts count
390     */
391    private function _count()
392    {
393        if ($this->group_id)
394            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
395                " ON (m.contact_id=c.".$this->primary_key.")";
396
397        // count contacts for this user
398        $sql_result = $this->db->query(
399            "SELECT COUNT(c.contact_id) AS rows".
400            " FROM ".get_table_name($this->db_name)." AS c".
401                $join.
402            " WHERE c.del<>1".
403            " AND c.user_id=?".
404            ($this->group_id ? " AND m.contactgroup_id=?" : "").
405            ($this->filter ? " AND (".$this->filter.")" : ""),
406            $this->user_id,
407            $this->group_id
408        );
409
410        $sql_arr = $this->db->fetch_assoc($sql_result);
411
412        $this->cache['count'] = (int) $sql_arr['rows'];
413
414        return $this->cache['count'];
415    }
416
417
418    /**
419     * Return the last result set
420     *
421     * @return mixed Result array or NULL if nothing selected yet
422     */
423    function get_result()
424    {
425        return $this->result;
426    }
427
428
429    /**
430     * Get a specific contact record
431     *
432     * @param mixed record identifier(s)
433     * @return mixed Result object with all record fields or False if not found
434     */
435    function get_record($id, $assoc=false)
436    {
437        // return cached result
438        if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
439            return $assoc ? $first : $this->result;
440
441        $this->db->query(
442            "SELECT * FROM ".get_table_name($this->db_name).
443            " WHERE contact_id=?".
444                " AND user_id=?".
445                " AND del<>1",
446            $id,
447            $this->user_id
448        );
449
450        if ($sql_arr = $this->db->fetch_assoc()) {
451            $record = $this->convert_db_data($sql_arr);
452            $this->result = new rcube_result_set(1);
453            $this->result->add($record);
454        }
455
456        return $assoc && $record ? $record : $this->result;
457    }
458
459
460    /**
461     * Get group assignments of a specific contact record
462     *
463     * @param mixed Record identifier
464     * @return array List of assigned groups as ID=>Name pairs
465     */
466    function get_record_groups($id)
467    {
468      $results = array();
469
470      if (!$this->groups)
471          return $results;
472
473      $sql_result = $this->db->query(
474        "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
475        " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
476        " WHERE cgm.contact_id=?",
477        $id
478      );
479      while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
480        $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
481      }
482
483      return $results;
484    }
485
486
487    /**
488     * Check the given data before saving.
489     * If input not valid, the message to display can be fetched using get_error()
490     *
491     * @param array Assoziative array with data to save
492     * @return boolean True if input is valid, False if not.
493     */
494    public function validate($save_data)
495    {
496        // validate e-mail addresses
497        $valid = parent::validate($save_data);
498
499        // require at least one e-mail address (syntax check is already done)
500        if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
501            $this->set_error('warning', 'noemailwarning');
502            $valid = false;
503        }
504
505        return $valid;
506    }
507
508
509    /**
510     * Create a new contact record
511     *
512     * @param array Associative array with save data
513     * @return integer|boolean The created record ID on success, False on error
514     */
515    function insert($save_data, $check=false)
516    {
517        if (!is_array($save_data))
518            return false;
519
520        $insert_id = $existing = false;
521
522        if ($check) {
523            foreach ($save_data as $col => $values) {
524                if (strpos($col, 'email') === 0) {
525                    foreach ((array)$values as $email) {
526                        if ($existing = $this->search('email', $email, false, false))
527                            break 2;
528                    }
529                }
530            }
531        }
532
533        $save_data = $this->convert_save_data($save_data);
534        $a_insert_cols = $a_insert_values = array();
535
536        foreach ($save_data as $col => $value) {
537            $a_insert_cols[]   = $this->db->quoteIdentifier($col);
538            $a_insert_values[] = $this->db->quote($value);
539        }
540
541        if (!$existing->count && !empty($a_insert_cols)) {
542            $this->db->query(
543                "INSERT INTO ".get_table_name($this->db_name).
544                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
545                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
546            );
547
548            $insert_id = $this->db->insert_id($this->db_name);
549        }
550
551        // also add the newly created contact to the active group
552        if ($insert_id && $this->group_id)
553            $this->add_to_group($this->group_id, $insert_id);
554
555        $this->cache = null;
556
557        return $insert_id;
558    }
559
560
561    /**
562     * Update a specific contact record
563     *
564     * @param mixed Record identifier
565     * @param array Assoziative array with save data
566     * @return boolean True on success, False on error
567     */
568    function update($id, $save_cols)
569    {
570        $updated = false;
571        $write_sql = array();
572        $record = $this->get_record($id, true);
573        $save_cols = $this->convert_save_data($save_cols, $record);
574
575        foreach ($save_cols as $col => $value) {
576            $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
577        }
578
579        if (!empty($write_sql)) {
580            $this->db->query(
581                "UPDATE ".get_table_name($this->db_name).
582                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
583                " WHERE contact_id=?".
584                    " AND user_id=?".
585                    " AND del<>1",
586                $id,
587                $this->user_id
588            );
589
590            $updated = $this->db->affected_rows();
591            $this->result = null;  // clear current result (from get_record())
592        }
593
594        return $updated;
595    }
596   
597   
598    private function convert_db_data($sql_arr)
599    {
600        $record = array();
601        $record['ID'] = $sql_arr[$this->primary_key];
602       
603        if ($sql_arr['vcard']) {
604            unset($sql_arr['email']);
605            $vcard = new rcube_vcard($sql_arr['vcard']);
606            $record += $vcard->get_assoc() + $sql_arr;
607        }
608        else {
609            $record += $sql_arr;
610            $record['email'] = preg_split('/,\s*/', $record['email']);
611        }
612       
613        return $record;
614    }
615
616
617    private function convert_save_data($save_data, $record = array())
618    {
619        $out = array();
620        $words = '';
621
622        // copy values into vcard object
623        $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
624        $vcard->reset();
625        foreach ($save_data as $key => $values) {
626            list($field, $section) = explode(':', $key);
627            $fulltext = in_array($field, $this->fulltext_cols);
628            foreach ((array)$values as $value) {
629                if (isset($value))
630                    $vcard->set($field, $value, $section);
631                if ($fulltext && is_array($value))
632                    $words .= ' ' . self::normalize_string(join(" ", $value));
633                else if ($fulltext && strlen($value) >= 3)
634                    $words .= ' ' . self::normalize_string($value);
635            }
636        }
637        $out['vcard'] = $vcard->export(false);
638
639        foreach ($this->table_cols as $col) {
640            $key = $col;
641            if (!isset($save_data[$key]))
642                $key .= ':home';
643            if (isset($save_data[$key]))
644                $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
645        }
646
647        // save all e-mails in database column
648        $out['email'] = join(", ", $vcard->email);
649
650        // join words for fulltext search
651        $out['words'] = join(" ", array_unique(explode(" ", $words)));
652
653        return $out;
654    }
655
656
657    /**
658     * Mark one or more contact records as deleted
659     *
660     * @param array  Record identifiers
661     */
662    function delete($ids)
663    {
664        if (!is_array($ids))
665            $ids = explode(',', $ids);
666
667        $ids = $this->db->array2list($ids, 'integer');
668
669        // flag record as deleted
670        $this->db->query(
671            "UPDATE ".get_table_name($this->db_name).
672            " SET del=1, changed=".$this->db->now().
673            " WHERE user_id=?".
674                " AND contact_id IN ($ids)",
675            $this->user_id
676        );
677
678        $this->cache = null;
679
680        return $this->db->affected_rows();
681    }
682
683
684    /**
685     * Remove all records from the database
686     */
687    function delete_all()
688    {
689        $this->db->query("DELETE FROM ".get_table_name($this->db_name)." WHERE user_id = ?", $this->user_id);
690        $this->cache = null;
691        return $this->db->affected_rows();
692    }
693
694
695    /**
696     * Create a contact group with the given name
697     *
698     * @param string The group name
699     * @return mixed False on error, array with record props in success
700     */
701    function create_group($name)
702    {
703        $result = false;
704
705        // make sure we have a unique name
706        $name = $this->unique_groupname($name);
707
708        $this->db->query(
709            "INSERT INTO ".get_table_name($this->db_groups).
710            " (user_id, changed, name)".
711            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
712        );
713
714        if ($insert_id = $this->db->insert_id($this->db_groups))
715            $result = array('id' => $insert_id, 'name' => $name);
716
717        return $result;
718    }
719
720
721    /**
722     * Delete the given group (and all linked group members)
723     *
724     * @param string Group identifier
725     * @return boolean True on success, false if no data was changed
726     */
727    function delete_group($gid)
728    {
729        // flag group record as deleted
730        $sql_result = $this->db->query(
731            "UPDATE ".get_table_name($this->db_groups).
732            " SET del=1, changed=".$this->db->now().
733            " WHERE contactgroup_id=?",
734            $gid
735        );
736
737        $this->cache = null;
738
739        return $this->db->affected_rows();
740    }
741
742
743    /**
744     * Rename a specific contact group
745     *
746     * @param string Group identifier
747     * @param string New name to set for this group
748     * @return boolean New name on success, false if no data was changed
749     */
750    function rename_group($gid, $newname)
751    {
752        // make sure we have a unique name
753        $name = $this->unique_groupname($newname);
754
755        $sql_result = $this->db->query(
756            "UPDATE ".get_table_name($this->db_groups).
757            " SET name=?, changed=".$this->db->now().
758            " WHERE contactgroup_id=?",
759            $name, $gid
760        );
761
762        return $this->db->affected_rows() ? $name : false;
763    }
764
765
766    /**
767     * Add the given contact records the a certain group
768     *
769     * @param string  Group identifier
770     * @param array   List of contact identifiers to be added
771     * @return int    Number of contacts added
772     */
773    function add_to_group($group_id, $ids)
774    {
775        if (!is_array($ids))
776            $ids = explode(',', $ids);
777
778        $added = 0;
779        $exists = array();
780
781        // get existing assignments ...
782        $sql_result = $this->db->query(
783            "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
784            " WHERE contactgroup_id=?".
785                " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
786            $group_id
787        );
788        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
789            $exists[] = $sql_arr['contact_id'];
790        }
791        // ... and remove them from the list
792        $ids = array_diff($ids, $exists);
793
794        foreach ($ids as $contact_id) {
795            $this->db->query(
796                "INSERT INTO ".get_table_name($this->db_groupmembers).
797                " (contactgroup_id, contact_id, created)".
798                " VALUES (?, ?, ".$this->db->now().")",
799                $group_id,
800                $contact_id
801            );
802
803            if (!$this->db->db_error)
804                $added++;
805        }
806
807        return $added;
808    }
809
810
811    /**
812     * Remove the given contact records from a certain group
813     *
814     * @param string  Group identifier
815     * @param array   List of contact identifiers to be removed
816     * @return int    Number of deleted group members
817     */
818    function remove_from_group($group_id, $ids)
819    {
820        if (!is_array($ids))
821            $ids = explode(',', $ids);
822
823        $ids = $this->db->array2list($ids, 'integer');
824
825        $sql_result = $this->db->query(
826            "DELETE FROM ".get_table_name($this->db_groupmembers).
827            " WHERE contactgroup_id=?".
828                " AND contact_id IN ($ids)",
829            $group_id
830        );
831
832        return $this->db->affected_rows();
833    }
834
835
836    /**
837     * Check for existing groups with the same name
838     *
839     * @param string Name to check
840     * @return string A group name which is unique for the current use
841     */
842    private function unique_groupname($name)
843    {
844        $checkname = $name;
845        $num = 2; $hit = false;
846
847        do {
848            $sql_result = $this->db->query(
849                "SELECT 1 FROM ".get_table_name($this->db_groups).
850                " WHERE del<>1".
851                    " AND user_id=?".
852                    " AND name=?",
853                $this->user_id,
854                $checkname);
855
856            // append number to make name unique
857            if ($hit = $this->db->num_rows($sql_result))
858                $checkname = $name . ' ' . $num++;
859        } while ($hit > 0);
860
861        return $checkname;
862    }
863
864}
Note: See TracBrowser for help on using the repository browser.