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