source: subversion/trunk/roundcubemail/program/include/rcube_contacts.php @ 5871

Last change on this file since 5871 was 5871, checked in by thomasb, 16 months ago

User configurable setting how to display contact names in list

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