source: github/program/include/rcube_contacts.php @ 4d4a2fa

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 4d4a2fa was 4d4a2fa, checked in by alecpl <alec@…>, 22 months ago
  • Added possibility to extend rcube_vcard's fieldmap
  • Skip empty values in vCard export
  • Property mode set to 100644
File size: 28.0 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     * List the current set of contact records
168     *
169     * @param  array   List of cols to show, Null means all
170     * @param  int     Only return this number of records, use negative values for tail
171     * @param  boolean True to skip the count query (select only)
172     * @return array  Indexed list of contact records, each a hash array
173     */
174    function list_records($cols=null, $subset=0, $nocount=false)
175    {
176        if ($nocount || $this->list_page <= 1) {
177            // create dummy result, we don't need a count now
178            $this->result = new rcube_result_set();
179        } else {
180            // count all records
181            $this->result = $this->count();
182        }
183
184        $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
185        $length = $subset != 0 ? abs($subset) : $this->page_size;
186
187        if ($this->group_id)
188            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
189                " ON (m.contact_id = c.".$this->primary_key.")";
190
191        $sql_result = $this->db->limitquery(
192            "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
193            $join .
194            " WHERE c.del<>1" .
195                " AND c.user_id=?" .
196                ($this->group_id ? " AND m.contactgroup_id=?" : "").
197                ($this->filter ? " AND (".$this->filter.")" : "") .
198            " ORDER BY ". $this->db->concat('c.name', 'c.email'),
199            $start_row,
200            $length,
201            $this->user_id,
202            $this->group_id);
203
204        // determine whether we have to parse the vcard or if only db cols are requested
205        $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
206
207        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
208            $sql_arr['ID'] = $sql_arr[$this->primary_key];
209
210            if ($read_vcard)
211                $sql_arr = $this->convert_db_data($sql_arr);
212            else
213                $sql_arr['email'] = preg_split('/,\s*/', $sql_arr['email']);
214
215            // make sure we have a name to display
216            if (empty($sql_arr['name'])) {
217                if (empty($sql_arr['email']))
218                  $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
219                $sql_arr['name'] = $sql_arr['email'][0];
220            }
221
222            $this->result->add($sql_arr);
223        }
224
225        $cnt = count($this->result->records);
226
227        // update counter
228        if ($nocount)
229            $this->result->count = $cnt;
230        else if ($this->list_page <= 1) {
231            if ($cnt < $this->page_size && $subset == 0)
232                $this->result->count = $cnt;
233            else if (isset($this->cache['count']))
234                $this->result->count = $this->cache['count'];
235            else
236                $this->result->count = $this->_count();
237        }
238
239        return $this->result;
240    }
241
242
243    /**
244     * Search contacts
245     *
246     * @param mixed   $fields   The field name of array of field names to search in
247     * @param mixed   $value    Search value (or array of values when $fields is array)
248     * @param boolean $strict   True for strict (=), False for partial (LIKE) matching
249     * @param boolean $select   True if results are requested, False if count only
250     * @param boolean $nocount  True to skip the count query (select only)
251     * @param array   $required List of fields that cannot be empty
252     *
253     * @return object rcube_result_set Contact records and 'count' value
254     */
255    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
256    {
257        if (!is_array($fields))
258            $fields = array($fields);
259        if (!is_array($required) && !empty($required))
260            $required = array($required);
261
262        $where = $and_where = array();
263
264        foreach ($fields as $idx => $col) {
265            // direct ID search
266            if ($col == 'ID' || $col == $this->primary_key) {
267                $ids     = !is_array($value) ? explode(',', $value) : $value;
268                $ids     = $this->db->array2list($ids, 'integer');
269                $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
270                continue;
271            }
272            // fulltext search in all fields
273            else if ($col == '*') {
274                $words = array();
275                foreach (explode(" ", self::normalize_string($value)) as $word)
276                    $words[] = $this->db->ilike('words', '%'.$word.'%');
277                $where[] = '(' . join(' AND ', $words) . ')';
278            }
279            else {
280                $val = is_array($value) ? $value[$idx] : $value;
281                // table column
282                if (in_array($col, $this->table_cols)) {
283                    if ($strict) {
284                        $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($val);
285                    }
286                    else {
287                        $where[] = $this->db->ilike($col, '%'.$val.'%');
288                    }
289                }
290                // vCard field
291                else {
292                    if (in_array($col, $this->fulltext_cols)) {
293                        foreach (explode(" ", self::normalize_string($val)) as $word)
294                            $words[] = $this->db->ilike('words', '%'.$word.'%');
295                        $where[] = '(' . join(' AND ', $words) . ')';
296                    }
297                    if (is_array($value))
298                        $post_search[$col] = mb_strtolower($val);
299                }
300            }
301        }
302
303        foreach (array_intersect($required, $this->table_cols) as $col) {
304            $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
305        }
306
307        if (!empty($where)) {
308            // use AND operator for advanced searches
309            $where = join(is_array($value) ? ' AND ' : ' OR ', $where);
310        }
311
312        if (!empty($and_where))
313            $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
314
315        // Post-searching in vCard data fields
316        // we will search in all records and then build a where clause for their IDs
317        if (!empty($post_search)) {
318            $ids = array(0);
319            // build key name regexp
320            $regexp = '/^(' . implode(array_keys($post_search), '|') . ')(?:.*)$/';
321            // use initial WHERE clause, to limit records number if possible
322            if (!empty($where))
323                $this->set_search_set($where);
324
325            // count result pages
326            $cnt   = $this->count();
327            $pages = ceil($cnt / $this->page_size);
328            $scnt  = count($post_search);
329
330            // get (paged) result
331            for ($i=0; $i<$pages; $i++) {
332                $this->list_records(null, $i, true);
333                while ($row = $this->result->next()) {
334                    $id = $row[$this->primary_key];
335                    $found = array();
336                    foreach (preg_grep($regexp, array_keys($row)) as $col) {
337                        $pos     = strpos($col, ':');
338                        $colname = $pos ? substr($col, 0, $pos) : $col;
339                        $search  = $post_search[$colname];
340                        foreach ((array)$row[$col] as $value) {
341                            // composite field, e.g. address
342                            if (is_array($value)) {
343                                $value = implode($value);
344                            }
345                            $value = mb_strtolower($value);
346                            if (($strict && $value == $search) || (!$strict && strpos($value, $search) !== false)) {
347                                $found[$colname] = true;
348                                break;
349                            }
350                        }
351                    }
352                    // all fields match
353                    if (count($found) >= $scnt) {
354                        $ids[] = $id;
355                    }
356                }
357            }
358
359            // build WHERE clause
360            $ids = $this->db->array2list($ids, 'integer');
361            $where = 'c.' . $this->primary_key.' IN ('.$ids.')';
362            // reset counter
363            unset($this->cache['count']);
364
365            // when we know we have an empty result
366            if ($ids == '0') {
367                $this->set_search_set($where);
368                return ($this->result = new rcube_result_set(0, 0));
369            }
370        }
371
372        if (!empty($where)) {
373            $this->set_search_set($where);
374            if ($select)
375                $this->list_records(null, 0, $nocount);
376            else
377                $this->result = $this->count();
378        }
379
380        return $this->result;
381    }
382
383
384    /**
385     * Count number of available contacts in database
386     *
387     * @return rcube_result_set Result object
388     */
389    function count()
390    {
391        $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
392
393        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
394    }
395
396
397    /**
398     * Count number of available contacts in database
399     *
400     * @return int Contacts count
401     */
402    private function _count()
403    {
404        if ($this->group_id)
405            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
406                " ON (m.contact_id=c.".$this->primary_key.")";
407
408        // count contacts for this user
409        $sql_result = $this->db->query(
410            "SELECT COUNT(c.contact_id) AS rows".
411            " FROM ".get_table_name($this->db_name)." AS c".
412                $join.
413            " WHERE c.del<>1".
414            " AND c.user_id=?".
415            ($this->group_id ? " AND m.contactgroup_id=?" : "").
416            ($this->filter ? " AND (".$this->filter.")" : ""),
417            $this->user_id,
418            $this->group_id
419        );
420
421        $sql_arr = $this->db->fetch_assoc($sql_result);
422
423        $this->cache['count'] = (int) $sql_arr['rows'];
424
425        return $this->cache['count'];
426    }
427
428
429    /**
430     * Return the last result set
431     *
432     * @return mixed Result array or NULL if nothing selected yet
433     */
434    function get_result()
435    {
436        return $this->result;
437    }
438
439
440    /**
441     * Get a specific contact record
442     *
443     * @param mixed record identifier(s)
444     * @return mixed Result object with all record fields or False if not found
445     */
446    function get_record($id, $assoc=false)
447    {
448        // return cached result
449        if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
450            return $assoc ? $first : $this->result;
451
452        $this->db->query(
453            "SELECT * FROM ".get_table_name($this->db_name).
454            " WHERE contact_id=?".
455                " AND user_id=?".
456                " AND del<>1",
457            $id,
458            $this->user_id
459        );
460
461        if ($sql_arr = $this->db->fetch_assoc()) {
462            $record = $this->convert_db_data($sql_arr);
463            $this->result = new rcube_result_set(1);
464            $this->result->add($record);
465        }
466
467        return $assoc && $record ? $record : $this->result;
468    }
469
470
471    /**
472     * Get group assignments of a specific contact record
473     *
474     * @param mixed Record identifier
475     * @return array List of assigned groups as ID=>Name pairs
476     */
477    function get_record_groups($id)
478    {
479      $results = array();
480
481      if (!$this->groups)
482          return $results;
483
484      $sql_result = $this->db->query(
485        "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
486        " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
487        " WHERE cgm.contact_id=?",
488        $id
489      );
490      while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
491        $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
492      }
493
494      return $results;
495    }
496
497
498    /**
499     * Check the given data before saving.
500     * If input not valid, the message to display can be fetched using get_error()
501     *
502     * @param array Assoziative array with data to save
503     * @return boolean True if input is valid, False if not.
504     */
505    public function validate($save_data)
506    {
507        // validate e-mail addresses
508        $valid = parent::validate($save_data);
509
510        // require at least one e-mail address (syntax check is already done)
511        if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
512            $this->set_error('warning', 'noemailwarning');
513            $valid = false;
514        }
515
516        return $valid;
517    }
518
519
520    /**
521     * Create a new contact record
522     *
523     * @param array Associative array with save data
524     * @return integer|boolean The created record ID on success, False on error
525     */
526    function insert($save_data, $check=false)
527    {
528        if (!is_array($save_data))
529            return false;
530
531        $insert_id = $existing = false;
532
533        if ($check) {
534            foreach ($save_data as $col => $values) {
535                if (strpos($col, 'email') === 0) {
536                    foreach ((array)$values as $email) {
537                        if ($existing = $this->search('email', $email, false, false))
538                            break 2;
539                    }
540                }
541            }
542        }
543
544        $save_data = $this->convert_save_data($save_data);
545        $a_insert_cols = $a_insert_values = array();
546
547        foreach ($save_data as $col => $value) {
548            $a_insert_cols[]   = $this->db->quoteIdentifier($col);
549            $a_insert_values[] = $this->db->quote($value);
550        }
551
552        if (!$existing->count && !empty($a_insert_cols)) {
553            $this->db->query(
554                "INSERT INTO ".get_table_name($this->db_name).
555                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
556                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
557            );
558
559            $insert_id = $this->db->insert_id($this->db_name);
560        }
561
562        // also add the newly created contact to the active group
563        if ($insert_id && $this->group_id)
564            $this->add_to_group($this->group_id, $insert_id);
565
566        $this->cache = null;
567
568        return $insert_id;
569    }
570
571
572    /**
573     * Update a specific contact record
574     *
575     * @param mixed Record identifier
576     * @param array Assoziative array with save data
577     * @return boolean True on success, False on error
578     */
579    function update($id, $save_cols)
580    {
581        $updated = false;
582        $write_sql = array();
583        $record = $this->get_record($id, true);
584console($save_cols);
585        $save_cols = $this->convert_save_data($save_cols, $record);
586console($save_cols);
587        foreach ($save_cols as $col => $value) {
588            $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
589        }
590
591        if (!empty($write_sql)) {
592            $this->db->query(
593                "UPDATE ".get_table_name($this->db_name).
594                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
595                " WHERE contact_id=?".
596                    " AND user_id=?".
597                    " AND del<>1",
598                $id,
599                $this->user_id
600            );
601
602            $updated = $this->db->affected_rows();
603            $this->result = null;  // clear current result (from get_record())
604        }
605
606        return $updated;
607    }
608
609
610    private function convert_db_data($sql_arr)
611    {
612        $record = array();
613        $record['ID'] = $sql_arr[$this->primary_key];
614
615        if ($sql_arr['vcard']) {
616            unset($sql_arr['email']);
617            $vcard = new rcube_vcard($sql_arr['vcard']);
618            $record += $vcard->get_assoc() + $sql_arr;
619        }
620        else {
621            $record += $sql_arr;
622            $record['email'] = preg_split('/,\s*/', $record['email']);
623        }
624
625        return $record;
626    }
627
628
629    private function convert_save_data($save_data, $record = array())
630    {
631        $out = array();
632        $words = '';
633
634        // copy values into vcard object
635        $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
636        $vcard->reset();
637        foreach ($save_data as $key => $values) {
638            list($field, $section) = explode(':', $key);
639            $fulltext = in_array($field, $this->fulltext_cols);
640            foreach ((array)$values as $value) {
641                if (isset($value))
642                    $vcard->set($field, $value, $section);
643                if ($fulltext && is_array($value))
644                    $words .= ' ' . self::normalize_string(join(" ", $value));
645                else if ($fulltext && strlen($value) >= 3)
646                    $words .= ' ' . self::normalize_string($value);
647            }
648        }
649        $out['vcard'] = $vcard->export(false);
650
651        foreach ($this->table_cols as $col) {
652            $key = $col;
653            if (!isset($save_data[$key]))
654                $key .= ':home';
655            if (isset($save_data[$key]))
656                $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
657        }
658
659        // save all e-mails in database column
660        $out['email'] = join(", ", $vcard->email);
661
662        // join words for fulltext search
663        $out['words'] = join(" ", array_unique(explode(" ", $words)));
664
665        return $out;
666    }
667
668
669    /**
670     * Mark one or more contact records as deleted
671     *
672     * @param array   Record identifiers
673     * @param boolean Remove record(s) irreversible (unsupported)
674     */
675    function delete($ids, $force=true)
676    {
677        if (!is_array($ids))
678            $ids = explode(',', $ids);
679
680        $ids = $this->db->array2list($ids, 'integer');
681
682        // flag record as deleted (always)
683        $this->db->query(
684            "UPDATE ".get_table_name($this->db_name).
685            " SET del=1, changed=".$this->db->now().
686            " WHERE user_id=?".
687                " AND contact_id IN ($ids)",
688            $this->user_id
689        );
690
691        $this->cache = null;
692
693        return $this->db->affected_rows();
694    }
695
696
697    /**
698     * Undelete one or more contact records
699     *
700     * @param array  Record identifiers
701     */
702    function undelete($ids)
703    {
704        if (!is_array($ids))
705            $ids = explode(',', $ids);
706
707        $ids = $this->db->array2list($ids, 'integer');
708
709        // clear deleted flag
710        $this->db->query(
711            "UPDATE ".get_table_name($this->db_name).
712            " SET del=0, changed=".$this->db->now().
713            " WHERE user_id=?".
714                " AND contact_id IN ($ids)",
715            $this->user_id
716        );
717
718        $this->cache = null;
719
720        return $this->db->affected_rows();
721    }
722
723
724    /**
725     * Remove all records from the database
726     */
727    function delete_all()
728    {
729        $this->cache = null;
730
731        $this->db->query("UPDATE ".get_table_name($this->db_name).
732            " SET del=1, changed=".$this->db->now().
733            " WHERE user_id = ?", $this->user_id);
734
735        return $this->db->affected_rows();
736    }
737
738
739    /**
740     * Create a contact group with the given name
741     *
742     * @param string The group name
743     * @return mixed False on error, array with record props in success
744     */
745    function create_group($name)
746    {
747        $result = false;
748
749        // make sure we have a unique name
750        $name = $this->unique_groupname($name);
751
752        $this->db->query(
753            "INSERT INTO ".get_table_name($this->db_groups).
754            " (user_id, changed, name)".
755            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
756        );
757
758        if ($insert_id = $this->db->insert_id($this->db_groups))
759            $result = array('id' => $insert_id, 'name' => $name);
760
761        return $result;
762    }
763
764
765    /**
766     * Delete the given group (and all linked group members)
767     *
768     * @param string Group identifier
769     * @return boolean True on success, false if no data was changed
770     */
771    function delete_group($gid)
772    {
773        // flag group record as deleted
774        $sql_result = $this->db->query(
775            "UPDATE ".get_table_name($this->db_groups).
776            " SET del=1, changed=".$this->db->now().
777            " WHERE contactgroup_id=?",
778            $gid
779        );
780
781        $this->cache = null;
782
783        return $this->db->affected_rows();
784    }
785
786
787    /**
788     * Rename a specific contact group
789     *
790     * @param string Group identifier
791     * @param string New name to set for this group
792     * @return boolean New name on success, false if no data was changed
793     */
794    function rename_group($gid, $newname)
795    {
796        // make sure we have a unique name
797        $name = $this->unique_groupname($newname);
798
799        $sql_result = $this->db->query(
800            "UPDATE ".get_table_name($this->db_groups).
801            " SET name=?, changed=".$this->db->now().
802            " WHERE contactgroup_id=?",
803            $name, $gid
804        );
805
806        return $this->db->affected_rows() ? $name : false;
807    }
808
809
810    /**
811     * Add the given contact records the a certain group
812     *
813     * @param string  Group identifier
814     * @param array   List of contact identifiers to be added
815     * @return int    Number of contacts added
816     */
817    function add_to_group($group_id, $ids)
818    {
819        if (!is_array($ids))
820            $ids = explode(',', $ids);
821
822        $added = 0;
823        $exists = array();
824
825        // get existing assignments ...
826        $sql_result = $this->db->query(
827            "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
828            " WHERE contactgroup_id=?".
829                " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
830            $group_id
831        );
832        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
833            $exists[] = $sql_arr['contact_id'];
834        }
835        // ... and remove them from the list
836        $ids = array_diff($ids, $exists);
837
838        foreach ($ids as $contact_id) {
839            $this->db->query(
840                "INSERT INTO ".get_table_name($this->db_groupmembers).
841                " (contactgroup_id, contact_id, created)".
842                " VALUES (?, ?, ".$this->db->now().")",
843                $group_id,
844                $contact_id
845            );
846
847            if (!$this->db->db_error)
848                $added++;
849        }
850
851        return $added;
852    }
853
854
855    /**
856     * Remove the given contact records from a certain group
857     *
858     * @param string  Group identifier
859     * @param array   List of contact identifiers to be removed
860     * @return int    Number of deleted group members
861     */
862    function remove_from_group($group_id, $ids)
863    {
864        if (!is_array($ids))
865            $ids = explode(',', $ids);
866
867        $ids = $this->db->array2list($ids, 'integer');
868
869        $sql_result = $this->db->query(
870            "DELETE FROM ".get_table_name($this->db_groupmembers).
871            " WHERE contactgroup_id=?".
872                " AND contact_id IN ($ids)",
873            $group_id
874        );
875
876        return $this->db->affected_rows();
877    }
878
879
880    /**
881     * Check for existing groups with the same name
882     *
883     * @param string Name to check
884     * @return string A group name which is unique for the current use
885     */
886    private function unique_groupname($name)
887    {
888        $checkname = $name;
889        $num = 2; $hit = false;
890
891        do {
892            $sql_result = $this->db->query(
893                "SELECT 1 FROM ".get_table_name($this->db_groups).
894                " WHERE del<>1".
895                    " AND user_id=?".
896                    " AND name=?",
897                $this->user_id,
898                $checkname);
899
900            // append number to make name unique
901            if ($hit = $this->db->num_rows($sql_result))
902                $checkname = $name . ' ' . $num++;
903        } while ($hit > 0);
904
905        return $checkname;
906    }
907
908}
Note: See TracBrowser for help on using the repository browser.