source: subversion/branches/release-0.7/program/include/rcube_contacts.php @ 5351

Last change on this file since 5351 was 5328, checked in by thomasb, 21 months ago

Contact groups can have direct email addresses => distribution lists; enable 'compose' command for the selected group

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