source: github/program/include/rcube_contacts.php @ 3cacf94

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 3cacf94 was 3cacf94, checked in by alecpl <alec@…>, 2 years ago
  • Add popup with basic fields selection for addressbook search
  • Property mode set to 100644
File size: 23.7 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 $cache;
45    private $table_cols = array('name', 'email', 'firstname', 'surname');
46    private $fulltext_cols = array('name', 'firstname', 'surname', 'middlename', 'nickname',
47      'jobtitle', 'organization', 'department', 'maidenname', 'email', 'phone',
48      'address', 'street', 'locality', 'zipcode', 'region', 'country', 'website', 'im', 'notes');
49
50    // public properties
51    public $primary_key = 'contact_id';
52    public $readonly = false;
53    public $groups = true;
54    public $list_page = 1;
55    public $page_size = 10;
56    public $group_id = 0;
57    public $ready = false;
58    public $coltypes = array('name', 'firstname', 'surname', 'middlename', 'prefix', 'suffix', 'nickname',
59      'jobtitle', 'organization', 'department', 'assistant', 'manager',
60      'gender', 'maidenname', 'spouse', 'email', 'phone', 'address',
61      'birthday', 'anniversary', 'website', 'im', 'notes', 'photo');
62
63
64    /**
65     * Object constructor
66     *
67     * @param object  Instance of the rcube_db class
68     * @param integer User-ID
69     */
70    function __construct($dbconn, $user)
71    {
72        $this->db = $dbconn;
73        $this->user_id = $user;
74        $this->ready = $this->db && !$this->db->is_error();
75    }
76
77
78    /**
79     * Save a search string for future listings
80     *
81     * @param  string SQL params to use in listing method
82     */
83    function set_search_set($filter)
84    {
85        $this->filter = $filter;
86        $this->cache = null;
87    }
88
89
90    /**
91     * Getter for saved search properties
92     *
93     * @return mixed Search properties used by this class
94     */
95    function get_search_set()
96    {
97        return $this->filter;
98    }
99
100
101    /**
102     * Setter for the current group
103     * (empty, has to be re-implemented by extending class)
104     */
105    function set_group($gid)
106    {
107        $this->group_id = $gid;
108        $this->cache = null;
109    }
110
111
112    /**
113     * Reset all saved results and search parameters
114     */
115    function reset()
116    {
117        $this->result = null;
118        $this->filter = null;
119        $this->cache = null;
120    }
121
122
123    /**
124     * List all active contact groups of this source
125     *
126     * @param string  Search string to match group name
127     * @return array  Indexed list of contact groups, each a hash array
128     */
129    function list_groups($search = null)
130    {
131        $results = array();
132
133        if (!$this->groups)
134            return $results;
135
136        $sql_filter = $search ? " AND " . $this->db->ilike('name', '%'.$search.'%') : '';
137
138        $sql_result = $this->db->query(
139            "SELECT * FROM ".get_table_name($this->db_groups).
140            " WHERE del<>1".
141            " AND user_id=?".
142            $sql_filter.
143            " ORDER BY name",
144            $this->user_id);
145
146        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
147            $sql_arr['ID'] = $sql_arr['contactgroup_id'];
148            $results[]     = $sql_arr;
149        }
150
151        return $results;
152    }
153
154
155    /**
156     * List the current set of contact records
157     *
158     * @param  array   List of cols to show, Null means all
159     * @param  int     Only return this number of records, use negative values for tail
160     * @param  boolean True to skip the count query (select only)
161     * @return array  Indexed list of contact records, each a hash array
162     */
163    function list_records($cols=null, $subset=0, $nocount=false)
164    {
165        if ($nocount || $this->list_page <= 1) {
166            // create dummy result, we don't need a count now
167            $this->result = new rcube_result_set();
168        } else {
169            // count all records
170            $this->result = $this->count();
171        }
172
173        $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
174        $length = $subset != 0 ? abs($subset) : $this->page_size;
175
176        if ($this->group_id)
177            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
178                " ON (m.contact_id = c.".$this->primary_key.")";
179
180        $sql_result = $this->db->limitquery(
181            "SELECT * FROM ".get_table_name($this->db_name)." AS c" .
182            $join .
183            " WHERE c.del<>1" .
184                " AND c.user_id=?" .
185                ($this->group_id ? " AND m.contactgroup_id=?" : "").
186                ($this->filter ? " AND (".$this->filter.")" : "") .
187            " ORDER BY ". $this->db->concat('c.name', 'c.email'),
188            $start_row,
189            $length,
190            $this->user_id,
191            $this->group_id);
192
193        // determine whether we have to parse the vcard or if only db cols are requested
194        $read_vcard = !$cols || count(array_intersect($cols, $this->table_cols)) < count($cols);
195
196        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
197            $sql_arr['ID'] = $sql_arr[$this->primary_key];
198
199            if ($read_vcard)
200                $sql_arr = $this->convert_db_data($sql_arr);
201            else
202                $sql_arr['email'] = preg_split('/,\s*/', $sql_arr['email']);
203
204            // make sure we have a name to display
205            if (empty($sql_arr['name'])) {
206                if (empty($sql_arr['email']))
207                  $sql_arr['email'] = $this->get_col_values('email', $sql_arr, true);
208                $sql_arr['name'] = $sql_arr['email'][0];
209            }
210
211            $this->result->add($sql_arr);
212        }
213
214        $cnt = count($this->result->records);
215
216        // update counter
217        if ($nocount)
218            $this->result->count = $cnt;
219        else if ($this->list_page <= 1) {
220            if ($cnt < $this->page_size && $subset == 0)
221                $this->result->count = $cnt;
222            else if (isset($this->cache['count']))
223                $this->result->count = $this->cache['count'];
224            else
225                $this->result->count = $this->_count();
226        }
227
228        return $this->result;
229    }
230
231
232    /**
233     * Search contacts
234     *
235     * @param array   List of fields to search in
236     * @param string  Search value
237     * @param boolean True for strict (=), False for partial (LIKE) matching
238     * @param boolean True if results are requested, False if count only
239     * @param boolean True to skip the count query (select only)
240     * @param array   List of fields that cannot be empty
241     * @return object rcube_result_set Contact records and 'count' value
242     */
243    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
244    {
245        if (!is_array($fields))
246            $fields = array($fields);
247        if (!is_array($required) && !empty($required))
248            $required = array($required);
249
250        $where = $and_where = array();
251
252        foreach ($fields as $col) {
253            if ($col == 'ID' || $col == $this->primary_key) {
254                $ids     = !is_array($value) ? explode(',', $value) : $value;
255                $ids     = $this->db->array2list($ids, 'integer');
256                $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
257            }
258            else if ($col == '*') {
259                $words = array();
260                foreach(explode(" ", self::normalize_string($value)) as $word)
261                    $words[] = $this->db->ilike('words', '%'.$word.'%');
262                $where[] = '(' . join(' AND ', $words) . ')';
263            }
264            else if ($strict) {
265                $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($value);
266            }
267            else if (in_array($col, $this->table_cols)) {
268                $where[] = $this->db->ilike($col, '%'.$value.'%');
269            }
270        }
271
272        foreach ($required as $col) {
273            $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
274        }
275
276        if (!empty($where))
277            $where = join(' OR ', $where);
278
279        if (!empty($and_where))
280            $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
281
282        if (!empty($where)) {
283            $this->set_search_set($where);
284            if ($select)
285                $this->list_records(null, 0, $nocount);
286            else
287                $this->result = $this->count();
288        }
289
290        return $this->result; 
291    }
292
293
294    /**
295     * Count number of available contacts in database
296     *
297     * @return rcube_result_set Result object
298     */
299    function count()
300    {
301        $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
302
303        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
304    }
305
306
307    /**
308     * Count number of available contacts in database
309     *
310     * @return int Contacts count
311     */
312    private function _count()
313    {
314        if ($this->group_id)
315            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
316                " ON (m.contact_id=c.".$this->primary_key.")";
317
318        // count contacts for this user
319        $sql_result = $this->db->query(
320            "SELECT COUNT(c.contact_id) AS rows".
321            " FROM ".get_table_name($this->db_name)." AS c".
322                $join.
323            " WHERE c.del<>1".
324            " AND c.user_id=?".
325            ($this->group_id ? " AND m.contactgroup_id=?" : "").
326            ($this->filter ? " AND (".$this->filter.")" : ""),
327            $this->user_id,
328            $this->group_id
329        );
330
331        $sql_arr = $this->db->fetch_assoc($sql_result);
332
333        $this->cache['count'] = (int) $sql_arr['rows'];
334
335        return $this->cache['count'];
336    }
337
338
339    /**
340     * Return the last result set
341     *
342     * @return mixed Result array or NULL if nothing selected yet
343     */
344    function get_result()
345    {
346        return $this->result;
347    }
348
349
350    /**
351     * Get a specific contact record
352     *
353     * @param mixed record identifier(s)
354     * @return mixed Result object with all record fields or False if not found
355     */
356    function get_record($id, $assoc=false)
357    {
358        // return cached result
359        if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
360            return $assoc ? $first : $this->result;
361
362        $this->db->query(
363            "SELECT * FROM ".get_table_name($this->db_name).
364            " WHERE contact_id=?".
365                " AND user_id=?".
366                " AND del<>1",
367            $id,
368            $this->user_id
369        );
370
371        if ($sql_arr = $this->db->fetch_assoc()) {
372            $record = $this->convert_db_data($sql_arr);
373            $this->result = new rcube_result_set(1);
374            $this->result->add($record);
375        }
376
377        return $assoc && $record ? $record : $this->result;
378    }
379
380
381    /**
382     * Get group assignments of a specific contact record
383     *
384     * @param mixed Record identifier
385     * @return array List of assigned groups as ID=>Name pairs
386     */
387    function get_record_groups($id)
388    {
389      $results = array();
390
391      if (!$this->groups)
392          return $results;
393
394      $sql_result = $this->db->query(
395        "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
396        " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
397        " WHERE cgm.contact_id=?",
398        $id
399      );
400      while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
401        $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
402      }
403
404      return $results;
405    }
406
407
408    /**
409     * Check the given data before saving.
410     * If input not valid, the message to display can be fetched using get_error()
411     *
412     * @param array Assoziative array with data to save
413     * @return boolean True if input is valid, False if not.
414     */
415    public function validate($save_data)
416    {
417        // validate e-mail addresses
418        $valid = parent::validate($save_data);
419
420        // require at least one e-mail address (syntax check is already done)
421        if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
422            $this->set_error('warning', 'noemailwarning');
423            $valid = false;
424        }
425
426        return $valid;
427    }
428
429
430    /**
431     * Create a new contact record
432     *
433     * @param array Associative array with save data
434     * @return integer|boolean The created record ID on success, False on error
435     */
436    function insert($save_data, $check=false)
437    {
438        if (!is_array($save_data))
439            return false;
440
441        $insert_id = $existing = false;
442
443        if ($check) {
444            foreach ($save_data as $col => $values) {
445                if (strpos($col, 'email') === 0) {
446                    foreach ((array)$values as $email) {
447                        if ($existing = $this->search('email', $email, false, false))
448                            break 2;
449                    }
450                }
451            }
452        }
453
454        $save_data = $this->convert_save_data($save_data);
455        $a_insert_cols = $a_insert_values = array();
456
457        foreach ($save_data as $col => $value) {
458            $a_insert_cols[]   = $this->db->quoteIdentifier($col);
459            $a_insert_values[] = $this->db->quote($value);
460        }
461
462        if (!$existing->count && !empty($a_insert_cols)) {
463            $this->db->query(
464                "INSERT INTO ".get_table_name($this->db_name).
465                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
466                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
467            );
468
469            $insert_id = $this->db->insert_id($this->db_name);
470        }
471
472        // also add the newly created contact to the active group
473        if ($insert_id && $this->group_id)
474            $this->add_to_group($this->group_id, $insert_id);
475
476        $this->cache = null;
477
478        return $insert_id;
479    }
480
481
482    /**
483     * Update a specific contact record
484     *
485     * @param mixed Record identifier
486     * @param array Assoziative array with save data
487     * @return boolean True on success, False on error
488     */
489    function update($id, $save_cols)
490    {
491        $updated = false;
492        $write_sql = array();
493        $record = $this->get_record($id, true);
494        $save_cols = $this->convert_save_data($save_cols, $record);
495
496        foreach ($save_cols as $col => $value) {
497            $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
498        }
499
500        if (!empty($write_sql)) {
501            $this->db->query(
502                "UPDATE ".get_table_name($this->db_name).
503                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
504                " WHERE contact_id=?".
505                    " AND user_id=?".
506                    " AND del<>1",
507                $id,
508                $this->user_id
509            );
510
511            $updated = $this->db->affected_rows();
512            $this->result = null;  // clear current result (from get_record())
513        }
514
515        return $updated;
516    }
517   
518   
519    private function convert_db_data($sql_arr)
520    {
521        $record = array();
522        $record['ID'] = $sql_arr[$this->primary_key];
523       
524        if ($sql_arr['vcard']) {
525            unset($sql_arr['email']);
526            $vcard = new rcube_vcard($sql_arr['vcard']);
527            $record += $vcard->get_assoc() + $sql_arr;
528        }
529        else {
530            $record += $sql_arr;
531            $record['email'] = preg_split('/,\s*/', $record['email']);
532        }
533       
534        return $record;
535    }
536
537
538    private function convert_save_data($save_data, $record = array())
539    {
540        $out = array();
541        $words = '';
542
543        // copy values into vcard object
544        $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
545        $vcard->reset();
546        foreach ($save_data as $key => $values) {
547            list($field, $section) = explode(':', $key);
548            $fulltext = in_array($field, $this->fulltext_cols);
549            foreach ((array)$values as $value) {
550                if (isset($value))
551                    $vcard->set($field, $value, $section);
552                if ($fulltext && is_array($value))
553                    $words .= ' ' . self::normalize_string(join(" ", $value));
554                else if ($fulltext && strlen($value) >= 3)
555                    $words .= ' ' . self::normalize_string($value);
556            }
557        }
558        $out['vcard'] = $vcard->export(false);
559
560        foreach ($this->table_cols as $col) {
561            $key = $col;
562            if (!isset($save_data[$key]))
563                $key .= ':home';
564            if (isset($save_data[$key]))
565                $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
566        }
567
568        // save all e-mails in database column
569        $out['email'] = join(", ", $vcard->email);
570
571        // join words for fulltext search
572        $out['words'] = join(" ", array_unique(explode(" ", $words)));
573
574        return $out;
575    }
576
577
578    /**
579     * Mark one or more contact records as deleted
580     *
581     * @param array  Record identifiers
582     */
583    function delete($ids)
584    {
585        if (!is_array($ids))
586            $ids = explode(',', $ids);
587
588        $ids = $this->db->array2list($ids, 'integer');
589
590        // flag record as deleted
591        $this->db->query(
592            "UPDATE ".get_table_name($this->db_name).
593            " SET del=1, changed=".$this->db->now().
594            " WHERE user_id=?".
595                " AND contact_id IN ($ids)",
596            $this->user_id
597        );
598
599        $this->cache = null;
600
601        return $this->db->affected_rows();
602    }
603
604
605    /**
606     * Remove all records from the database
607     */
608    function delete_all()
609    {
610        $this->db->query("DELETE FROM ".get_table_name($this->db_name)." WHERE user_id = ?", $this->user_id);
611        $this->cache = null;
612        return $this->db->affected_rows();
613    }
614
615
616    /**
617     * Create a contact group with the given name
618     *
619     * @param string The group name
620     * @return mixed False on error, array with record props in success
621     */
622    function create_group($name)
623    {
624        $result = false;
625
626        // make sure we have a unique name
627        $name = $this->unique_groupname($name);
628
629        $this->db->query(
630            "INSERT INTO ".get_table_name($this->db_groups).
631            " (user_id, changed, name)".
632            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
633        );
634
635        if ($insert_id = $this->db->insert_id($this->db_groups))
636            $result = array('id' => $insert_id, 'name' => $name);
637
638        return $result;
639    }
640
641
642    /**
643     * Delete the given group (and all linked group members)
644     *
645     * @param string Group identifier
646     * @return boolean True on success, false if no data was changed
647     */
648    function delete_group($gid)
649    {
650        // flag group record as deleted
651        $sql_result = $this->db->query(
652            "UPDATE ".get_table_name($this->db_groups).
653            " SET del=1, changed=".$this->db->now().
654            " WHERE contactgroup_id=?",
655            $gid
656        );
657
658        $this->cache = null;
659
660        return $this->db->affected_rows();
661    }
662
663
664    /**
665     * Rename a specific contact group
666     *
667     * @param string Group identifier
668     * @param string New name to set for this group
669     * @return boolean New name on success, false if no data was changed
670     */
671    function rename_group($gid, $newname)
672    {
673        // make sure we have a unique name
674        $name = $this->unique_groupname($newname);
675
676        $sql_result = $this->db->query(
677            "UPDATE ".get_table_name($this->db_groups).
678            " SET name=?, changed=".$this->db->now().
679            " WHERE contactgroup_id=?",
680            $name, $gid
681        );
682
683        return $this->db->affected_rows() ? $name : false;
684    }
685
686
687    /**
688     * Add the given contact records the a certain group
689     *
690     * @param string  Group identifier
691     * @param array   List of contact identifiers to be added
692     * @return int    Number of contacts added
693     */
694    function add_to_group($group_id, $ids)
695    {
696        if (!is_array($ids))
697            $ids = explode(',', $ids);
698
699        $added = 0;
700        $exists = array();
701
702        // get existing assignments ...
703        $sql_result = $this->db->query(
704            "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
705            " WHERE contactgroup_id=?".
706                " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
707            $group_id
708        );
709        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
710            $exists[] = $sql_arr['contact_id'];
711        }
712        // ... and remove them from the list
713        $ids = array_diff($ids, $exists);
714
715        foreach ($ids as $contact_id) {
716            $this->db->query(
717                "INSERT INTO ".get_table_name($this->db_groupmembers).
718                " (contactgroup_id, contact_id, created)".
719                " VALUES (?, ?, ".$this->db->now().")",
720                $group_id,
721                $contact_id
722            );
723
724            if (!$this->db->db_error)
725                $added++;
726        }
727
728        return $added;
729    }
730
731
732    /**
733     * Remove the given contact records from a certain group
734     *
735     * @param string  Group identifier
736     * @param array   List of contact identifiers to be removed
737     * @return int    Number of deleted group members
738     */
739    function remove_from_group($group_id, $ids)
740    {
741        if (!is_array($ids))
742            $ids = explode(',', $ids);
743
744        $ids = $this->db->array2list($ids, 'integer');
745
746        $sql_result = $this->db->query(
747            "DELETE FROM ".get_table_name($this->db_groupmembers).
748            " WHERE contactgroup_id=?".
749                " AND contact_id IN ($ids)",
750            $group_id
751        );
752
753        return $this->db->affected_rows();
754    }
755
756
757    /**
758     * Check for existing groups with the same name
759     *
760     * @param string Name to check
761     * @return string A group name which is unique for the current use
762     */
763    private function unique_groupname($name)
764    {
765        $checkname = $name;
766        $num = 2; $hit = false;
767
768        do {
769            $sql_result = $this->db->query(
770                "SELECT 1 FROM ".get_table_name($this->db_groups).
771                " WHERE del<>1".
772                    " AND user_id=?".
773                    " AND name=?",
774                $this->user_id,
775                $checkname);
776
777            // append number to make name unique
778            if ($hit = $this->db->num_rows($sql_result))
779                $checkname = $name . ' ' . $num++;
780        } while ($hit > 0);
781
782        return $checkname;
783    }
784
785}
Note: See TracBrowser for help on using the repository browser.