source: github/program/include/rcube_contacts.php @ cc90ed1

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