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