source: github/program/include/rcube_contacts.php @ 1097a3c

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