Aleksander Machniak
2016-04-02 6f2c007d1be866e47bf6a9f8e6900fe6ec2a6901
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      *
5c461b 545      * @return mixed Result object with all record fields or False if not found
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
A 563         if ($sql_arr = $this->db->fetch_assoc()) {
0501b6 564             $record = $this->convert_db_data($sql_arr);
3d6c04 565             $this->result = new rcube_result_set(1);
0501b6 566             $this->result->add($record);
3d6c04 567         }
A 568
0501b6 569         return $assoc && $record ? $record : $this->result;
a61bbb 570     }
3d6c04 571
A 572     /**
b393e5 573      * Get group assignments of a specific contact record
cb7d32 574      *
a95874 575      * @param mixed $id Record identifier
AM 576      *
b393e5 577      * @return array List of assigned groups as ID=>Name pairs
cb7d32 578      */
T 579     function get_record_groups($id)
580     {
a95874 581         $results = array();
cb7d32 582
a95874 583         if (!$this->groups) {
AM 584             return $results;
585         }
cb7d32 586
a95874 587         $sql_result = $this->db->query(
AM 588             "SELECT cgm.`contactgroup_id`, cg.`name` "
589             . " FROM " . $this->db->table_name($this->db_groupmembers, true) . " AS cgm"
590             . " LEFT JOIN " . $this->db->table_name($this->db_groups, true) . " AS cg"
591                 . " ON (cgm.`contactgroup_id` = cg.`contactgroup_id` AND cg.`del` <> 1)"
592             . " WHERE cgm.`contact_id` = ?",
593             $id
594         );
cb7d32 595
a95874 596         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
AM 597             $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
598         }
599
600         return $results;
cb7d32 601     }
T 602
603     /**
07b95d 604      * Check the given data before saving.
T 605      * If input not valid, the message to display can be fetched using get_error()
606      *
a95874 607      * @param array   $save_data Associative array with data to save
AM 608      * @param boolean $autofix   Try to fix/complete record automatically
609      *
07b95d 610      * @return boolean True if input is valid, False if not.
T 611      */
39cafa 612     public function validate(&$save_data, $autofix = false)
07b95d 613     {
e84818 614         // validate e-mail addresses
39cafa 615         $valid = parent::validate($save_data, $autofix);
07b95d 616
a69363 617         // require at least one email address or a name
TB 618         if ($valid && !strlen($save_data['firstname'].$save_data['surname'].$save_data['name']) && !array_filter($this->get_col_values('email', $save_data, true))) {
39cafa 619             $this->set_error(self::ERROR_VALIDATE, 'noemailwarning');
07b95d 620             $valid = false;
T 621         }
622
623         return $valid;
624     }
625
626     /**
3d6c04 627      * Create a new contact record
A 628      *
a95874 629      * @param array $save_data Associative array with save data
AM 630      * @param bool  $check     Enables validity checks
631      *
5c461b 632      * @return integer|boolean The created record ID on success, False on error
3d6c04 633      */
a95874 634     function insert($save_data, $check = false)
3d6c04 635     {
a95874 636         if (!is_array($save_data)) {
0501b6 637             return false;
a95874 638         }
3d6c04 639
A 640         $insert_id = $existing = false;
641
0501b6 642         if ($check) {
T 643             foreach ($save_data as $col => $values) {
644                 if (strpos($col, 'email') === 0) {
645                     foreach ((array)$values as $email) {
715c79 646                         if ($existing = $this->search('email', $email, false, false))
0501b6 647                             break 2;
T 648                     }
649                 }
650             }
651         }
3d6c04 652
029f7a 653         $save_data     = $this->convert_save_data($save_data);
3d6c04 654         $a_insert_cols = $a_insert_values = array();
A 655
0501b6 656         foreach ($save_data as $col => $value) {
51fe04 657             $a_insert_cols[]   = $this->db->quote_identifier($col);
0501b6 658             $a_insert_values[] = $this->db->quote($value);
T 659         }
3d6c04 660
A 661         if (!$existing->count && !empty($a_insert_cols)) {
662             $this->db->query(
34a090 663                 "INSERT INTO " . $this->db->table_name($this->db_name, true).
AM 664                 " (`user_id`, `changed`, `del`, ".join(', ', $a_insert_cols).")".
3d6c04 665                 " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
A 666             );
667
982e0b 668             $insert_id = $this->db->insert_id($this->db_name);
3d6c04 669         }
A 670
566b14 671         $this->cache = null;
A 672
3d6c04 673         return $insert_id;
A 674     }
675
676     /**
677      * Update a specific contact record
678      *
a95874 679      * @param mixed $id        Record identifier
AM 680      * @param array $save_cols Associative array with save data
029f7a 681      *
5c461b 682      * @return boolean True on success, False on error
3d6c04 683      */
A 684     function update($id, $save_cols)
685     {
029f7a 686         $updated   = false;
3d6c04 687         $write_sql = array();
029f7a 688         $record    = $this->get_record($id, true);
0501b6 689         $save_cols = $this->convert_save_data($save_cols, $record);
feaf7b 690
0501b6 691         foreach ($save_cols as $col => $value) {
51fe04 692             $write_sql[] = sprintf("%s=%s", $this->db->quote_identifier($col), $this->db->quote($value));
0501b6 693         }
3d6c04 694
A 695         if (!empty($write_sql)) {
696             $this->db->query(
34a090 697                 "UPDATE " . $this->db->table_name($this->db_name, true).
AM 698                 " SET `changed` = ".$this->db->now().", ".join(', ', $write_sql).
699                 " WHERE `contact_id` = ?".
700                     " AND `user_id` = ?".
701                     " AND `del` <> 1",
3d6c04 702                 $id,
A 703                 $this->user_id
704             );
705
706             $updated = $this->db->affected_rows();
0501b6 707             $this->result = null;  // clear current result (from get_record())
3d6c04 708         }
25fdec 709
6f2c00 710         return !empty($updated);
3d6c04 711     }
63fda8 712
a95874 713     /**
AM 714      * Convert data stored in the database into output format
715      */
0501b6 716     private function convert_db_data($sql_arr)
T 717     {
718         $record = array();
719         $record['ID'] = $sql_arr[$this->primary_key];
63fda8 720
0501b6 721         if ($sql_arr['vcard']) {
T 722             unset($sql_arr['email']);
a92beb 723             $vcard = new rcube_vcard($sql_arr['vcard'], RCUBE_CHARSET, false, $this->vcard_fieldmap);
0501b6 724             $record += $vcard->get_assoc() + $sql_arr;
T 725         }
726         else {
727             $record += $sql_arr;
e2c9ab 728             $record['email'] = explode(self::SEPARATOR, $record['email']);
A 729             $record['email'] = array_map('trim', $record['email']);
0501b6 730         }
63fda8 731
0501b6 732         return $record;
T 733     }
734
a95874 735     /**
AM 736      * Convert input data for storing in the database
737      */
0501b6 738     private function convert_save_data($save_data, $record = array())
T 739     {
740         $out = array();
3e2637 741         $words = '';
0501b6 742
T 743         // copy values into vcard object
7e3298 744         $vcard = new rcube_vcard($record['vcard'] ?: $save_data['vcard'], RCUBE_CHARSET, false, $this->vcard_fieldmap);
0501b6 745         $vcard->reset();
bd8252 746
AM 747         // don't store groups in vCard (#1490277)
748         $vcard->set('groups', null);
749         unset($save_data['groups']);
750
0501b6 751         foreach ($save_data as $key => $values) {
T 752             list($field, $section) = explode(':', $key);
3e2637 753             $fulltext = in_array($field, $this->fulltext_cols);
52830e 754             // avoid casting DateTime objects to array
TB 755             if (is_object($values) && is_a($values, 'DateTime')) {
756                 $values = array(0 => $values);
757             }
0501b6 758             foreach ((array)$values as $value) {
T 759                 if (isset($value))
760                     $vcard->set($field, $value, $section);
3e2637 761                 if ($fulltext && is_array($value))
ceb5b5 762                     $words .= ' ' . rcube_utils::normalize_string(join(" ", $value));
3e2637 763                 else if ($fulltext && strlen($value) >= 3)
ceb5b5 764                     $words .= ' ' . rcube_utils::normalize_string($value);
0501b6 765             }
T 766         }
569f83 767         $out['vcard'] = $vcard->export(false);
0501b6 768
T 769         foreach ($this->table_cols as $col) {
770             $key = $col;
771             if (!isset($save_data[$key]))
772                 $key .= ':home';
e2c9ab 773             if (isset($save_data[$key])) {
A 774                 if (is_array($save_data[$key]))
775                     $out[$col] = join(self::SEPARATOR, $save_data[$key]);
776                 else
777                     $out[$col] = $save_data[$key];
778             }
0501b6 779         }
T 780
781         // save all e-mails in database column
e2c9ab 782         $out['email'] = join(self::SEPARATOR, $vcard->email);
0501b6 783
3e2637 784         // join words for fulltext search
T 785         $out['words'] = join(" ", array_unique(explode(" ", $words)));
786
0501b6 787         return $out;
T 788     }
3d6c04 789
A 790     /**
791      * Mark one or more contact records as deleted
792      *
a95874 793      * @param array   $ids   Record identifiers
AM 794      * @param boolean $force Remove record(s) irreversible (unsupported)
3d6c04 795      */
a95874 796     function delete($ids, $force = true)
3d6c04 797     {
a95874 798         if (!is_array($ids)) {
e2c9ab 799             $ids = explode(self::SEPARATOR, $ids);
a95874 800         }
3d6c04 801
a004bb 802         $ids = $this->db->array2list($ids, 'integer');
3d6c04 803
63fda8 804         // flag record as deleted (always)
3d6c04 805         $this->db->query(
34a090 806             "UPDATE " . $this->db->table_name($this->db_name, true).
AM 807             " SET `del` = 1, `changed` = ".$this->db->now().
808             " WHERE `user_id` = ?".
809                 " AND `contact_id` IN ($ids)",
3d6c04 810             $this->user_id
A 811         );
812
566b14 813         $this->cache = null;
A 814
3d6c04 815         return $this->db->affected_rows();
A 816     }
817
818     /**
7f5a84 819      * Undelete one or more contact records
A 820      *
a95874 821      * @param array $ids Record identifiers
7f5a84 822      */
A 823     function undelete($ids)
824     {
a95874 825         if (!is_array($ids)) {
e2c9ab 826             $ids = explode(self::SEPARATOR, $ids);
a95874 827         }
7f5a84 828
A 829         $ids = $this->db->array2list($ids, 'integer');
830
63fda8 831         // clear deleted flag
7f5a84 832         $this->db->query(
34a090 833             "UPDATE " . $this->db->table_name($this->db_name, true).
AM 834             " SET `del` = 0, `changed` = ".$this->db->now().
835             " WHERE `user_id` = ?".
836                 " AND `contact_id` IN ($ids)",
7f5a84 837             $this->user_id
A 838         );
839
840         $this->cache = null;
841
842         return $this->db->affected_rows();
843     }
844
845     /**
3d6c04 846      * Remove all records from the database
18b40c 847      *
AM 848      * @param bool $with_groups Remove also groups
849      *
850      * @return int Number of removed records
3d6c04 851      */
18b40c 852     function delete_all($with_groups = false)
3d6c04 853     {
566b14 854         $this->cache = null;
7f5a84 855
34a090 856         $now = $this->db->now();
AM 857
858         $this->db->query("UPDATE " . $this->db->table_name($this->db_name, true)
859             . " SET `del` = 1, `changed` = $now"
860             . " WHERE `user_id` = ?", $this->user_id);
7f5a84 861
18b40c 862         $count = $this->db->affected_rows();
AM 863
864         if ($with_groups) {
34a090 865             $this->db->query("UPDATE " . $this->db->table_name($this->db_groups, true)
AM 866                 . " SET `del` = 1, `changed` = $now"
867                 . " WHERE `user_id` = ?", $this->user_id);
18b40c 868
AM 869             $count += $this->db->affected_rows();
870         }
871
872         return $count;
3d6c04 873     }
A 874
875     /**
876      * Create a contact group with the given name
877      *
a95874 878      * @param string $name The group name
AM 879      *
5c461b 880      * @return mixed False on error, array with record props in success
3d6c04 881      */
A 882     function create_group($name)
883     {
884         $result = false;
885
886         // make sure we have a unique name
887         $name = $this->unique_groupname($name);
25fdec 888
3d6c04 889         $this->db->query(
34a090 890             "INSERT INTO " . $this->db->table_name($this->db_groups, true).
AM 891             " (`user_id`, `changed`, `name`)".
3d6c04 892             " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
A 893         );
25fdec 894
34a090 895         if ($insert_id = $this->db->insert_id($this->db_groups)) {
3d6c04 896             $result = array('id' => $insert_id, 'name' => $name);
34a090 897         }
25fdec 898
3d6c04 899         return $result;
A 900     }
901
902     /**
903      * Delete the given group (and all linked group members)
904      *
a95874 905      * @param string $gid Group identifier
AM 906      *
3d6c04 907      * @return boolean True on success, false if no data was changed
A 908      */
909     function delete_group($gid)
910     {
911         // flag group record as deleted
18b40c 912         $this->db->query(
34a090 913             "UPDATE " . $this->db->table_name($this->db_groups, true)
AM 914             . " SET `del` = 1, `changed` = " . $this->db->now()
915             . " WHERE `contactgroup_id` = ?"
916                 . " AND `user_id` = ?",
dc6c4f 917             $gid, $this->user_id
3d6c04 918         );
A 919
566b14 920         $this->cache = null;
A 921
3d6c04 922         return $this->db->affected_rows();
A 923     }
924
925     /**
926      * Rename a specific contact group
927      *
a95874 928      * @param string $gid     Group identifier
AM 929      * @param string $name    New name to set for this group
930      * @param string $new_gid (not used)
931      *
3d6c04 932      * @return boolean New name on success, false if no data was changed
A 933      */
a95874 934     function rename_group($gid, $name, &$new_gid)
3d6c04 935     {
A 936         // make sure we have a unique name
a95874 937         $name = $this->unique_groupname($name);
25fdec 938
3d6c04 939         $sql_result = $this->db->query(
34a090 940             "UPDATE " . $this->db->table_name($this->db_groups, true).
AM 941             " SET `name` = ?, `changed` = ".$this->db->now().
942             " WHERE `contactgroup_id` = ?".
943                 " AND `user_id` = ?",
dc6c4f 944             $name, $gid, $this->user_id
3d6c04 945         );
A 946
9e4246 947         return $this->db->affected_rows($sql_result) ? $name : false;
3d6c04 948     }
A 949
950     /**
951      * Add the given contact records the a certain group
952      *
40d419 953      * @param string       Group identifier
AM 954      * @param array|string List of contact identifiers to be added
955      *
956      * @return int Number of contacts added
3d6c04 957      */
A 958     function add_to_group($group_id, $ids)
959     {
a95874 960         if (!is_array($ids)) {
e2c9ab 961             $ids = explode(self::SEPARATOR, $ids);
a95874 962         }
25fdec 963
a95874 964         $added  = 0;
1126fc 965         $exists = array();
A 966
967         // get existing assignments ...
968         $sql_result = $this->db->query(
34a090 969             "SELECT `contact_id` FROM " . $this->db->table_name($this->db_groupmembers, true).
AM 970             " WHERE `contactgroup_id` = ?".
971                 " AND `contact_id` IN (".$this->db->array2list($ids, 'integer').")",
1126fc 972             $group_id
A 973         );
a95874 974
1126fc 975         while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
A 976             $exists[] = $sql_arr['contact_id'];
977         }
a95874 978
1126fc 979         // ... and remove them from the list
A 980         $ids = array_diff($ids, $exists);
25fdec 981
3d6c04 982         foreach ($ids as $contact_id) {
1126fc 983             $this->db->query(
34a090 984                 "INSERT INTO " . $this->db->table_name($this->db_groupmembers, true).
AM 985                 " (`contactgroup_id`, `contact_id`, `created`)".
1126fc 986                 " VALUES (?, ?, ".$this->db->now().")",
3d6c04 987                 $group_id,
A 988                 $contact_id
989             );
990
a95874 991             if ($error = $this->db->is_error()) {
159691 992                 $this->set_error(self::ERROR_SAVING, $error);
a95874 993             }
AM 994             else {
1126fc 995                 $added++;
a95874 996             }
3d6c04 997         }
A 998
999         return $added;
1000     }
1001
1002     /**
1003      * Remove the given contact records from a certain group
1004      *
40d419 1005      * @param string       Group identifier
AM 1006      * @param array|string List of contact identifiers to be removed
1007      *
1008      * @return int Number of deleted group members
3d6c04 1009      */
A 1010     function remove_from_group($group_id, $ids)
1011     {
1012         if (!is_array($ids))
e2c9ab 1013             $ids = explode(self::SEPARATOR, $ids);
3d6c04 1014
a004bb 1015         $ids = $this->db->array2list($ids, 'integer');
A 1016
3d6c04 1017         $sql_result = $this->db->query(
34a090 1018             "DELETE FROM " . $this->db->table_name($this->db_groupmembers, true).
AM 1019             " WHERE `contactgroup_id` = ?".
1020                 " AND `contact_id` IN ($ids)",
3d6c04 1021             $group_id
A 1022         );
1023
9e4246 1024         return $this->db->affected_rows($sql_result);
3d6c04 1025     }
A 1026
1027     /**
1028      * Check for existing groups with the same name
1029      *
a95874 1030      * @param string $name Name to check
AM 1031      *
3d6c04 1032      * @return string A group name which is unique for the current use
A 1033      */
1034     private function unique_groupname($name)
1035     {
1036         $checkname = $name;
a95874 1037         $num       = 2;
AM 1038         $hit       = false;
25fdec 1039
3d6c04 1040         do {
A 1041             $sql_result = $this->db->query(
34a090 1042                 "SELECT 1 FROM " . $this->db->table_name($this->db_groups, true).
AM 1043                 " WHERE `del` <> 1".
1044                     " AND `user_id` = ?".
1045                     " AND `name` = ?",
3d6c04 1046                 $this->user_id,
A 1047                 $checkname);
25fdec 1048
3d6c04 1049             // append number to make name unique
0d94fd 1050             if ($hit = $this->db->fetch_array($sql_result)) {
3d6c04 1051                 $checkname = $name . ' ' . $num++;
0d94fd 1052             }
a95874 1053         }
AM 1054         while ($hit);
25fdec 1055
3d6c04 1056         return $checkname;
3b67e3 1057     }
f11541 1058 }