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