source: subversion/trunk/roundcubemail/program/include/rcube_contacts.php @ 3449

Last change on this file since 3449 was 3449, checked in by thomasb, 3 years ago

Asynchronously expand contact groups + skip count queries in autocompletion mode + check for the existance of contactgroups table

  • Property svn:keywords set to Id
File size: 15.0 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$
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 $groups = false;
43  var $list_page = 1;
44  var $page_size = 10;
45  var $group_id = 0;
46  var $ready = false;
47
48 
49  /**
50   * Object constructor
51   *
52   * @param object  Instance of the rcube_db class
53   * @param integer User-ID
54   */
55  function __construct($dbconn, $user)
56  {
57    $this->db = $dbconn;
58    $this->db_name = get_table_name('contacts');
59    $this->user_id = $user;
60    $this->ready = $this->db && !$this->db->is_error();
61   
62    if (in_array('contactgroups', $this->db->list_tables()))
63      $this->groups = true;
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  }
76 
77 
78  /**
79   * Getter for saved search properties
80   *
81   * @return mixed Search properties used by this class
82   */
83  function get_search_set()
84  {
85    return $this->filter;
86  }
87
88
89  /**
90   * Setter for the current group
91   * (empty, has to be re-implemented by extending class)
92   */
93  function set_group($gid)
94  {
95    $this->group_id = $gid;
96  }
97
98
99  /**
100   * Reset all saved results and search parameters
101   */
102  function reset()
103  {
104    $this->result = null;
105    $this->filter = null;
106    $this->search_fields = null;
107    $this->search_string = null;
108  }
109 
110  /**
111   * List all active contact groups of this source
112   *
113   * @param string  Search string to match group name
114   * @return array  Indexed list of contact groups, each a hash array
115   */
116  function list_groups($search = null)
117  {
118    $results = array();
119   
120    if (!$this->groups)
121      return $results;
122     
123    $sql_filter = $search ? "AND " . $this->db->ilike('name', '%'.$search.'%') : '';
124
125    $sql_result = $this->db->query(
126      "SELECT * FROM ".get_table_name('contactgroups')."
127       WHERE  del<>1
128       AND    user_id=?
129       $sql_filter
130       ORDER BY name",
131      $this->user_id);
132
133    while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
134      $sql_arr['ID'] = $sql_arr['contactgroup_id'];
135      $results[] = $sql_arr;
136    }
137   
138    return $results;
139  }
140 
141  /**
142   * List the current set of contact records
143   *
144   * @param  array   List of cols to show
145   * @param  int     Only return this number of records, use negative values for tail
146   * @param  boolean True to skip the count query (select only)
147   * @return array  Indexed list of contact records, each a hash array
148   */
149  function list_records($cols=null, $subset=0, $nocount=false)
150  {
151    // count contacts for this user
152    $this->result = $nocount ? new rcube_result_set(1) : $this->count();
153    $sql_result = NULL;
154
155    // get contacts from DB
156    if ($this->result->count)
157    {
158      if ($this->group_id)
159        $join = "LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
160          " ON (m.contact_id=c.".$this->primary_key.")";
161     
162      $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
163      $length = $subset != 0 ? abs($subset) : $this->page_size;
164     
165      $sql_result = $this->db->limitquery(
166        "SELECT * FROM ".$this->db_name." AS c ".$join."
167         WHERE  c.del<>1
168         AND    c.user_id=?" .
169        ($this->group_id ? " AND m.contactgroup_id=?" : "").
170        ($this->filter ? " AND (".$this->filter.")" : "") .
171        " ORDER BY c.name",
172        $start_row,
173        $length,
174        $this->user_id,
175        $this->group_id);
176    }
177   
178    while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result)))
179    {
180      $sql_arr['ID'] = $sql_arr[$this->primary_key];
181      // make sure we have a name to display
182      if (empty($sql_arr['name']))
183        $sql_arr['name'] = $sql_arr['email'];
184      $this->result->add($sql_arr);
185    }
186   
187    if ($nocount)
188      $this->result->count = count($this->result->records);
189   
190    return $this->result;
191  }
192
193
194  /**
195   * Search contacts
196   *
197   * @param array   List of fields to search in
198   * @param string  Search value
199   * @param boolean True for strict (=), False for partial (LIKE) matching
200   * @param boolean True if results are requested, False if count only
201   * @param boolean True to skip the count query (select only)
202   * @return Indexed list of contact records and 'count' value
203   */
204  function search($fields, $value, $strict=false, $select=true, $nocount=false)
205  {
206    if (!is_array($fields))
207      $fields = array($fields);
208     
209    $add_where = array();
210    foreach ($fields as $col)
211    {
212      if ($col == 'ID' || $col == $this->primary_key)
213      {
214        $ids = !is_array($value) ? explode(',', $value) : $value;
215        $add_where[] = $this->primary_key.' IN ('.join(',', $ids).')';
216      }
217      else if ($strict)
218        $add_where[] = $this->db->quoteIdentifier($col).'='.$this->db->quote($value);
219      else
220        $add_where[] = $this->db->ilike($col, '%'.$value.'%');
221    }
222   
223    if (!empty($add_where))
224    {
225      $this->set_search_set(join(' OR ', $add_where));
226      if ($select)
227        $this->list_records(null, 0, $nocount);
228      else
229        $this->result = $this->count();
230    }
231   
232    return $this->result; 
233  }
234
235
236  /**
237   * Count number of available contacts in database
238   *
239   * @return Result array with values for 'count' and 'first'
240   */
241  function count()
242  {
243    if ($this->group_id)
244      $join = "LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
245        " ON (m.contact_id=c.".$this->primary_key.")";
246     
247    // count contacts for this user
248    $sql_result = $this->db->query(
249      "SELECT COUNT(c.contact_id) AS rows
250       FROM ".$this->db_name." AS c ".$join."
251       WHERE  c.del<>1
252       AND    c.user_id=?".
253       ($this->group_id ? " AND m.contactgroup_id=?" : "").
254       ($this->filter ? " AND (".$this->filter.")" : ""),
255      $this->user_id,
256      $this->group_id);
257
258    $sql_arr = $this->db->fetch_assoc($sql_result);
259    return new rcube_result_set($sql_arr['rows'], ($this->list_page-1) * $this->page_size);;
260  }
261
262
263  /**
264   * Return the last result set
265   *
266   * @return Result array or NULL if nothing selected yet
267   */
268  function get_result()
269  {
270    return $this->result;
271  }
272 
273 
274  /**
275   * Get a specific contact record
276   *
277   * @param mixed record identifier(s)
278   * @return Result object with all record fields or False if not found
279   */
280  function get_record($id, $assoc=false)
281  {
282    // return cached result
283    if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
284      return $assoc ? $first : $this->result;
285     
286    $this->db->query(
287      "SELECT * FROM ".$this->db_name."
288       WHERE  contact_id=?
289       AND    user_id=?
290       AND    del<>1",
291      $id,
292      $this->user_id);
293
294    if ($sql_arr = $this->db->fetch_assoc())
295    {
296      $sql_arr['ID'] = $sql_arr[$this->primary_key];
297      $this->result = new rcube_result_set(1);
298      $this->result->add($sql_arr);
299    }
300
301    return $assoc && $sql_arr ? $sql_arr : $this->result;
302  }
303 
304 
305  /**
306   * Create a new contact record
307   *
308   * @param array Assoziative array with save data
309   * @return The created record ID on success, False on error
310   */
311  function insert($save_data, $check=false)
312  {
313    if (is_object($save_data) && is_a($save_data, rcube_result_set))
314      return $this->insert_recset($save_data, $check);
315
316    $insert_id = $existing = false;
317
318    if ($check)
319      $existing = $this->search('email', $save_data['email'], true, false);
320
321    $a_insert_cols = $a_insert_values = array();
322    foreach ($this->table_cols as $col)
323      if (isset($save_data[$col]))
324      {
325        $a_insert_cols[] = $this->db->quoteIdentifier($col);
326        $a_insert_values[] = $this->db->quote($save_data[$col]);
327      }
328
329    if (!$existing->count && !empty($a_insert_cols))
330    {
331      $this->db->query(
332        "INSERT INTO ".$this->db_name."
333         (user_id, changed, del, ".join(', ', $a_insert_cols).")
334         VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
335        );
336       
337      $insert_id = $this->db->insert_id('contacts');
338    }
339
340    return $insert_id;
341  }
342
343
344  /**
345   * Insert new contacts for each row in set
346   */
347  function insert_recset($result, $check=false)
348  {
349    $ids = array();
350    while ($row = $result->next())
351    {
352      if ($insert = $this->insert($row, $check))
353        $ids[] = $insert;
354    }
355    return $ids;
356  }
357 
358 
359  /**
360   * Update a specific contact record
361   *
362   * @param mixed Record identifier
363   * @param array Assoziative array with save data
364   * @return True on success, False on error
365   */
366  function update($id, $save_cols)
367  {
368    $updated = false;
369    $write_sql = array();
370    foreach ($this->table_cols as $col)
371      if (isset($save_cols[$col]))
372        $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($save_cols[$col]));
373
374    if (!empty($write_sql))
375    {
376      $this->db->query(
377        "UPDATE ".$this->db_name."
378         SET    changed=".$this->db->now().", ".join(', ', $write_sql)."
379         WHERE  contact_id=?
380         AND    user_id=?
381         AND    del<>1",
382        $id,
383        $this->user_id);
384
385      $updated = $this->db->affected_rows();
386    }
387   
388    return $updated;
389  }
390 
391 
392  /**
393   * Mark one or more contact records as deleted
394   *
395   * @param array  Record identifiers
396   */
397  function delete($ids)
398  {
399    if (is_array($ids))
400      $ids = join(',', $ids);
401
402    $this->db->query(
403      "UPDATE ".$this->db_name."
404       SET    del=1
405       WHERE  user_id=?
406       AND    contact_id IN (".$ids.")",
407      $this->user_id);
408
409    return $this->db->affected_rows();
410  }
411 
412 
413  /**
414   * Remove all records from the database
415   */
416  function delete_all()
417  {
418    $this->db->query("DELETE FROM {$this->db_name} WHERE user_id=?", $this->user_id);
419    return $this->db->affected_rows();
420  }
421
422
423  /**
424   * Create a contact group with the given name
425   *
426   * @param string The group name
427   * @return False on error, array with record props in success
428   */
429  function create_group($name)
430  {
431    $result = false;
432
433    // make sure we have a unique name
434    $name = $this->unique_groupname($name);
435   
436    $this->db->query(
437      "INSERT INTO ".get_table_name('contactgroups')." (user_id, changed, name)
438       VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
439      );
440   
441    if ($insert_id = $this->db->insert_id('contactgroups'))
442      $result = array('id' => $insert_id, 'name' => $name);
443   
444    return $result;
445  }
446
447  /**
448   * Delete the given group and all linked group members
449   *
450   * @param string Group identifier
451   * @return boolean True on success, false if no data was changed
452   */
453  function delete_group($gid)
454  {
455    $sql_result = $this->db->query(
456      "DELETE FROM ".get_table_name('contactgroupmembers')."
457       WHERE  contactgroup_id=?",
458      $gid);
459   
460    $sql_result = $this->db->query(
461      "UPDATE ".get_table_name('contactgroups')."
462       SET del=1, changed=".$this->db->now()."
463       WHERE  contactgroup_id=?",
464      $gid);
465   
466    return $this->db->affected_rows();
467  }
468 
469  /**
470   * Rename a specific contact group
471   *
472   * @param string Group identifier
473   * @param string New name to set for this group
474   * @return boolean New name on success, false if no data was changed
475   */
476  function rename_group($gid, $newname)
477  {
478    // make sure we have a unique name
479    $name = $this->unique_groupname($newname);
480   
481    $sql_result = $this->db->query(
482      "UPDATE ".get_table_name('contactgroups')."
483       SET name=".$this->db->quote($name).", changed=".$this->db->now()."
484       WHERE  contactgroup_id=?",
485      $gid);
486   
487    return $this->db->affected_rows() ? $name : false;
488  }
489
490  /**
491   * Add the given contact records the a certain group
492   *
493   * @param string  Group identifier
494   * @param array   List of contact identifiers to be added
495   */
496  function add_to_group($group_id, $ids)
497  {
498    if (!is_array($ids))
499      $ids = explode(',', $ids);
500   
501    $added = 0;
502   
503    foreach ($ids as $contact_id) {
504      $sql_result = $this->db->query(
505        "SELECT 1 FROM ".get_table_name('contactgroupmembers')."
506         WHERE  contactgroup_id=?
507         AND    contact_id=?",
508      $group_id,
509      $contact_id);
510     
511      if (!$this->db->num_rows($sql_result)) {
512        $this->db->query(
513          "INSERT INTO ".get_table_name('contactgroupmembers')." (contactgroup_id, contact_id, created)
514           VALUES (".intval($group_id).", ".intval($contact_id).", ".$this->db->now().")"
515        );
516        if (!$this->db->db_error)
517          $added++;
518      }
519    }
520   
521    return $added;
522  }
523 
524 
525  /**
526   * Remove the given contact records from a certain group
527   *
528   * @param string  Group identifier
529   * @param array   List of contact identifiers to be removed
530   */
531  function remove_from_group($group_id, $ids)
532  {
533    if (!is_array($ids))
534      $ids = explode(',', $ids);
535   
536    $sql_result = $this->db->query(
537      "DELETE FROM ".get_table_name('contactgroupmembers')."
538       WHERE  contactgroup_id=?
539       AND    contact_id IN (".join(',', array_map(array($this->db, 'quote'), $ids)).")",
540      $group_id);
541   
542    return $this->db->affected_rows();
543  }
544 
545  /**
546   * Check for existing groups with the same name
547   *
548   * @param string Name to check
549   * @return string A group name which is unique for the current use
550   */
551  private function unique_groupname($name)
552  {
553    $checkname = $name;
554    $num = 2; $hit = false;
555   
556    do {
557      $sql_result = $this->db->query(
558        "SELECT 1 FROM ".get_table_name('contactgroups')."
559         WHERE  del<>1
560         AND    user_id=?
561         AND    name LIKE ?",
562        $this->user_id,
563        $checkname);
564   
565      // append number to make name unique
566      if ($hit = $this->db->num_rows($sql_result))
567        $checkname = $name . ' ' . $num++;
568    } while ($hit > 0);
569   
570    return $checkname;
571  }
572}
Note: See TracBrowser for help on using the repository browser.