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