source: github/program/include/rcube_contacts.php @ 58510fc

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 58510fc was 569f830, checked in by thomascube <thomas@…>, 2 years ago

Fix vcard folding at 75 chars; don't fold vcards for internal storage

  • Property mode set to 100644
File size: 23.5 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 c.name",
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                $sql_arr['name'] = $sql_arr['email'][0];
207
208            $this->result->add($sql_arr);
209        }
210
211        $cnt = count($this->result->records);
212
213        // update counter
214        if ($nocount)
215            $this->result->count = $cnt;
216        else if ($this->list_page <= 1) {
217            if ($cnt < $this->page_size && $subset == 0)
218                $this->result->count = $cnt;
219            else if (isset($this->cache['count']))
220                $this->result->count = $this->cache['count'];
221            else
222                $this->result->count = $this->_count();
223        }
224
225        return $this->result;
226    }
227
228
229    /**
230     * Search contacts
231     *
232     * @param array   List of fields to search in
233     * @param string  Search value
234     * @param boolean True for strict (=), False for partial (LIKE) matching
235     * @param boolean True if results are requested, False if count only
236     * @param boolean True to skip the count query (select only)
237     * @param array   List of fields that cannot be empty
238     * @return object rcube_result_set Contact records and 'count' value
239     */
240    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
241    {
242        if (!is_array($fields))
243            $fields = array($fields);
244        if (!is_array($required) && !empty($required))
245            $required = array($required);
246
247        $where = $and_where = array();
248
249        foreach ($fields as $col) {
250            if ($col == 'ID' || $col == $this->primary_key) {
251                $ids     = !is_array($value) ? explode(',', $value) : $value;
252                $ids     = $this->db->array2list($ids, 'integer');
253                $where[] = 'c.' . $this->primary_key.' IN ('.$ids.')';
254            }
255            else if ($strict) {
256                $where[] = $this->db->quoteIdentifier($col).' = '.$this->db->quote($value);
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
265                $where[] = $this->db->ilike($col, '%'.$value.'%');
266        }
267
268        foreach ($required as $col) {
269            $and_where[] = $this->db->quoteIdentifier($col).' <> '.$this->db->quote('');
270        }
271
272        if (!empty($where))
273            $where = join(' OR ', $where);
274
275        if (!empty($and_where))
276            $where = ($where ? "($where) AND " : '') . join(' AND ', $and_where);
277
278        if (!empty($where)) {
279            $this->set_search_set($where);
280            if ($select)
281                $this->list_records(null, 0, $nocount);
282            else
283                $this->result = $this->count();
284        }
285
286        return $this->result; 
287    }
288
289
290    /**
291     * Count number of available contacts in database
292     *
293     * @return rcube_result_set Result object
294     */
295    function count()
296    {
297        $count = isset($this->cache['count']) ? $this->cache['count'] : $this->_count();
298
299        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
300    }
301
302
303    /**
304     * Count number of available contacts in database
305     *
306     * @return int Contacts count
307     */
308    private function _count()
309    {
310        if ($this->group_id)
311            $join = " LEFT JOIN ".get_table_name($this->db_groupmembers)." AS m".
312                " ON (m.contact_id=c.".$this->primary_key.")";
313
314        // count contacts for this user
315        $sql_result = $this->db->query(
316            "SELECT COUNT(c.contact_id) AS rows".
317            " FROM ".get_table_name($this->db_name)." AS c".
318                $join.
319            " WHERE c.del<>1".
320            " AND c.user_id=?".
321            ($this->group_id ? " AND m.contactgroup_id=?" : "").
322            ($this->filter ? " AND (".$this->filter.")" : ""),
323            $this->user_id,
324            $this->group_id
325        );
326
327        $sql_arr = $this->db->fetch_assoc($sql_result);
328
329        $this->cache['count'] = (int) $sql_arr['rows'];
330
331        return $this->cache['count'];
332    }
333
334
335    /**
336     * Return the last result set
337     *
338     * @return mixed Result array or NULL if nothing selected yet
339     */
340    function get_result()
341    {
342        return $this->result;
343    }
344
345
346    /**
347     * Get a specific contact record
348     *
349     * @param mixed record identifier(s)
350     * @return mixed Result object with all record fields or False if not found
351     */
352    function get_record($id, $assoc=false)
353    {
354        // return cached result
355        if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
356            return $assoc ? $first : $this->result;
357
358        $this->db->query(
359            "SELECT * FROM ".get_table_name($this->db_name).
360            " WHERE contact_id=?".
361                " AND user_id=?".
362                " AND del<>1",
363            $id,
364            $this->user_id
365        );
366
367        if ($sql_arr = $this->db->fetch_assoc()) {
368            $record = $this->convert_db_data($sql_arr);
369            $this->result = new rcube_result_set(1);
370            $this->result->add($record);
371        }
372
373        return $assoc && $record ? $record : $this->result;
374    }
375
376
377    /**
378     * Get group assignments of a specific contact record
379     *
380     * @param mixed Record identifier
381     * @return array List of assigned groups as ID=>Name pairs
382     */
383    function get_record_groups($id)
384    {
385      $results = array();
386
387      if (!$this->groups)
388          return $results;
389
390      $sql_result = $this->db->query(
391        "SELECT cgm.contactgroup_id, cg.name FROM " . get_table_name($this->db_groupmembers) . " AS cgm" .
392        " LEFT JOIN " . get_table_name($this->db_groups) . " AS cg ON (cgm.contactgroup_id = cg.contactgroup_id AND cg.del<>1)" .
393        " WHERE cgm.contact_id=?",
394        $id
395      );
396      while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
397        $results[$sql_arr['contactgroup_id']] = $sql_arr['name'];
398      }
399
400      return $results;
401    }
402
403
404    /**
405     * Check the given data before saving.
406     * If input not valid, the message to display can be fetched using get_error()
407     *
408     * @param array Assoziative array with data to save
409     * @return boolean True if input is valid, False if not.
410     */
411    public function validate($save_data)
412    {
413        // check for name input
414        $valid = parent::validate($save_data);
415
416        // require at least one e-mail address (syntax check is done later in save.inc)
417        if ($valid && !array_filter($this->get_col_values('email', $save_data, true))) {
418            $this->set_error('warning', 'noemailwarning');
419            $valid = false;
420        }
421
422        return $valid;
423    }
424
425
426    /**
427     * Create a new contact record
428     *
429     * @param array Associative array with save data
430     * @return integer|boolean The created record ID on success, False on error
431     */
432    function insert($save_data, $check=false)
433    {
434        if (!is_array($save_data))
435            return false;
436
437        $insert_id = $existing = false;
438
439        if ($check) {
440            foreach ($save_data as $col => $values) {
441                if (strpos($col, 'email') === 0) {
442                    foreach ((array)$values as $email) {
443                        if ($existing = $this->search('email', $email, false, false))
444                            break 2;
445                    }
446                }
447            }
448        }
449
450        $save_data = $this->convert_save_data($save_data);
451        $a_insert_cols = $a_insert_values = array();
452
453        foreach ($save_data as $col => $value) {
454            $a_insert_cols[]   = $this->db->quoteIdentifier($col);
455            $a_insert_values[] = $this->db->quote($value);
456        }
457
458        if (!$existing->count && !empty($a_insert_cols)) {
459            $this->db->query(
460                "INSERT INTO ".get_table_name($this->db_name).
461                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
462                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
463            );
464
465            $insert_id = $this->db->insert_id($this->db_name);
466        }
467
468        // also add the newly created contact to the active group
469        if ($insert_id && $this->group_id)
470            $this->add_to_group($this->group_id, $insert_id);
471
472        $this->cache = null;
473
474        return $insert_id;
475    }
476
477
478    /**
479     * Update a specific contact record
480     *
481     * @param mixed Record identifier
482     * @param array Assoziative array with save data
483     * @return boolean True on success, False on error
484     */
485    function update($id, $save_cols)
486    {
487        $updated = false;
488        $write_sql = array();
489        $record = $this->get_record($id, true);
490        $save_cols = $this->convert_save_data($save_cols, $record);
491
492        foreach ($save_cols as $col => $value) {
493            $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($value));
494        }
495
496        if (!empty($write_sql)) {
497            $this->db->query(
498                "UPDATE ".get_table_name($this->db_name).
499                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
500                " WHERE contact_id=?".
501                    " AND user_id=?".
502                    " AND del<>1",
503                $id,
504                $this->user_id
505            );
506
507            $updated = $this->db->affected_rows();
508            $this->result = null;  // clear current result (from get_record())
509        }
510
511        return $updated;
512    }
513   
514   
515    private function convert_db_data($sql_arr)
516    {
517        $record = array();
518        $record['ID'] = $sql_arr[$this->primary_key];
519       
520        if ($sql_arr['vcard']) {
521            unset($sql_arr['email']);
522            $vcard = new rcube_vcard($sql_arr['vcard']);
523            $record += $vcard->get_assoc() + $sql_arr;
524        }
525        else {
526            $record += $sql_arr;
527            $record['email'] = preg_split('/,\s*/', $record['email']);
528        }
529       
530        return $record;
531    }
532
533
534    private function convert_save_data($save_data, $record = array())
535    {
536        $out = array();
537        $words = '';
538
539        // copy values into vcard object
540        $vcard = new rcube_vcard($record['vcard'] ? $record['vcard'] : $save_data['vcard']);
541        $vcard->reset();
542        foreach ($save_data as $key => $values) {
543            list($field, $section) = explode(':', $key);
544            $fulltext = in_array($field, $this->fulltext_cols);
545            foreach ((array)$values as $value) {
546                if (isset($value))
547                    $vcard->set($field, $value, $section);
548                if ($fulltext && is_array($value))
549                    $words .= ' ' . self::normalize_string(join(" ", $value));
550                else if ($fulltext && strlen($value) >= 3)
551                    $words .= ' ' . self::normalize_string($value);
552            }
553        }
554        $out['vcard'] = $vcard->export(false);
555
556        foreach ($this->table_cols as $col) {
557            $key = $col;
558            if (!isset($save_data[$key]))
559                $key .= ':home';
560            if (isset($save_data[$key]))
561                $out[$col] = is_array($save_data[$key]) ? join(',', $save_data[$key]) : $save_data[$key];
562        }
563
564        // save all e-mails in database column
565        $out['email'] = join(", ", $vcard->email);
566
567        // join words for fulltext search
568        $out['words'] = join(" ", array_unique(explode(" ", $words)));
569
570        return $out;
571    }
572
573
574    /**
575     * Mark one or more contact records as deleted
576     *
577     * @param array  Record identifiers
578     */
579    function delete($ids)
580    {
581        if (!is_array($ids))
582            $ids = explode(',', $ids);
583
584        $ids = $this->db->array2list($ids, 'integer');
585
586        // flag record as deleted
587        $this->db->query(
588            "UPDATE ".get_table_name($this->db_name).
589            " SET del=1, changed=".$this->db->now().
590            " WHERE user_id=?".
591                " AND contact_id IN ($ids)",
592            $this->user_id
593        );
594
595        $this->cache = null;
596
597        return $this->db->affected_rows();
598    }
599
600
601    /**
602     * Remove all records from the database
603     */
604    function delete_all()
605    {
606        $this->db->query("DELETE FROM ".get_table_name($this->db_name)." WHERE user_id = ?", $this->user_id);
607        $this->cache = null;
608        return $this->db->affected_rows();
609    }
610
611
612    /**
613     * Create a contact group with the given name
614     *
615     * @param string The group name
616     * @return mixed False on error, array with record props in success
617     */
618    function create_group($name)
619    {
620        $result = false;
621
622        // make sure we have a unique name
623        $name = $this->unique_groupname($name);
624
625        $this->db->query(
626            "INSERT INTO ".get_table_name($this->db_groups).
627            " (user_id, changed, name)".
628            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
629        );
630
631        if ($insert_id = $this->db->insert_id($this->db_groups))
632            $result = array('id' => $insert_id, 'name' => $name);
633
634        return $result;
635    }
636
637
638    /**
639     * Delete the given group (and all linked group members)
640     *
641     * @param string Group identifier
642     * @return boolean True on success, false if no data was changed
643     */
644    function delete_group($gid)
645    {
646        // flag group record as deleted
647        $sql_result = $this->db->query(
648            "UPDATE ".get_table_name($this->db_groups).
649            " SET del=1, changed=".$this->db->now().
650            " WHERE contactgroup_id=?",
651            $gid
652        );
653
654        $this->cache = null;
655
656        return $this->db->affected_rows();
657    }
658
659
660    /**
661     * Rename a specific contact group
662     *
663     * @param string Group identifier
664     * @param string New name to set for this group
665     * @return boolean New name on success, false if no data was changed
666     */
667    function rename_group($gid, $newname)
668    {
669        // make sure we have a unique name
670        $name = $this->unique_groupname($newname);
671
672        $sql_result = $this->db->query(
673            "UPDATE ".get_table_name($this->db_groups).
674            " SET name=?, changed=".$this->db->now().
675            " WHERE contactgroup_id=?",
676            $name, $gid
677        );
678
679        return $this->db->affected_rows() ? $name : false;
680    }
681
682
683    /**
684     * Add the given contact records the a certain group
685     *
686     * @param string  Group identifier
687     * @param array   List of contact identifiers to be added
688     * @return int    Number of contacts added
689     */
690    function add_to_group($group_id, $ids)
691    {
692        if (!is_array($ids))
693            $ids = explode(',', $ids);
694
695        $added = 0;
696        $exists = array();
697
698        // get existing assignments ...
699        $sql_result = $this->db->query(
700            "SELECT contact_id FROM ".get_table_name($this->db_groupmembers).
701            " WHERE contactgroup_id=?".
702                " AND contact_id IN (".$this->db->array2list($ids, 'integer').")",
703            $group_id
704        );
705        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
706            $exists[] = $sql_arr['contact_id'];
707        }
708        // ... and remove them from the list
709        $ids = array_diff($ids, $exists);
710
711        foreach ($ids as $contact_id) {
712            $this->db->query(
713                "INSERT INTO ".get_table_name($this->db_groupmembers).
714                " (contactgroup_id, contact_id, created)".
715                " VALUES (?, ?, ".$this->db->now().")",
716                $group_id,
717                $contact_id
718            );
719
720            if (!$this->db->db_error)
721                $added++;
722        }
723
724        return $added;
725    }
726
727
728    /**
729     * Remove the given contact records from a certain group
730     *
731     * @param string  Group identifier
732     * @param array   List of contact identifiers to be removed
733     * @return int    Number of deleted group members
734     */
735    function remove_from_group($group_id, $ids)
736    {
737        if (!is_array($ids))
738            $ids = explode(',', $ids);
739
740        $ids = $this->db->array2list($ids, 'integer');
741
742        $sql_result = $this->db->query(
743            "DELETE FROM ".get_table_name($this->db_groupmembers).
744            " WHERE contactgroup_id=?".
745                " AND contact_id IN ($ids)",
746            $group_id
747        );
748
749        return $this->db->affected_rows();
750    }
751
752
753    /**
754     * Check for existing groups with the same name
755     *
756     * @param string Name to check
757     * @return string A group name which is unique for the current use
758     */
759    private function unique_groupname($name)
760    {
761        $checkname = $name;
762        $num = 2; $hit = false;
763
764        do {
765            $sql_result = $this->db->query(
766                "SELECT 1 FROM ".get_table_name($this->db_groups).
767                " WHERE del<>1".
768                    " AND user_id=?".
769                    " AND name=?",
770                $this->user_id,
771                $checkname);
772
773            // append number to make name unique
774            if ($hit = $this->db->num_rows($sql_result))
775                $checkname = $name . ' ' . $num++;
776        } while ($hit > 0);
777
778        return $checkname;
779    }
780
781}
Note: See TracBrowser for help on using the repository browser.