till
2011-11-02 8ae0937604c7466b0b97b3ac5610dff034845569
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     /**
dc6c4f 167      * Get group properties such as name and email address(es)
T 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     /**
3d6c04 190      * List the current set of contact records
A 191      *
0501b6 192      * @param  array   List of cols to show, Null means all
3d6c04 193      * @param  int     Only return this number of records, use negative values for tail
A 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)
982e0b 211             $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
3d6c04 212                 " ON (m.contact_id = c.".$this->primary_key.")";
A 213
214         $sql_result = $this->db->limitquery(
982e0b 215             "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
821a56 216             $join .
3d6c04 217             " WHERE c.del<>1" .
566b14 218                 " AND c.user_id=?" .
A 219                 ($this->group_id ? " AND m.contactgroup_id=?" : "").
220                 ($this->filter ? " AND (".$this->filter.")" : "") .
0ec7fe 221             " ORDER BY ". $this->db->concat('c.name', 'c.email'),
3d6c04 222             $start_row,
A 223             $length,
224             $this->user_id,
225             $this->group_id);
226
0501b6 227         // determine whether we have to parse the vcard or if only db cols are requested
T 228         $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
3cacf9 229
3d6c04 230         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
A 231             $sql_arr['ID'] = $sql_arr[$this->primary_key];
0501b6 232
T 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']);
445a4c 237
3d6c04 238             // make sure we have a name to display
445a4c 239             if (empty($sql_arr['name'])) {
T 240                 if (empty($sql_arr['email']))
241                   $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
0501b6 242                 $sql_arr['name'] = $sql_arr['email'][0];
445a4c 243             }
0501b6 244
3d6c04 245             $this->result->add($sql_arr);
A 246         }
25fdec 247
3d6c04 248         $cnt = count($this->result->records);
A 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;
821a56 256             else if (isset($this->cache['count']))
A 257                 $this->result->count = $this->cache['count'];
3d6c04 258             else
A 259                 $this->result->count = $this->_count();
260         }
25fdec 261
3d6c04 262         return $this->result;
A 263     }
264
265
266     /**
267      * Search contacts
268      *
e9a9f2 269      * @param mixed   $fields   The field name of array of field names to search in
A 270      * @param mixed   $value    Search value (or array of values when $fields is array)
271      * @param boolean $strict   True for strict (=), False for partial (LIKE) matching
272      * @param boolean $select   True if results are requested, False if count only
273      * @param boolean $nocount  True to skip the count query (select only)
274      * @param array   $required List of fields that cannot be empty
275      *
0501b6 276      * @return object rcube_result_set Contact records and 'count' value
3d6c04 277      */
25fdec 278     function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
3d6c04 279     {
A 280         if (!is_array($fields))
281             $fields = array($fields);
25fdec 282         if (!is_array($required) && !empty($required))
A 283             $required = array($required);
566b14 284
25fdec 285         $where = $and_where = array();
A 286
e9a9f2 287         foreach ($fields as $idx => $col) {
A 288             // direct ID search
3d6c04 289             if ($col == 'ID' || $col == $this->primary_key) {
25fdec 290                 $ids     = !is_array($value) ? explode(',', $value) : $value;
A 291                 $ids     = $this->db->array2list($ids, 'integer');
292                 $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
e9a9f2 293                 continue;
3d6c04 294             }
e9a9f2 295             // fulltext search in all fields
3e2637 296             else if ($col == '*') {
T 297                 $words = array();
e9a9f2 298                 foreach (explode(" ", self::normalize_string($value)) as $word)
3e2637 299                     $words[] = $this->db->ilike('words', '%'.$word.'%');
T 300                 $where[] = '(' . join(' AND ', $words) . ')';
3cacf9 301             }
e9a9f2 302             else {
A 303                 $val = is_array($value) ? $value[$idx] : $value;
304                 // table column
305                 if (in_array($col, $this->table_cols)) {
306                     if ($strict) {
307                         $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($val);
308                     }
309                     else {
310                         $where[] = $this->db->ilike($col, '%'.$val.'%');
311                     }
312                 }
313                 // vCard field
314                 else {
315                     if (in_array($col, $this->fulltext_cols)) {
316                         foreach (explode(" ", self::normalize_string($val)) as $word)
317                             $words[] = $this->db->ilike('words', '%'.$word.'%');
318                         $where[] = '(' . join(' AND ', $words) . ')';
319                     }
320                     if (is_array($value))
a5be87 321                         $post_search[$col] = mb_strtolower($val);
e9a9f2 322                 }
3cacf9 323             }
3d6c04 324         }
25fdec 325
03eb13 326         foreach (array_intersect($required, $this->table_cols) as $col) {
25fdec 327             $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
A 328         }
329
e9a9f2 330         if (!empty($where)) {
A 331             // use AND operator for advanced searches
332             $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
333         }
25fdec 334
A 335         if (!empty($and_where))
336             $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
e9a9f2 337
A 338         // Post-searching in vCard data fields
339         // we will search in all records and then build a where clause for their IDs
340         if (!empty($post_search)) {
341             $ids = array(0);
342             // build key name regexp
62e225 343             $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
e9a9f2 344             // use initial WHERE clause, to limit records number if possible
A 345             if (!empty($where))
346                 $this->set_search_set($where);
347
348             // count result pages
349             $cnt   = $this->count();
350             $pages = ceil($cnt / $this->page_size);
351             $scnt  = count($post_search);
352
353             // get (paged) result
354             for ($i=0; $i<$pages; $i++) {
355                 $this->list_records(null, $i, true);
356                 while ($row = $this->result->next()) {
357                     $id = $row[$this->primary_key];
5148d3 358                     $found = array();
e9a9f2 359                     foreach (preg_grep($regexp, array_keys($row)) as $col) {
A 360                         $pos     = strpos($col, ':');
361                         $colname = $pos ? substr($col, 0, $pos) : $col;
362                         $search  = $post_search[$colname];
363                         foreach ((array)$row[$col] as $value) {
364                             // composite field, e.g. address
365                             if (is_array($value)) {
366                                 $value = implode($value);
367                             }
a5be87 368                             $value = mb_strtolower($value);
A 369                             if (($strict && $value == $search) || (!$strict && strpos($value, $search) !== false)) {
5148d3 370                                 $found[$colname] = true;
e9a9f2 371                                 break;
A 372                             }
373                         }
374                     }
375                     // all fields match
5148d3 376                     if (count($found) >= $scnt) {
e9a9f2 377                         $ids[] = $id;
A 378                     }
379                 }
380             }
381
382             // build WHERE clause
383             $ids = $this->db->array2list($ids, 'integer');
384             $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
a5be87 385             // reset counter
e9a9f2 386             unset($this->cache['count']);
a5be87 387
A 388             // when we know we have an empty result
389             if ($ids == '0') {
390                 $this->set_search_set($where);
391                 return ($this->result = new rcube_result_set(0, 0));
392             }
e9a9f2 393         }
25fdec 394
A 395         if (!empty($where)) {
396             $this->set_search_set($where);
3d6c04 397             if ($select)
A 398                 $this->list_records(null, 0, $nocount);
399             else
400                 $this->result = $this->count();
401         }
402
e9a9f2 403         return $this->result;
3d6c04 404     }
A 405
406
407     /**
408      * Count number of available contacts in database
409      *
410      * @return rcube_result_set Result object
411      */
412     function count()
413     {
566b14 414         $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
25fdec 415
566b14 416         return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
3d6c04 417     }
A 418
419
420     /**
421      * Count number of available contacts in database
422      *
423      * @return int Contacts count
424      */
425     private function _count()
426     {
427         if ($this->group_id)
982e0b 428             $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
3d6c04 429                 " ON (m.contact_id=c.".$this->primary_key.")";
25fdec 430
3d6c04 431         // count contacts for this user
A 432         $sql_result = $this->db->query(
433             "SELECT COUNT(c.contact_id) AS rows".
982e0b 434             " FROM ".get_table_name($this->db_name)." AS c".
821a56 435                 $join.
A 436             " WHERE c.del<>1".
3d6c04 437             " AND c.user_id=?".
A 438             ($this->group_id ? " AND m.contactgroup_id=?" : "").
439             ($this->filter ? " AND (".$this->filter.")" : ""),
440             $this->user_id,
441             $this->group_id
4307cc 442         );
3d6c04 443
A 444         $sql_arr = $this->db->fetch_assoc($sql_result);
566b14 445
A 446         $this->cache['count'] = (int) $sql_arr['rows'];
447
448         return $this->cache['count'];
f11541 449     }
T 450
451
3d6c04 452     /**
A 453      * Return the last result set
454      *
5c461b 455      * @return mixed Result array or NULL if nothing selected yet
3d6c04 456      */
A 457     function get_result()
f11541 458     {
3d6c04 459         return $this->result;
f11541 460     }
25fdec 461
A 462
3d6c04 463     /**
A 464      * Get a specific contact record
465      *
466      * @param mixed record identifier(s)
5c461b 467      * @return mixed Result object with all record fields or False if not found
3d6c04 468      */
A 469     function get_record($id, $assoc=false)
f11541 470     {
3d6c04 471         // return cached result
A 472         if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
473             return $assoc ? $first : $this->result;
25fdec 474
a61bbb 475         $this->db->query(
982e0b 476             "SELECT * FROM ".get_table_name($this->db_name).
3d6c04 477             " WHERE contact_id=?".
A 478                 " AND user_id=?".
479                 " AND del<>1",
480             $id,
481             $this->user_id
a61bbb 482         );
3d6c04 483
A 484         if ($sql_arr = $this->db->fetch_assoc()) {
0501b6 485             $record = $this->convert_db_data($sql_arr);
3d6c04 486             $this->result = new rcube_result_set(1);
0501b6 487             $this->result->add($record);
3d6c04 488         }
A 489
0501b6 490         return $assoc && $record ? $record : $this->result;
a61bbb 491     }
3d6c04 492
A 493
494     /**
b393e5 495      * Get group assignments of a specific contact record
cb7d32 496      *
T 497      * @param mixed Record identifier
b393e5 498      * @return array List of assigned groups as ID=>Name pairs
cb7d32 499      */
T 500     function get_record_groups($id)
501     {
502       $results = array();
503
504       if (!$this->groups)
505           return $results;
506
507       $sql_result = $this->db->query(
508         "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
509         " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
510         " WHERE cgm.contact_id=?",
511         $id
512       );
513       while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
514         $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
515       }
516
517       return $results;
518     }
519
520
521     /**
07b95d 522      * Check the given data before saving.
T 523      * If input not valid, the message to display can be fetched using get_error()
524      *
525      * @param array Assoziative array with data to save
39cafa 526      * @param boolean Try to fix/complete record automatically
07b95d 527      * @return boolean True if input is valid, False if not.
T 528      */
39cafa 529     public function validate(&$save_data, $autofix = false)
07b95d 530     {
e84818 531         // validate e-mail addresses
39cafa 532         $valid = parent::validate($save_data, $autofix);
07b95d 533
e84818 534         // require at least one e-mail address (syntax check is already done)
07b95d 535         if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
39cafa 536             $this->set_error(self::ERROR_VALIDATE, 'noemailwarning');
07b95d 537             $valid = false;
T 538         }
539
540         return $valid;
541     }
542
543
544     /**
3d6c04 545      * Create a new contact record
A 546      *
b393e5 547      * @param array Associative array with save data
5c461b 548      * @return integer|boolean The created record ID on success, False on error
3d6c04 549      */
A 550     function insert($save_data, $check=false)
551     {
0501b6 552         if (!is_array($save_data))
T 553             return false;
3d6c04 554
A 555         $insert_id = $existing = false;
556
0501b6 557         if ($check) {
T 558             foreach ($save_data as $col => $values) {
559                 if (strpos($col, 'email') === 0) {
560                     foreach ((array)$values as $email) {
715c79 561                         if ($existing = $this->search('email', $email, false, false))
0501b6 562                             break 2;
T 563                     }
564                 }
565             }
566         }
3d6c04 567
0501b6 568         $save_data = $this->convert_save_data($save_data);
3d6c04 569         $a_insert_cols = $a_insert_values = array();
A 570
0501b6 571         foreach ($save_data as $col => $value) {
T 572             $a_insert_cols[]   = $this->db->quoteIdentifier($col);
573             $a_insert_values[] = $this->db->quote($value);
574         }
3d6c04 575
A 576         if (!$existing->count && !empty($a_insert_cols)) {
577             $this->db->query(
982e0b 578                 "INSERT INTO ".get_table_name($this->db_name).
3d6c04 579                 " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
A 580                 " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
581             );
582
982e0b 583             $insert_id = $this->db->insert_id($this->db_name);
3d6c04 584         }
A 585
586         // also add the newly created contact to the active group
587         if ($insert_id && $this->group_id)
588             $this->add_to_group($this->group_id, $insert_id);
589
566b14 590         $this->cache = null;
A 591
3d6c04 592         return $insert_id;
A 593     }
594
595
596     /**
597      * Update a specific contact record
598      *
599      * @param mixed Record identifier
600      * @param array Assoziative array with save data
5c461b 601      * @return boolean True on success, False on error
3d6c04 602      */
A 603     function update($id, $save_cols)
604     {
605         $updated = false;
606         $write_sql = array();
0501b6 607         $record = $this->get_record($id, true);
T 608         $save_cols = $this->convert_save_data($save_cols, $record);
feaf7b 609
0501b6 610         foreach ($save_cols as $col => $value) {
T 611             $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
612         }
3d6c04 613
A 614         if (!empty($write_sql)) {
615             $this->db->query(
982e0b 616                 "UPDATE ".get_table_name($this->db_name).
3d6c04 617                 " SET changed=".$this->db->now().", ".join(', ', $write_sql).
A 618                 " WHERE contact_id=?".
619                     " AND user_id=?".
620                     " AND del<>1",
621                 $id,
622                 $this->user_id
623             );
624
625             $updated = $this->db->affected_rows();
0501b6 626             $this->result = null;  // clear current result (from get_record())
3d6c04 627         }
25fdec 628
3d6c04 629         return $updated;
A 630     }
63fda8 631
A 632
0501b6 633     private function convert_db_data($sql_arr)
T 634     {
635         $record = array();
636         $record['ID'] = $sql_arr[$this->primary_key];
63fda8 637
0501b6 638         if ($sql_arr['vcard']) {
T 639             unset($sql_arr['email']);
640             $vcard = new rcube_vcard($sql_arr['vcard']);
641             $record += $vcard->get_assoc() + $sql_arr;
642         }
643         else {
644             $record += $sql_arr;
645             $record['email'] = preg_split('/,\s*/', $record['email']);
646         }
63fda8 647
0501b6 648         return $record;
T 649     }
650
651
652     private function convert_save_data($save_data, $record = array())
653     {
654         $out = array();
3e2637 655         $words = '';
0501b6 656
T 657         // copy values into vcard object
658         $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
659         $vcard->reset();
660         foreach ($save_data as $key => $values) {
661             list($field, $section) = explode(':', $key);
3e2637 662             $fulltext = in_array($field, $this->fulltext_cols);
0501b6 663             foreach ((array)$values as $value) {
T 664                 if (isset($value))
665                     $vcard->set($field, $value, $section);
3e2637 666                 if ($fulltext && is_array($value))
T 667                     $words .= ' ' . self::normalize_string(join(" ", $value));
668                 else if ($fulltext && strlen($value) >= 3)
669                     $words .= ' ' . self::normalize_string($value);
0501b6 670             }
T 671         }
569f83 672         $out['vcard'] = $vcard->export(false);
0501b6 673
T 674         foreach ($this->table_cols as $col) {
675             $key = $col;
676             if (!isset($save_data[$key]))
677                 $key .= ':home';
678             if (isset($save_data[$key]))
679                 $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
680         }
681
682         // save all e-mails in database column
683         $out['email'] = join(", ", $vcard->email);
684
3e2637 685         // join words for fulltext search
T 686         $out['words'] = join(" ", array_unique(explode(" ", $words)));
687
0501b6 688         return $out;
T 689     }
3d6c04 690
A 691
692     /**
693      * Mark one or more contact records as deleted
694      *
63fda8 695      * @param array   Record identifiers
A 696      * @param boolean Remove record(s) irreversible (unsupported)
3d6c04 697      */
63fda8 698     function delete($ids, $force=true)
3d6c04 699     {
566b14 700         if (!is_array($ids))
A 701             $ids = explode(',', $ids);
3d6c04 702
a004bb 703         $ids = $this->db->array2list($ids, 'integer');
3d6c04 704
63fda8 705         // flag record as deleted (always)
3d6c04 706         $this->db->query(
982e0b 707             "UPDATE ".get_table_name($this->db_name).
3d6c04 708             " SET del=1, changed=".$this->db->now().
A 709             " WHERE user_id=?".
710                 " AND contact_id IN ($ids)",
711             $this->user_id
712         );
713
566b14 714         $this->cache = null;
A 715
3d6c04 716         return $this->db->affected_rows();
A 717     }
718
719
720     /**
7f5a84 721      * Undelete one or more contact records
A 722      *
723      * @param array  Record identifiers
724      */
725     function undelete($ids)
726     {
727         if (!is_array($ids))
728             $ids = explode(',', $ids);
729
730         $ids = $this->db->array2list($ids, 'integer');
731
63fda8 732         // clear deleted flag
7f5a84 733         $this->db->query(
A 734             "UPDATE ".get_table_name($this->db_name).
735             " SET del=0, changed=".$this->db->now().
736             " WHERE user_id=?".
737                 " AND contact_id IN ($ids)",
738             $this->user_id
739         );
740
741         $this->cache = null;
742
743         return $this->db->affected_rows();
744     }
745
746
747     /**
3d6c04 748      * Remove all records from the database
A 749      */
750     function delete_all()
751     {
566b14 752         $this->cache = null;
7f5a84 753
A 754         $this->db->query("UPDATE ".get_table_name($this->db_name).
755             " SET del=1, changed=".$this->db->now().
756             " WHERE user_id = ?", $this->user_id);
757
3d6c04 758         return $this->db->affected_rows();
A 759     }
760
761
762     /**
763      * Create a contact group with the given name
764      *
765      * @param string The group name
5c461b 766      * @return mixed False on error, array with record props in success
3d6c04 767      */
A 768     function create_group($name)
769     {
770         $result = false;
771
772         // make sure we have a unique name
773         $name = $this->unique_groupname($name);
25fdec 774
3d6c04 775         $this->db->query(
982e0b 776             "INSERT INTO ".get_table_name($this->db_groups).
3d6c04 777             " (user_id, changed, name)".
A 778             " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
779         );
25fdec 780
982e0b 781         if ($insert_id = $this->db->insert_id($this->db_groups))
3d6c04 782             $result = array('id' => $insert_id, 'name' => $name);
25fdec 783
3d6c04 784         return $result;
A 785     }
786
787
788     /**
789      * Delete the given group (and all linked group members)
790      *
791      * @param string Group identifier
792      * @return boolean True on success, false if no data was changed
793      */
794     function delete_group($gid)
795     {
796         // flag group record as deleted
797         $sql_result = $this->db->query(
982e0b 798             "UPDATE ".get_table_name($this->db_groups).
3d6c04 799             " SET del=1, changed=".$this->db->now().
dc6c4f 800             " WHERE contactgroup_id=?".
T 801             " AND user_id=?",
802             $gid, $this->user_id
3d6c04 803         );
A 804
566b14 805         $this->cache = null;
A 806
3d6c04 807         return $this->db->affected_rows();
A 808     }
809
810
811     /**
812      * Rename a specific contact group
813      *
814      * @param string Group identifier
815      * @param string New name to set for this group
816      * @return boolean New name on success, false if no data was changed
817      */
818     function rename_group($gid, $newname)
819     {
820         // make sure we have a unique name
821         $name = $this->unique_groupname($newname);
25fdec 822
3d6c04 823         $sql_result = $this->db->query(
982e0b 824             "UPDATE ".get_table_name($this->db_groups).
3d6c04 825             " SET name=?, changed=".$this->db->now().
dc6c4f 826             " WHERE contactgroup_id=?".
T 827             " AND user_id=?",
828             $name, $gid, $this->user_id
3d6c04 829         );
A 830
831         return $this->db->affected_rows() ? $name : false;
832     }
833
834
835     /**
836      * Add the given contact records the a certain group
837      *
838      * @param string  Group identifier
839      * @param array   List of contact identifiers to be added
840      * @return int    Number of contacts added 
841      */
842     function add_to_group($group_id, $ids)
843     {
844         if (!is_array($ids))
845             $ids = explode(',', $ids);
25fdec 846
3d6c04 847         $added = 0;
1126fc 848         $exists = array();
A 849
850         // get existing assignments ...
851         $sql_result = $this->db->query(
852             "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
853             " WHERE contactgroup_id=?".
854                 " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
855             $group_id
856         );
857         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
858             $exists[] = $sql_arr['contact_id'];
859         }
860         // ... and remove them from the list
861         $ids = array_diff($ids, $exists);
25fdec 862
3d6c04 863         foreach ($ids as $contact_id) {
1126fc 864             $this->db->query(
A 865                 "INSERT INTO ".get_table_name($this->db_groupmembers).
866                 " (contactgroup_id, contact_id, created)".
867                 " VALUES (?, ?, ".$this->db->now().")",
3d6c04 868                 $group_id,
A 869                 $contact_id
870             );
871
1126fc 872             if (!$this->db->db_error)
A 873                 $added++;
3d6c04 874         }
A 875
876         return $added;
877     }
878
879
880     /**
881      * Remove the given contact records from a certain group
882      *
883      * @param string  Group identifier
884      * @param array   List of contact identifiers to be removed
885      * @return int    Number of deleted group members
886      */
887     function remove_from_group($group_id, $ids)
888     {
889         if (!is_array($ids))
890             $ids = explode(',', $ids);
891
a004bb 892         $ids = $this->db->array2list($ids, 'integer');
A 893
3d6c04 894         $sql_result = $this->db->query(
982e0b 895             "DELETE FROM ".get_table_name($this->db_groupmembers).
3d6c04 896             " WHERE contactgroup_id=?".
A 897                 " AND contact_id IN ($ids)",
898             $group_id
899         );
900
901         return $this->db->affected_rows();
902     }
903
904
905     /**
906      * Check for existing groups with the same name
907      *
908      * @param string Name to check
909      * @return string A group name which is unique for the current use
910      */
911     private function unique_groupname($name)
912     {
913         $checkname = $name;
914         $num = 2; $hit = false;
25fdec 915
3d6c04 916         do {
A 917             $sql_result = $this->db->query(
982e0b 918                 "SELECT 1 FROM ".get_table_name($this->db_groups).
3d6c04 919                 " WHERE del<>1".
A 920                     " AND user_id=?".
3e696d 921                     " AND name=?",
3d6c04 922                 $this->user_id,
A 923                 $checkname);
25fdec 924
3d6c04 925             // append number to make name unique
A 926             if ($hit = $this->db->num_rows($sql_result))
927                 $checkname = $name . ' ' . $num++;
928         } while ($hit > 0);
25fdec 929
3d6c04 930         return $checkname;
3b67e3 931     }
T 932
f11541 933 }