]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_contacts.php
Imported Upstream version 0.2~alpha
[roundcube.git] / program / include / rcube_contacts.php
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-2008, 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: rcube_contacts.inc 328 2006-08-30 17:41:21Z thomasb $
19
20 */
21
22
23 /**
24  * Model class for the local address book database
25  *
26  * @package Addressbook
27  */
28 class rcube_contacts
29 {
30   var $db = null;
31   var $db_name = '';
32   var $user_id = 0;
33   var $filter = null;
34   var $result = null;
35   var $search_fields;
36   var $search_string;
37   var $table_cols = array('name', 'email', 'firstname', 'surname');
38   
39   /** public properties */
40   var $primary_key = 'contact_id';
41   var $readonly = false;
42   var $list_page = 1;
43   var $page_size = 10;
44   var $ready = false;
45
46   
47   /**
48    * Object constructor
49    *
50    * @param object  Instance of the rcube_db class
51    * @param integer User-ID
52    */
53   function __construct($dbconn, $user)
54   {
55     $this->db = $dbconn;
56     $this->db_name = get_table_name('contacts');
57     $this->user_id = $user;
58     $this->ready = $this->db && !$this->db->is_error();
59   }
60
61   /**
62    * PHP 4 object constructor
63    *
64    * @see rcube_contacts::__construct()
65    */
66   function rcube_contacts($dbconn, $user)
67   {
68     $this->__construct($dbconn, $user);
69   }
70
71
72   /**
73    * Set internal list page
74    *
75    * @param  number  Page number to list
76    * @access public
77    */
78   function set_page($page)
79   {
80     $this->list_page = (int)$page;
81   }
82
83
84   /**
85    * Set internal page size
86    *
87    * @param  number  Number of messages to display on one page
88    * @access public
89    */
90   function set_pagesize($size)
91   {
92     $this->page_size = (int)$size;
93   }
94
95
96   /**
97    * Save a search string for future listings
98    *
99    * @param  string SQL params to use in listing method
100    */
101   function set_search_set($filter)
102   {
103     $this->filter = $filter;
104   }
105   
106   
107   /**
108    * Getter for saved search properties
109    *
110    * @return mixed Search properties used by this class
111    */
112   function get_search_set()
113   {
114     return $this->filter;
115   }
116
117
118   /**
119    * Reset all saved results and search parameters
120    */
121   function reset()
122   {
123     $this->result = null;
124     $this->filter = null;
125     $this->search_fields = null;
126     $this->search_string = null;
127   }
128   
129   
130   /**
131    * Close connection to source
132    * Called on script shutdown
133    */
134   function close(){}
135   
136   
137   /**
138    * List the current set of contact records
139    *
140    * @param  array  List of cols to show
141    * @param  int    Only return this number of records, use negative values for tail
142    * @return array  Indexed list of contact records, each a hash array
143    */
144   function list_records($cols=null, $subset=0)
145   {
146     // count contacts for this user
147     $this->result = $this->count();
148     $sql_result = NULL;
149
150     // get contacts from DB
151     if ($this->result->count)
152     {
153       $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
154       $length = $subset != 0 ? abs($subset) : $this->page_size;
155       
156       $sql_result = $this->db->limitquery(
157         "SELECT * FROM ".$this->db_name."
158          WHERE  del<>1
159          AND    user_id=?" .
160         ($this->filter ? " AND (".$this->filter.")" : "") .
161         " ORDER BY name",
162         $start_row,
163         $length,
164         $this->user_id);
165     }
166     
167     while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result)))
168     {
169       $sql_arr['ID'] = $sql_arr[$this->primary_key];
170       // make sure we have a name to display
171       if (empty($sql_arr['name']))
172         $sql_arr['name'] = $sql_arr['email'];
173       $this->result->add($sql_arr);
174     }
175     
176     return $this->result;
177   }
178
179
180   /**
181    * Search contacts
182    *
183    * @param array   List of fields to search in
184    * @param string  Search value
185    * @param boolean True if results are requested, False if count only
186    * @return Indexed list of contact records and 'count' value
187    */
188   function search($fields, $value, $strict=false, $select=true)
189   {
190     if (!is_array($fields))
191       $fields = array($fields);
192       
193     $add_where = array();
194     foreach ($fields as $col)
195     {
196       if ($col == 'ID' || $col == $this->primary_key)
197       {
198         $ids = !is_array($value) ? split(',', $value) : $value;
199         $add_where[] = $this->primary_key." IN (".join(',', $ids).")";
200       }
201       else if ($strict)
202         $add_where[] = $this->db->quoteIdentifier($col)."=".$this->db->quote($value);
203       else
204         $add_where[] = $this->db->quoteIdentifier($col)." LIKE ".$this->db->quote(strlen($value)>2 ? "%$value%" : "$value%");
205     }
206     
207     if (!empty($add_where))
208     {
209       $this->set_search_set(join(' OR ', $add_where));
210       if ($select)
211         $this->list_records();
212       else
213         $this->result = $this->count();
214     }
215    
216     return $this->result; 
217   }
218
219
220   /**
221    * Count number of available contacts in database
222    *
223    * @return Result array with values for 'count' and 'first'
224    */
225   function count()
226   {
227     // count contacts for this user
228     $sql_result = $this->db->query(
229       "SELECT COUNT(contact_id) AS rows
230        FROM ".$this->db_name."
231        WHERE  del<>1
232        AND    user_id=?".
233        ($this->filter ? " AND (".$this->filter.")" : ""),
234       $this->user_id);
235
236     $sql_arr = $this->db->fetch_assoc($sql_result);
237     return new rcube_result_set($sql_arr['rows'], ($this->list_page-1) * $this->page_size);;
238   }
239
240
241   /**
242    * Return the last result set
243    *
244    * @return Result array or NULL if nothing selected yet
245    */
246   function get_result($as_res=true)
247   {
248     return $this->result;
249   }
250   
251   
252   /**
253    * Get a specific contact record
254    *
255    * @param mixed record identifier(s)
256    * @return Result object with all record fields or False if not found
257    */
258   function get_record($id, $assoc=false)
259   {
260     // return cached result
261     if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
262       return $assoc ? $first : $this->result;
263       
264     $this->db->query(
265       "SELECT * FROM ".$this->db_name."
266        WHERE  contact_id=?
267        AND    user_id=?
268        AND    del<>1",
269       $id,
270       $this->user_id);
271
272     if ($sql_arr = $this->db->fetch_assoc())
273     {
274       $sql_arr['ID'] = $sql_arr[$this->primary_key];
275       $this->result = new rcube_result_set(1);
276       $this->result->add($sql_arr);
277     }
278
279     return $assoc && $sql_arr ? $sql_arr : $this->result;
280   }
281   
282   
283   /**
284    * Create a new contact record
285    *
286    * @param array Assoziative array with save data
287    * @return The created record ID on success, False on error
288    */
289   function insert($save_data, $check=false)
290   {
291     if (is_object($save_data) && is_a($save_data, rcube_result_set))
292       return $this->insert_recset($save_data, $check);
293
294     $insert_id = $existing = false;
295
296     if ($check)
297       $existing = $this->search('email', $save_data['email'], true, false);
298
299     $a_insert_cols = $a_insert_values = array();
300     foreach ($this->table_cols as $col)
301       if (isset($save_data[$col]))
302       {
303         $a_insert_cols[] = $this->db->quoteIdentifier($col);
304         $a_insert_values[] = $this->db->quote($save_data[$col]);
305       }
306     
307     if (!$existing->count && !empty($a_insert_cols))
308     {
309       $this->db->query(
310         "INSERT INTO ".$this->db_name."
311          (user_id, changed, del, ".join(', ', $a_insert_cols).")
312          VALUES (?, ".$this->db->now().", 0, ".join(', ', $a_insert_values).")",
313         $this->user_id);
314         
315       $insert_id = $this->db->insert_id(get_sequence_name('contacts'));
316     }
317     
318     return $insert_id;
319   }
320
321
322   /**
323    * Insert new contacts for each row in set
324    */
325   function insert_recset($result, $check=false)
326   {
327     $ids = array();
328     while ($row = $result->next())
329     {
330       if ($insert = $this->insert($row, $check))
331         $ids[] = $insert;
332     }
333     return $ids;
334   }
335   
336   
337   /**
338    * Update a specific contact record
339    *
340    * @param mixed Record identifier
341    * @param array Assoziative array with save data
342    * @return True on success, False on error
343    */
344   function update($id, $save_cols)
345   {
346     $updated = false;
347     $write_sql = array();
348     foreach ($this->table_cols as $col)
349       if (isset($save_cols[$col]))
350         $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($save_cols[$col]));
351
352     if (!empty($write_sql))
353     {
354       $this->db->query(
355         "UPDATE ".$this->db_name."
356          SET    changed=".$this->db->now().", ".join(', ', $write_sql)."
357          WHERE  contact_id=?
358          AND    user_id=?
359          AND    del<>1",
360         $id,
361         $this->user_id);
362
363       $updated = $this->db->affected_rows();
364     }
365     
366     return $updated;
367   }
368   
369   
370   /**
371    * Mark one or more contact records as deleted
372    *
373    * @param array  Record identifiers
374    */
375   function delete($ids)
376   {
377     if (is_array($ids))
378       $ids = join(',', $ids);
379
380     $this->db->query(
381       "UPDATE ".$this->db_name."
382        SET    del=1
383        WHERE  user_id=?
384        AND    contact_id IN (".$ids.")",
385       $this->user_id);
386
387     return $this->db->affected_rows();
388   }
389   
390   
391   /**
392    * Remove all records from the database
393    */
394   function delete_all()
395   {
396     $this->db->query("DELETE FROM {$this->db_name} WHERE user_id=?", $this->user_id);
397     return $this->db->affected_rows();
398   }
399
400 }