source: github/program/include/rcube_contacts.php @ 4307ccd8

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 4307ccd8 was 4307ccd8, checked in by alecpl <alec@…>, 4 years ago
  • prevent PREPARE error on postgres when inserting non-Unicode characters
  • Property mode set to 100644
File size: 9.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-2009, 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 */
28class rcube_contacts extends rcube_addressbook
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', 'vcard');
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  /**
63   * Save a search string for future listings
64   *
65   * @param  string SQL params to use in listing method
66   */
67  function set_search_set($filter)
68  {
69    $this->filter = $filter;
70  }
71 
72 
73  /**
74   * Getter for saved search properties
75   *
76   * @return mixed Search properties used by this class
77   */
78  function get_search_set()
79  {
80    return $this->filter;
81  }
82
83
84  /**
85   * Reset all saved results and search parameters
86   */
87  function reset()
88  {
89    $this->result = null;
90    $this->filter = null;
91    $this->search_fields = null;
92    $this->search_string = null;
93  }
94 
95 
96  /**
97   * List the current set of contact records
98   *
99   * @param  array  List of cols to show
100   * @param  int    Only return this number of records, use negative values for tail
101   * @return array  Indexed list of contact records, each a hash array
102   */
103  function list_records($cols=null, $subset=0)
104  {
105    // count contacts for this user
106    $this->result = $this->count();
107    $sql_result = NULL;
108
109    // get contacts from DB
110    if ($this->result->count)
111    {
112      $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
113      $length = $subset != 0 ? abs($subset) : $this->page_size;
114     
115      $sql_result = $this->db->limitquery(
116        "SELECT * FROM ".$this->db_name."
117         WHERE  del<>1
118         AND    user_id=?" .
119        ($this->filter ? " AND (".$this->filter.")" : "") .
120        " ORDER BY name",
121        $start_row,
122        $length,
123        $this->user_id);
124    }
125   
126    while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result)))
127    {
128      $sql_arr['ID'] = $sql_arr[$this->primary_key];
129      // make sure we have a name to display
130      if (empty($sql_arr['name']))
131        $sql_arr['name'] = $sql_arr['email'];
132      $this->result->add($sql_arr);
133    }
134   
135    return $this->result;
136  }
137
138
139  /**
140   * Search contacts
141   *
142   * @param array   List of fields to search in
143   * @param string  Search value
144   * @param boolean True if results are requested, False if count only
145   * @return Indexed list of contact records and 'count' value
146   */
147  function search($fields, $value, $strict=false, $select=true)
148  {
149    if (!is_array($fields))
150      $fields = array($fields);
151     
152    $add_where = array();
153    foreach ($fields as $col)
154    {
155      if ($col == 'ID' || $col == $this->primary_key)
156      {
157        $ids = !is_array($value) ? explode(',', $value) : $value;
158        $add_where[] = $this->primary_key.' IN ('.join(',', $ids).')';
159      }
160      else if ($strict)
161        $add_where[] = $this->db->quoteIdentifier($col).'='.$this->db->quote($value);
162      else
163        $add_where[] = $this->db->ilike($col, '%'.$value.'%');
164    }
165   
166    if (!empty($add_where))
167    {
168      $this->set_search_set(join(' OR ', $add_where));
169      if ($select)
170        $this->list_records();
171      else
172        $this->result = $this->count();
173    }
174   
175    return $this->result; 
176  }
177
178
179  /**
180   * Count number of available contacts in database
181   *
182   * @return Result array with values for 'count' and 'first'
183   */
184  function count()
185  {
186    // count contacts for this user
187    $sql_result = $this->db->query(
188      "SELECT COUNT(contact_id) AS rows
189       FROM ".$this->db_name."
190       WHERE  del<>1
191       AND    user_id=?".
192       ($this->filter ? " AND (".$this->filter.")" : ""),
193      $this->user_id);
194
195    $sql_arr = $this->db->fetch_assoc($sql_result);
196    return new rcube_result_set($sql_arr['rows'], ($this->list_page-1) * $this->page_size);;
197  }
198
199
200  /**
201   * Return the last result set
202   *
203   * @return Result array or NULL if nothing selected yet
204   */
205  function get_result()
206  {
207    return $this->result;
208  }
209 
210 
211  /**
212   * Get a specific contact record
213   *
214   * @param mixed record identifier(s)
215   * @return Result object with all record fields or False if not found
216   */
217  function get_record($id, $assoc=false)
218  {
219    // return cached result
220    if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
221      return $assoc ? $first : $this->result;
222     
223    $this->db->query(
224      "SELECT * FROM ".$this->db_name."
225       WHERE  contact_id=?
226       AND    user_id=?
227       AND    del<>1",
228      $id,
229      $this->user_id);
230
231    if ($sql_arr = $this->db->fetch_assoc())
232    {
233      $sql_arr['ID'] = $sql_arr[$this->primary_key];
234      $this->result = new rcube_result_set(1);
235      $this->result->add($sql_arr);
236    }
237
238    return $assoc && $sql_arr ? $sql_arr : $this->result;
239  }
240 
241 
242  /**
243   * Create a new contact record
244   *
245   * @param array Assoziative array with save data
246   * @return The created record ID on success, False on error
247   */
248  function insert($save_data, $check=false)
249  {
250    if (is_object($save_data) && is_a($save_data, rcube_result_set))
251      return $this->insert_recset($save_data, $check);
252
253    $insert_id = $existing = false;
254
255    if ($check)
256      $existing = $this->search('email', $save_data['email'], true, false);
257
258    $a_insert_cols = $a_insert_values = array();
259    foreach ($this->table_cols as $col)
260      if (isset($save_data[$col]))
261      {
262        $a_insert_cols[] = $this->db->quoteIdentifier($col);
263        $a_insert_values[] = $this->db->quote($save_data[$col]);
264      }
265
266    if (!$existing->count && !empty($a_insert_cols))
267    {
268      $this->db->query(
269        "INSERT INTO ".$this->db_name."
270         (user_id, changed, del, ".join(', ', $a_insert_cols).")
271         VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
272        );
273       
274      $insert_id = $this->db->insert_id(get_sequence_name('contacts'));
275    }
276
277    return $insert_id;
278  }
279
280
281  /**
282   * Insert new contacts for each row in set
283   */
284  function insert_recset($result, $check=false)
285  {
286    $ids = array();
287    while ($row = $result->next())
288    {
289      if ($insert = $this->insert($row, $check))
290        $ids[] = $insert;
291    }
292    return $ids;
293  }
294 
295 
296  /**
297   * Update a specific contact record
298   *
299   * @param mixed Record identifier
300   * @param array Assoziative array with save data
301   * @return True on success, False on error
302   */
303  function update($id, $save_cols)
304  {
305    $updated = false;
306    $write_sql = array();
307    foreach ($this->table_cols as $col)
308      if (isset($save_cols[$col]))
309        $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($save_cols[$col]));
310
311    if (!empty($write_sql))
312    {
313      $this->db->query(
314        "UPDATE ".$this->db_name."
315         SET    changed=".$this->db->now().", ".join(', ', $write_sql)."
316         WHERE  contact_id=?
317         AND    user_id=?
318         AND    del<>1",
319        $id,
320        $this->user_id);
321
322      $updated = $this->db->affected_rows();
323    }
324   
325    return $updated;
326  }
327 
328 
329  /**
330   * Mark one or more contact records as deleted
331   *
332   * @param array  Record identifiers
333   */
334  function delete($ids)
335  {
336    if (is_array($ids))
337      $ids = join(',', $ids);
338
339    $this->db->query(
340      "UPDATE ".$this->db_name."
341       SET    del=1
342       WHERE  user_id=?
343       AND    contact_id IN (".$ids.")",
344      $this->user_id);
345
346    return $this->db->affected_rows();
347  }
348 
349 
350  /**
351   * Remove all records from the database
352   */
353  function delete_all()
354  {
355    $this->db->query("DELETE FROM {$this->db_name} WHERE user_id=?", $this->user_id);
356    return $this->db->affected_rows();
357  }
358
359}
Note: See TracBrowser for help on using the repository browser.