source: github/program/include/rcube_contacts.php @ 2563619

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 2563619 was d17a7fea, checked in by alecpl <alec@…>, 3 years ago
  • remove debug code
  • Property mode set to 100644
File size: 18.4 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_contacts.php                                    |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2006-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     * @param array   List of fields that cannot be empty
219     * @return Indexed list of contact records and 'count' value
220     */
221    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
222    {
223        if (!is_array($fields))
224            $fields = array($fields);
225        if (!is_array($required) && !empty($required))
226            $required = array($required);
227
228        $where = $and_where = array();
229
230        foreach ($fields as $col) {
231            if ($col == 'ID' || $col == $this->primary_key) {
232                $ids     = !is_array($value) ? explode(',', $value) : $value;
233                $ids     = $this->db->array2list($ids, 'integer');
234                $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
235            }
236            else if ($strict)
237                $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($value);
238            else
239                $where[] = $this->db->ilike($col, '%'.$value.'%');
240        }
241
242        foreach ($required as $col) {
243            $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
244        }
245
246        if (!empty($where))
247            $where = join(' OR ', $where);
248
249        if (!empty($and_where))
250            $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
251
252        if (!empty($where)) {
253            $this->set_search_set($where);
254            if ($select)
255                $this->list_records(null, 0, $nocount);
256            else
257                $this->result = $this->count();
258        }
259
260        return $this->result; 
261    }
262
263
264    /**
265     * Count number of available contacts in database
266     *
267     * @return rcube_result_set Result object
268     */
269    function count()
270    {
271        $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
272
273        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
274    }
275
276
277    /**
278     * Count number of available contacts in database
279     *
280     * @return int Contacts count
281     */
282    private function _count()
283    {
284        if ($this->group_id)
285            $join = " LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
286                " ON (m.contact_id=c.".$this->primary_key.")";
287
288        // count contacts for this user
289        $sql_result = $this->db->query(
290            "SELECT COUNT(c.contact_id) AS rows".
291            " FROM ".$this->db_name." AS c".
292                $join.
293            " WHERE c.del<>1".
294            " AND c.user_id=?".
295            ($this->group_id ? " AND m.contactgroup_id=?" : "").
296            ($this->filter ? " AND (".$this->filter.")" : ""),
297            $this->user_id,
298            $this->group_id
299        );
300
301        $sql_arr = $this->db->fetch_assoc($sql_result);
302
303        $this->cache['count'] = (int) $sql_arr['rows'];
304
305        return $this->cache['count'];
306    }
307
308
309    /**
310     * Return the last result set
311     *
312     * @return Result array or NULL if nothing selected yet
313     */
314    function get_result()
315    {
316        return $this->result;
317    }
318
319
320    /**
321     * Get a specific contact record
322     *
323     * @param mixed record identifier(s)
324     * @return Result object with all record fields or False if not found
325     */
326    function get_record($id, $assoc=false)
327    {
328        // return cached result
329        if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
330            return $assoc ? $first : $this->result;
331
332        $this->db->query(
333            "SELECT * FROM ".$this->db_name.
334            " WHERE contact_id=?".
335                " AND user_id=?".
336                " AND del<>1",
337            $id,
338            $this->user_id
339        );
340
341        if ($sql_arr = $this->db->fetch_assoc()) {
342            $sql_arr['ID'] = $sql_arr[$this->primary_key];
343            $this->result = new rcube_result_set(1);
344            $this->result->add($sql_arr);
345        }
346
347        return $assoc && $sql_arr ? $sql_arr : $this->result;
348    }
349
350
351    /**
352     * Create a new contact record
353     *
354     * @param array Assoziative array with save data
355     * @return The created record ID on success, False on error
356     */
357    function insert($save_data, $check=false)
358    {
359        if (is_object($save_data) && is_a($save_data, rcube_result_set))
360            return $this->insert_recset($save_data, $check);
361
362        $insert_id = $existing = false;
363
364        if ($check)
365            $existing = $this->search('email', $save_data['email'], true, false);
366
367        $a_insert_cols = $a_insert_values = array();
368
369        foreach ($this->table_cols as $col)
370            if (isset($save_data[$col])) {
371                $a_insert_cols[]   = $this->db->quoteIdentifier($col);
372                $a_insert_values[] = $this->db->quote($save_data[$col]);
373            }
374
375        if (!$existing->count && !empty($a_insert_cols)) {
376            $this->db->query(
377                "INSERT INTO ".$this->db_name.
378                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
379                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
380            );
381
382            $insert_id = $this->db->insert_id('contacts');
383        }
384
385        // also add the newly created contact to the active group
386        if ($insert_id && $this->group_id)
387            $this->add_to_group($this->group_id, $insert_id);
388
389        $this->cache = null;
390
391        return $insert_id;
392    }
393
394
395    /**
396     * Insert new contacts for each row in set
397     */
398    function insert_recset($result, $check=false)
399    {
400        $ids = array();
401        while ($row = $result->next()) {
402            if ($insert = $this->insert($row, $check))
403                $ids[] = $insert;
404        }
405        return $ids;
406    }
407
408
409    /**
410     * Update a specific contact record
411     *
412     * @param mixed Record identifier
413     * @param array Assoziative array with save data
414     * @return True on success, False on error
415     */
416    function update($id, $save_cols)
417    {
418        $updated = false;
419        $write_sql = array();
420
421        foreach ($this->table_cols as $col)
422            if (isset($save_cols[$col]))
423                $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col),
424                    $this->db->quote($save_cols[$col]));
425
426        if (!empty($write_sql)) {
427            $this->db->query(
428                "UPDATE ".$this->db_name.
429                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
430                " WHERE contact_id=?".
431                    " AND user_id=?".
432                    " AND del<>1",
433                $id,
434                $this->user_id
435            );
436
437            $updated = $this->db->affected_rows();
438        }
439
440        return $updated;
441    }
442
443
444    /**
445     * Mark one or more contact records as deleted
446     *
447     * @param array  Record identifiers
448     */
449    function delete($ids)
450    {
451        if (!is_array($ids))
452            $ids = explode(',', $ids);
453
454        $ids = $this->db->array2list($ids, 'integer');
455
456        // flag record as deleted
457        $this->db->query(
458            "UPDATE ".$this->db_name.
459            " SET del=1, changed=".$this->db->now().
460            " WHERE user_id=?".
461                " AND contact_id IN ($ids)",
462            $this->user_id
463        );
464
465        $this->cache = null;
466
467        return $this->db->affected_rows();
468    }
469
470
471    /**
472     * Remove all records from the database
473     */
474    function delete_all()
475    {
476        $this->db->query("DELETE FROM {$this->db_name} WHERE user_id=?", $this->user_id);
477        $this->cache = null;
478        return $this->db->affected_rows();
479    }
480
481
482    /**
483     * Create a contact group with the given name
484     *
485     * @param string The group name
486     * @return False on error, array with record props in success
487     */
488    function create_group($name)
489    {
490        $result = false;
491
492        // make sure we have a unique name
493        $name = $this->unique_groupname($name);
494
495        $this->db->query(
496            "INSERT INTO ".get_table_name('contactgroups').
497            " (user_id, changed, name)".
498            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
499        );
500
501        if ($insert_id = $this->db->insert_id('contactgroups'))
502            $result = array('id' => $insert_id, 'name' => $name);
503
504        return $result;
505    }
506
507
508    /**
509     * Delete the given group (and all linked group members)
510     *
511     * @param string Group identifier
512     * @return boolean True on success, false if no data was changed
513     */
514    function delete_group($gid)
515    {
516        // flag group record as deleted
517        $sql_result = $this->db->query(
518            "UPDATE ".get_table_name('contactgroups').
519            " SET del=1, changed=".$this->db->now().
520            " WHERE contactgroup_id=?",
521            $gid
522        );
523
524        $this->cache = null;
525
526        return $this->db->affected_rows();
527    }
528
529
530    /**
531     * Rename a specific contact group
532     *
533     * @param string Group identifier
534     * @param string New name to set for this group
535     * @return boolean New name on success, false if no data was changed
536     */
537    function rename_group($gid, $newname)
538    {
539        // make sure we have a unique name
540        $name = $this->unique_groupname($newname);
541
542        $sql_result = $this->db->query(
543            "UPDATE ".get_table_name('contactgroups').
544            " SET name=?, changed=".$this->db->now().
545            " WHERE contactgroup_id=?",
546            $name, $gid
547        );
548
549        return $this->db->affected_rows() ? $name : false;
550    }
551
552
553    /**
554     * Add the given contact records the a certain group
555     *
556     * @param string  Group identifier
557     * @param array   List of contact identifiers to be added
558     * @return int    Number of contacts added
559     */
560    function add_to_group($group_id, $ids)
561    {
562        if (!is_array($ids))
563            $ids = explode(',', $ids);
564
565        $added = 0;
566
567        foreach ($ids as $contact_id) {
568            $sql_result = $this->db->query(
569                "SELECT 1 FROM ".get_table_name('contactgroupmembers').
570                " WHERE contactgroup_id=?".
571                    " AND contact_id=?",
572                $group_id,
573                $contact_id
574            );
575
576            if (!$this->db->num_rows($sql_result)) {
577                $this->db->query(
578                    "INSERT INTO ".get_table_name('contactgroupmembers').
579                    " (contactgroup_id, contact_id, created)".
580                    " VALUES (?, ?, ".$this->db->now().")",
581                    $group_id,
582                    $contact_id
583                );
584
585                if (!$this->db->db_error)
586                    $added++;
587            }
588        }
589
590        return $added;
591    }
592
593
594    /**
595     * Remove the given contact records from a certain group
596     *
597     * @param string  Group identifier
598     * @param array   List of contact identifiers to be removed
599     * @return int    Number of deleted group members
600     */
601    function remove_from_group($group_id, $ids)
602    {
603        if (!is_array($ids))
604            $ids = explode(',', $ids);
605
606        $ids = $this->db->array2list($ids, 'integer');
607
608        $sql_result = $this->db->query(
609            "DELETE FROM ".get_table_name('contactgroupmembers').
610            " WHERE contactgroup_id=?".
611                " AND contact_id IN ($ids)",
612            $group_id
613        );
614
615        return $this->db->affected_rows();
616    }
617
618
619    /**
620     * Check for existing groups with the same name
621     *
622     * @param string Name to check
623     * @return string A group name which is unique for the current use
624     */
625    private function unique_groupname($name)
626    {
627        $checkname = $name;
628        $num = 2; $hit = false;
629
630        do {
631            $sql_result = $this->db->query(
632                "SELECT 1 FROM ".get_table_name('contactgroups').
633                " WHERE del<>1".
634                    " AND user_id=?".
635                    " AND name=?",
636                $this->user_id,
637                $checkname);
638
639            // append number to make name unique
640            if ($hit = $this->db->num_rows($sql_result))
641                $checkname = $name . ' ' . $num++;
642        } while ($hit > 0);
643
644        return $checkname;
645    }
646
647}
Note: See TracBrowser for help on using the repository browser.