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