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

Last change on this file since 3543 was 3543, checked in by alec, 3 years ago
  • Fix SQL error on contact auto-completion (#1486649)
  • Property svn:keywords set to Id
File size: 18.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-2010, RoundCube Dev. - Switzerland                 |
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    private $db = null;
31    private $db_name = '';
32    private $user_id = 0;
33    private $filter = null;
34    private $result = null;
35    private $search_fields;
36    private $search_string;
37    private $cache;
38    private $table_cols = array('name', 'email', 'firstname', 'surname', 'vcard');
39 
40    /** public properties */
41    var $primary_key = 'contact_id';
42    var $readonly = false;
43    var $groups = true;
44    var $list_page = 1;
45    var $page_size = 10;
46    var $group_id = 0;
47    var $ready = false;
48
49 
50    /**
51     * Object constructor
52     *
53     * @param object  Instance of the rcube_db class
54     * @param integer User-ID
55     */
56    function __construct($dbconn, $user)
57    {
58        $this->db = $dbconn;
59        $this->db_name = get_table_name('contacts');
60        $this->user_id = $user;
61        $this->ready = $this->db && !$this->db->is_error();
62    }
63
64
65    /**
66     * Save a search string for future listings
67     *
68     * @param  string SQL params to use in listing method
69     */
70    function set_search_set($filter)
71    {
72        $this->filter = $filter;
73        $this->cache = null;
74    }
75
76 
77    /**
78     * Getter for saved search properties
79     *
80     * @return mixed Search properties used by this class
81     */
82    function get_search_set()
83    {
84        return $this->filter;
85    }
86
87
88    /**
89     * Setter for the current group
90     * (empty, has to be re-implemented by extending class)
91     */
92    function set_group($gid)
93    {
94        $this->group_id = $gid;
95        $this->cache = null;
96    }
97
98
99    /**
100     * Reset all saved results and search parameters
101     */
102    function reset()
103    {
104        $this->result = null;
105        $this->filter = null;
106        $this->search_fields = null;
107        $this->search_string = null;
108        $this->cache = null;
109    }
110 
111
112    /**
113     * List all active contact groups of this source
114     *
115     * @param string  Search string to match group name
116     * @return array  Indexed list of contact groups, each a hash array
117     */
118    function list_groups($search = null)
119    {
120        $results = array();
121   
122        if (!$this->groups)
123            return $results;
124
125        $sql_filter = $search ? " AND " . $this->db->ilike('name', '%'.$search.'%') : '';
126
127        $sql_result = $this->db->query(
128            "SELECT * FROM ".get_table_name('contactgroups').
129            " WHERE del<>1".
130            " AND user_id=?".
131            $sql_filter.
132            " ORDER BY name",
133            $this->user_id);
134
135        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
136            $sql_arr['ID'] = $sql_arr['contactgroup_id'];
137            $results[]     = $sql_arr;
138        }
139
140        return $results;
141    }
142
143
144    /**
145     * List the current set of contact records
146     *
147     * @param  array   List of cols to show
148     * @param  int     Only return this number of records, use negative values for tail
149     * @param  boolean True to skip the count query (select only)
150     * @return array  Indexed list of contact records, each a hash array
151     */
152    function list_records($cols=null, $subset=0, $nocount=false)
153    {
154        if ($nocount || $this->list_page <= 1) {
155            // create dummy result, we don't need a count now
156            $this->result = new rcube_result_set();
157        } else {
158            // count all records
159            $this->result = $this->count();
160        }
161
162        $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
163        $length = $subset != 0 ? abs($subset) : $this->page_size;
164
165        if ($this->group_id)
166            $join = " LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
167                " ON (m.contact_id = c.".$this->primary_key.")";
168
169        $sql_result = $this->db->limitquery(
170            "SELECT * FROM ".$this->db_name." AS c" .
171            $join .
172            " WHERE c.del<>1" .
173                " AND c.user_id=?" .
174                ($this->group_id ? " AND m.contactgroup_id=?" : "").
175                ($this->filter ? " AND (".$this->filter.")" : "") .
176            " ORDER BY c.name",
177            $start_row,
178            $length,
179            $this->user_id,
180            $this->group_id);
181
182        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
183            $sql_arr['ID'] = $sql_arr[$this->primary_key];
184            // make sure we have a name to display
185            if (empty($sql_arr['name']))
186                $sql_arr['name'] = $sql_arr['email'];
187            $this->result->add($sql_arr);
188        }
189   
190        $cnt = count($this->result->records);
191
192        // update counter
193        if ($nocount)
194            $this->result->count = $cnt;
195        else if ($this->list_page <= 1) {
196            if ($cnt < $this->page_size && $subset == 0)
197                $this->result->count = $cnt;
198            else if (isset($this->cache['count']))
199                $this->result->count = $this->cache['count'];
200            else
201                $this->result->count = $this->_count();
202        }
203   
204        return $this->result;
205    }
206
207
208    /**
209     * Search contacts
210     *
211     * @param array   List of fields to search in
212     * @param string  Search value
213     * @param boolean True for strict (=), False for partial (LIKE) matching
214     * @param boolean True if results are requested, False if count only
215     * @param boolean True to skip the count query (select only)
216     * @return Indexed list of contact records and 'count' value
217     */
218    function search($fields, $value, $strict=false, $select=true, $nocount=false)
219    {
220        if (!is_array($fields))
221            $fields = array($fields);
222
223        $add_where = array();
224        foreach ($fields as $col) {
225            if ($col == 'ID' || $col == $this->primary_key) {
226                $ids         = !is_array($value) ? explode(',', $value) : $value;
227                $ids         = join(',', array_map(array($this->db, 'quote'), $ids));
228                $add_where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
229            }
230            else if ($strict)
231                $add_where[] = $this->db->quoteIdentifier($col).'='.$this->db->quote($value);
232            else
233                $add_where[] = $this->db->ilike($col, '%'.$value.'%');
234        }
235   
236        if (!empty($add_where)) {
237            $this->set_search_set(join(' OR ', $add_where));
238            if ($select)
239                $this->list_records(null, 0, $nocount);
240            else
241                $this->result = $this->count();
242        }
243
244        return $this->result; 
245    }
246
247
248    /**
249     * Count number of available contacts in database
250     *
251     * @return rcube_result_set Result object
252     */
253    function count()
254    {
255        $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
256   
257        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
258    }
259
260
261    /**
262     * Count number of available contacts in database
263     *
264     * @return int Contacts count
265     */
266    private function _count()
267    {
268        if ($this->group_id)
269            $join = " LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
270                " ON (m.contact_id=c.".$this->primary_key.")";
271     
272        // count contacts for this user
273        $sql_result = $this->db->query(
274            "SELECT COUNT(c.contact_id) AS rows".
275            " FROM ".$this->db_name." AS c".
276                $join.
277            " WHERE c.del<>1".
278            " AND c.user_id=?".
279            ($this->group_id ? " AND m.contactgroup_id=?" : "").
280            ($this->filter ? " AND (".$this->filter.")" : ""),
281            $this->user_id,
282            $this->group_id
283        );
284
285        $sql_arr = $this->db->fetch_assoc($sql_result);
286
287        $this->cache['count'] = (int) $sql_arr['rows'];
288
289        return $this->cache['count'];
290    }
291
292
293    /**
294     * Return the last result set
295     *
296     * @return Result array or NULL if nothing selected yet
297     */
298    function get_result()
299    {
300        return $this->result;
301    }
302 
303 
304    /**
305     * Get a specific contact record
306     *
307     * @param mixed record identifier(s)
308     * @return Result object with all record fields or False if not found
309     */
310    function get_record($id, $assoc=false)
311    {
312        // return cached result
313        if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
314            return $assoc ? $first : $this->result;
315     
316        $this->db->query(
317            "SELECT * FROM ".$this->db_name.
318            " WHERE contact_id=?".
319                " AND user_id=?".
320                " AND del<>1",
321            $id,
322            $this->user_id
323        );
324
325        if ($sql_arr = $this->db->fetch_assoc()) {
326            $sql_arr['ID'] = $sql_arr[$this->primary_key];
327            $this->result = new rcube_result_set(1);
328            $this->result->add($sql_arr);
329        }
330
331        return $assoc && $sql_arr ? $sql_arr : $this->result;
332    }
333
334
335    /**
336     * Create a new contact record
337     *
338     * @param array Assoziative array with save data
339     * @return The created record ID on success, False on error
340     */
341    function insert($save_data, $check=false)
342    {
343        if (is_object($save_data) && is_a($save_data, rcube_result_set))
344            return $this->insert_recset($save_data, $check);
345
346        $insert_id = $existing = false;
347
348        if ($check)
349            $existing = $this->search('email', $save_data['email'], true, false);
350
351        $a_insert_cols = $a_insert_values = array();
352
353        foreach ($this->table_cols as $col)
354            if (isset($save_data[$col])) {
355                $a_insert_cols[]   = $this->db->quoteIdentifier($col);
356                $a_insert_values[] = $this->db->quote($save_data[$col]);
357            }
358
359        if (!$existing->count && !empty($a_insert_cols)) {
360            $this->db->query(
361                "INSERT INTO ".$this->db_name.
362                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
363                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
364            );
365
366            $insert_id = $this->db->insert_id('contacts');
367        }
368
369        // also add the newly created contact to the active group
370        if ($insert_id && $this->group_id)
371            $this->add_to_group($this->group_id, $insert_id);
372
373        $this->cache = null;
374
375        return $insert_id;
376    }
377
378
379    /**
380     * Insert new contacts for each row in set
381     */
382    function insert_recset($result, $check=false)
383    {
384        $ids = array();
385        while ($row = $result->next()) {
386            if ($insert = $this->insert($row, $check))
387                $ids[] = $insert;
388        }
389        return $ids;
390    }
391
392
393    /**
394     * Update a specific contact record
395     *
396     * @param mixed Record identifier
397     * @param array Assoziative array with save data
398     * @return True on success, False on error
399     */
400    function update($id, $save_cols)
401    {
402        $updated = false;
403        $write_sql = array();
404
405        foreach ($this->table_cols as $col)
406            if (isset($save_cols[$col]))
407                $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col),
408                    $this->db->quote($save_cols[$col]));
409
410        if (!empty($write_sql)) {
411            $this->db->query(
412                "UPDATE ".$this->db_name.
413                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
414                " WHERE contact_id=?".
415                    " AND user_id=?".
416                    " AND del<>1",
417                $id,
418                $this->user_id
419            );
420
421            $updated = $this->db->affected_rows();
422        }
423   
424        return $updated;
425    }
426
427
428    /**
429     * Mark one or more contact records as deleted
430     *
431     * @param array  Record identifiers
432     */
433    function delete($ids)
434    {
435        if (!is_array($ids))
436            $ids = explode(',', $ids);
437
438        $ids = join(',', array_map(array($this->db, 'quote'), $ids));
439
440        // flag record as deleted
441        $this->db->query(
442            "UPDATE ".$this->db_name.
443            " SET del=1, changed=".$this->db->now().
444            " WHERE user_id=?".
445                " AND contact_id IN ($ids)",
446            $this->user_id
447        );
448
449        $this->cache = null;
450
451        return $this->db->affected_rows();
452    }
453
454
455    /**
456     * Remove all records from the database
457     */
458    function delete_all()
459    {
460        $this->db->query("DELETE FROM {$this->db_name} WHERE user_id=?", $this->user_id);
461        $this->cache = null;
462        return $this->db->affected_rows();
463    }
464
465
466    /**
467     * Create a contact group with the given name
468     *
469     * @param string The group name
470     * @return False on error, array with record props in success
471     */
472    function create_group($name)
473    {
474        $result = false;
475
476        // make sure we have a unique name
477        $name = $this->unique_groupname($name);
478   
479        $this->db->query(
480            "INSERT INTO ".get_table_name('contactgroups').
481            " (user_id, changed, name)".
482            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
483        );
484   
485        if ($insert_id = $this->db->insert_id('contactgroups'))
486            $result = array('id' => $insert_id, 'name' => $name);
487   
488        return $result;
489    }
490
491
492    /**
493     * Delete the given group (and all linked group members)
494     *
495     * @param string Group identifier
496     * @return boolean True on success, false if no data was changed
497     */
498    function delete_group($gid)
499    {
500        // flag group record as deleted
501        $sql_result = $this->db->query(
502            "UPDATE ".get_table_name('contactgroups').
503            " SET del=1, changed=".$this->db->now().
504            " WHERE contactgroup_id=?",
505            $gid
506        );
507
508        $this->cache = null;
509
510        return $this->db->affected_rows();
511    }
512
513
514    /**
515     * Rename a specific contact group
516     *
517     * @param string Group identifier
518     * @param string New name to set for this group
519     * @return boolean New name on success, false if no data was changed
520     */
521    function rename_group($gid, $newname)
522    {
523        // make sure we have a unique name
524        $name = $this->unique_groupname($newname);
525   
526        $sql_result = $this->db->query(
527            "UPDATE ".get_table_name('contactgroups').
528            " SET name=?, changed=".$this->db->now().
529            " WHERE contactgroup_id=?",
530            $name, $gid
531        );
532
533        return $this->db->affected_rows() ? $name : false;
534    }
535
536
537    /**
538     * Add the given contact records the a certain group
539     *
540     * @param string  Group identifier
541     * @param array   List of contact identifiers to be added
542     * @return int    Number of contacts added
543     */
544    function add_to_group($group_id, $ids)
545    {
546        if (!is_array($ids))
547            $ids = explode(',', $ids);
548   
549        $added = 0;
550   
551        foreach ($ids as $contact_id) {
552            $sql_result = $this->db->query(
553                "SELECT 1 FROM ".get_table_name('contactgroupmembers').
554                " WHERE contactgroup_id=?".
555                    " AND contact_id=?",
556                $group_id,
557                $contact_id
558            );
559
560            if (!$this->db->num_rows($sql_result)) {
561                $this->db->query(
562                    "INSERT INTO ".get_table_name('contactgroupmembers').
563                    " (contactgroup_id, contact_id, created)".
564                    " VALUES (?, ?, ".$this->db->now().")",
565                    $group_id,
566                    $contact_id
567                );
568
569                if (!$this->db->db_error)
570                    $added++;
571            }
572        }
573
574        return $added;
575    }
576
577
578    /**
579     * Remove the given contact records from a certain group
580     *
581     * @param string  Group identifier
582     * @param array   List of contact identifiers to be removed
583     * @return int    Number of deleted group members
584     */
585    function remove_from_group($group_id, $ids)
586    {
587        if (!is_array($ids))
588            $ids = explode(',', $ids);
589
590        $ids = join(',', array_map(array($this->db, 'quote'), $ids));
591   
592        $sql_result = $this->db->query(
593            "DELETE FROM ".get_table_name('contactgroupmembers').
594            " WHERE contactgroup_id=?".
595                " AND contact_id IN ($ids)",
596            $group_id
597        );
598
599        return $this->db->affected_rows();
600    }
601
602
603    /**
604     * Check for existing groups with the same name
605     *
606     * @param string Name to check
607     * @return string A group name which is unique for the current use
608     */
609    private function unique_groupname($name)
610    {
611        $checkname = $name;
612        $num = 2; $hit = false;
613   
614        do {
615            $sql_result = $this->db->query(
616                "SELECT 1 FROM ".get_table_name('contactgroups').
617                " WHERE del<>1".
618                    " AND user_id=?".
619                    " AND name=?",
620                $this->user_id,
621                $checkname);
622   
623            // append number to make name unique
624            if ($hit = $this->db->num_rows($sql_result))
625                $checkname = $name . ' ' . $num++;
626        } while ($hit > 0);
627   
628        return $checkname;
629    }
630
631}
Note: See TracBrowser for help on using the repository browser.