source: subversion/trunk/roundcubemail/program/include/rcube_contacts.php @ 4834

Last change on this file since 4834 was 4834, checked in by alec, 2 years ago
  • Added addressbook advanced search
  • Property svn:keywords set to Id
File size: 26.8 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] = $strict ? $val : 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 = 0;
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                            if (($strict && $value == $search)
335                                || (!$strict && strpos(mb_strtolower($value), $search) !== false)
336                            ) {
337                                $found++;
338                                break;
339                            }
340                        }
341                    }
342                    // all fields match
343                    if ($found == $scnt) {
344                        $ids[] = $id;
345                    }
346                }
347            }
348
349            // build WHERE clause
350            $ids = $this->db->array2list($ids, 'integer');
351            $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
352            unset($this->cache['count']);
353        }
354
355        if (!empty($where)) {
356            $this->set_search_set($where);
357            if ($select)
358                $this->list_records(null, 0, $nocount);
359            else
360                $this->result = $this->count();
361        }
362
363        return $this->result;
364    }
365
366
367    /**
368     * Count number of available contacts in database
369     *
370     * @return rcube_result_set Result object
371     */
372    function count()
373    {
374        $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
375
376        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
377    }
378
379
380    /**
381     * Count number of available contacts in database
382     *
383     * @return int Contacts count
384     */
385    private function _count()
386    {
387        if ($this->group_id)
388            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
389                " ON (m.contact_id=c.".$this->primary_key.")";
390
391        // count contacts for this user
392        $sql_result = $this->db->query(
393            "SELECT COUNT(c.contact_id) AS rows".
394            " FROM ".get_table_name($this->db_name)." AS c".
395                $join.
396            " WHERE c.del<>1".
397            " AND c.user_id=?".
398            ($this->group_id ? " AND m.contactgroup_id=?" : "").
399            ($this->filter ? " AND (".$this->filter.")" : ""),
400            $this->user_id,
401            $this->group_id
402        );
403
404        $sql_arr = $this->db->fetch_assoc($sql_result);
405
406        $this->cache['count'] = (int) $sql_arr['rows'];
407
408        return $this->cache['count'];
409    }
410
411
412    /**
413     * Return the last result set
414     *
415     * @return mixed Result array or NULL if nothing selected yet
416     */
417    function get_result()
418    {
419        return $this->result;
420    }
421
422
423    /**
424     * Get a specific contact record
425     *
426     * @param mixed record identifier(s)
427     * @return mixed Result object with all record fields or False if not found
428     */
429    function get_record($id, $assoc=false)
430    {
431        // return cached result
432        if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
433            return $assoc ? $first : $this->result;
434
435        $this->db->query(
436            "SELECT * FROM ".get_table_name($this->db_name).
437            " WHERE contact_id=?".
438                " AND user_id=?".
439                " AND del<>1",
440            $id,
441            $this->user_id
442        );
443
444        if ($sql_arr = $this->db->fetch_assoc()) {
445            $record = $this->convert_db_data($sql_arr);
446            $this->result = new rcube_result_set(1);
447            $this->result->add($record);
448        }
449
450        return $assoc && $record ? $record : $this->result;
451    }
452
453
454    /**
455     * Get group assignments of a specific contact record
456     *
457     * @param mixed Record identifier
458     * @return array List of assigned groups as ID=>Name pairs
459     */
460    function get_record_groups($id)
461    {
462      $results = array();
463
464      if (!$this->groups)
465          return $results;
466
467      $sql_result = $this->db->query(
468        "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
469        " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
470        " WHERE cgm.contact_id=?",
471        $id
472      );
473      while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
474        $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
475      }
476
477      return $results;
478    }
479
480
481    /**
482     * Check the given data before saving.
483     * If input not valid, the message to display can be fetched using get_error()
484     *
485     * @param array Assoziative array with data to save
486     * @return boolean True if input is valid, False if not.
487     */
488    public function validate($save_data)
489    {
490        // validate e-mail addresses
491        $valid = parent::validate($save_data);
492
493        // require at least one e-mail address (syntax check is already done)
494        if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
495            $this->set_error('warning', 'noemailwarning');
496            $valid = false;
497        }
498
499        return $valid;
500    }
501
502
503    /**
504     * Create a new contact record
505     *
506     * @param array Associative array with save data
507     * @return integer|boolean The created record ID on success, False on error
508     */
509    function insert($save_data, $check=false)
510    {
511        if (!is_array($save_data))
512            return false;
513
514        $insert_id = $existing = false;
515
516        if ($check) {
517            foreach ($save_data as $col => $values) {
518                if (strpos($col, 'email') === 0) {
519                    foreach ((array)$values as $email) {
520                        if ($existing = $this->search('email', $email, false, false))
521                            break 2;
522                    }
523                }
524            }
525        }
526
527        $save_data = $this->convert_save_data($save_data);
528        $a_insert_cols = $a_insert_values = array();
529
530        foreach ($save_data as $col => $value) {
531            $a_insert_cols[]   = $this->db->quoteIdentifier($col);
532            $a_insert_values[] = $this->db->quote($value);
533        }
534
535        if (!$existing->count && !empty($a_insert_cols)) {
536            $this->db->query(
537                "INSERT INTO ".get_table_name($this->db_name).
538                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
539                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
540            );
541
542            $insert_id = $this->db->insert_id($this->db_name);
543        }
544
545        // also add the newly created contact to the active group
546        if ($insert_id && $this->group_id)
547            $this->add_to_group($this->group_id, $insert_id);
548
549        $this->cache = null;
550
551        return $insert_id;
552    }
553
554
555    /**
556     * Update a specific contact record
557     *
558     * @param mixed Record identifier
559     * @param array Assoziative array with save data
560     * @return boolean True on success, False on error
561     */
562    function update($id, $save_cols)
563    {
564        $updated = false;
565        $write_sql = array();
566        $record = $this->get_record($id, true);
567        $save_cols = $this->convert_save_data($save_cols, $record);
568
569        foreach ($save_cols as $col => $value) {
570            $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
571        }
572
573        if (!empty($write_sql)) {
574            $this->db->query(
575                "UPDATE ".get_table_name($this->db_name).
576                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
577                " WHERE contact_id=?".
578                    " AND user_id=?".
579                    " AND del<>1",
580                $id,
581                $this->user_id
582            );
583
584            $updated = $this->db->affected_rows();
585            $this->result = null;  // clear current result (from get_record())
586        }
587
588        return $updated;
589    }
590   
591   
592    private function convert_db_data($sql_arr)
593    {
594        $record = array();
595        $record['ID'] = $sql_arr[$this->primary_key];
596       
597        if ($sql_arr['vcard']) {
598            unset($sql_arr['email']);
599            $vcard = new rcube_vcard($sql_arr['vcard']);
600            $record += $vcard->get_assoc() + $sql_arr;
601        }
602        else {
603            $record += $sql_arr;
604            $record['email'] = preg_split('/,\s*/', $record['email']);
605        }
606       
607        return $record;
608    }
609
610
611    private function convert_save_data($save_data, $record = array())
612    {
613        $out = array();
614        $words = '';
615
616        // copy values into vcard object
617        $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
618        $vcard->reset();
619        foreach ($save_data as $key => $values) {
620            list($field, $section) = explode(':', $key);
621            $fulltext = in_array($field, $this->fulltext_cols);
622            foreach ((array)$values as $value) {
623                if (isset($value))
624                    $vcard->set($field, $value, $section);
625                if ($fulltext && is_array($value))
626                    $words .= ' ' . self::normalize_string(join(" ", $value));
627                else if ($fulltext && strlen($value) >= 3)
628                    $words .= ' ' . self::normalize_string($value);
629            }
630        }
631        $out['vcard'] = $vcard->export(false);
632
633        foreach ($this->table_cols as $col) {
634            $key = $col;
635            if (!isset($save_data[$key]))
636                $key .= ':home';
637            if (isset($save_data[$key]))
638                $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
639        }
640
641        // save all e-mails in database column
642        $out['email'] = join(", ", $vcard->email);
643
644        // join words for fulltext search
645        $out['words'] = join(" ", array_unique(explode(" ", $words)));
646
647        return $out;
648    }
649
650
651    /**
652     * Mark one or more contact records as deleted
653     *
654     * @param array  Record identifiers
655     */
656    function delete($ids)
657    {
658        if (!is_array($ids))
659            $ids = explode(',', $ids);
660
661        $ids = $this->db->array2list($ids, 'integer');
662
663        // flag record as deleted
664        $this->db->query(
665            "UPDATE ".get_table_name($this->db_name).
666            " SET del=1, changed=".$this->db->now().
667            " WHERE user_id=?".
668                " AND contact_id IN ($ids)",
669            $this->user_id
670        );
671
672        $this->cache = null;
673
674        return $this->db->affected_rows();
675    }
676
677
678    /**
679     * Remove all records from the database
680     */
681    function delete_all()
682    {
683        $this->db->query("DELETE FROM ".get_table_name($this->db_name)." WHERE user_id = ?", $this->user_id);
684        $this->cache = null;
685        return $this->db->affected_rows();
686    }
687
688
689    /**
690     * Create a contact group with the given name
691     *
692     * @param string The group name
693     * @return mixed False on error, array with record props in success
694     */
695    function create_group($name)
696    {
697        $result = false;
698
699        // make sure we have a unique name
700        $name = $this->unique_groupname($name);
701
702        $this->db->query(
703            "INSERT INTO ".get_table_name($this->db_groups).
704            " (user_id, changed, name)".
705            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
706        );
707
708        if ($insert_id = $this->db->insert_id($this->db_groups))
709            $result = array('id' => $insert_id, 'name' => $name);
710
711        return $result;
712    }
713
714
715    /**
716     * Delete the given group (and all linked group members)
717     *
718     * @param string Group identifier
719     * @return boolean True on success, false if no data was changed
720     */
721    function delete_group($gid)
722    {
723        // flag group record as deleted
724        $sql_result = $this->db->query(
725            "UPDATE ".get_table_name($this->db_groups).
726            " SET del=1, changed=".$this->db->now().
727            " WHERE contactgroup_id=?",
728            $gid
729        );
730
731        $this->cache = null;
732
733        return $this->db->affected_rows();
734    }
735
736
737    /**
738     * Rename a specific contact group
739     *
740     * @param string Group identifier
741     * @param string New name to set for this group
742     * @return boolean New name on success, false if no data was changed
743     */
744    function rename_group($gid, $newname)
745    {
746        // make sure we have a unique name
747        $name = $this->unique_groupname($newname);
748
749        $sql_result = $this->db->query(
750            "UPDATE ".get_table_name($this->db_groups).
751            " SET name=?, changed=".$this->db->now().
752            " WHERE contactgroup_id=?",
753            $name, $gid
754        );
755
756        return $this->db->affected_rows() ? $name : false;
757    }
758
759
760    /**
761     * Add the given contact records the a certain group
762     *
763     * @param string  Group identifier
764     * @param array   List of contact identifiers to be added
765     * @return int    Number of contacts added
766     */
767    function add_to_group($group_id, $ids)
768    {
769        if (!is_array($ids))
770            $ids = explode(',', $ids);
771
772        $added = 0;
773        $exists = array();
774
775        // get existing assignments ...
776        $sql_result = $this->db->query(
777            "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
778            " WHERE contactgroup_id=?".
779                " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
780            $group_id
781        );
782        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
783            $exists[] = $sql_arr['contact_id'];
784        }
785        // ... and remove them from the list
786        $ids = array_diff($ids, $exists);
787
788        foreach ($ids as $contact_id) {
789            $this->db->query(
790                "INSERT INTO ".get_table_name($this->db_groupmembers).
791                " (contactgroup_id, contact_id, created)".
792                " VALUES (?, ?, ".$this->db->now().")",
793                $group_id,
794                $contact_id
795            );
796
797            if (!$this->db->db_error)
798                $added++;
799        }
800
801        return $added;
802    }
803
804
805    /**
806     * Remove the given contact records from a certain group
807     *
808     * @param string  Group identifier
809     * @param array   List of contact identifiers to be removed
810     * @return int    Number of deleted group members
811     */
812    function remove_from_group($group_id, $ids)
813    {
814        if (!is_array($ids))
815            $ids = explode(',', $ids);
816
817        $ids = $this->db->array2list($ids, 'integer');
818
819        $sql_result = $this->db->query(
820            "DELETE FROM ".get_table_name($this->db_groupmembers).
821            " WHERE contactgroup_id=?".
822                " AND contact_id IN ($ids)",
823            $group_id
824        );
825
826        return $this->db->affected_rows();
827    }
828
829
830    /**
831     * Check for existing groups with the same name
832     *
833     * @param string Name to check
834     * @return string A group name which is unique for the current use
835     */
836    private function unique_groupname($name)
837    {
838        $checkname = $name;
839        $num = 2; $hit = false;
840
841        do {
842            $sql_result = $this->db->query(
843                "SELECT 1 FROM ".get_table_name($this->db_groups).
844                " WHERE del<>1".
845                    " AND user_id=?".
846                    " AND name=?",
847                $this->user_id,
848                $checkname);
849
850            // append number to make name unique
851            if ($hit = $this->db->num_rows($sql_result))
852                $checkname = $name . ' ' . $num++;
853        } while ($hit > 0);
854
855        return $checkname;
856    }
857
858}
Note: See TracBrowser for help on using the repository browser.