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

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

Always set changed date when marking a DB record as deleted + provide a cleanup script

  • Property svn:keywords set to Id
File size: 15.2 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[] = 'c.' . $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    // also add the newly created contact to the active group
341    if ($insert_id && $this->group_id)
342      $this->add_to_group($this->group_id, $insert_id);
343
344    return $insert_id;
345  }
346
347
348  /**
349   * Insert new contacts for each row in set
350   */
351  function insert_recset($result, $check=false)
352  {
353    $ids = array();
354    while ($row = $result->next())
355    {
356      if ($insert = $this->insert($row, $check))
357        $ids[] = $insert;
358    }
359    return $ids;
360  }
361 
362 
363  /**
364   * Update a specific contact record
365   *
366   * @param mixed Record identifier
367   * @param array Assoziative array with save data
368   * @return True on success, False on error
369   */
370  function update($id, $save_cols)
371  {
372    $updated = false;
373    $write_sql = array();
374    foreach ($this->table_cols as $col)
375      if (isset($save_cols[$col]))
376        $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($save_cols[$col]));
377
378    if (!empty($write_sql))
379    {
380      $this->db->query(
381        "UPDATE ".$this->db_name."
382         SET    changed=".$this->db->now().", ".join(', ', $write_sql)."
383         WHERE  contact_id=?
384         AND    user_id=?
385         AND    del<>1",
386        $id,
387        $this->user_id);
388
389      $updated = $this->db->affected_rows();
390    }
391   
392    return $updated;
393  }
394 
395 
396  /**
397   * Mark one or more contact records as deleted
398   *
399   * @param array  Record identifiers
400   */
401  function delete($ids)
402  {
403    if (is_array($ids))
404      $ids = join(',', $ids);
405
406    // flag record as deleted
407    $this->db->query(
408      "UPDATE ".$this->db_name."
409       SET    del=1, changed=".$this->db->now()."
410       WHERE  user_id=?
411       AND    contact_id IN (".$ids.")",
412      $this->user_id);
413
414    return $this->db->affected_rows();
415  }
416 
417 
418  /**
419   * Remove all records from the database
420   */
421  function delete_all()
422  {
423    $this->db->query("DELETE FROM {$this->db_name} WHERE user_id=?", $this->user_id);
424    return $this->db->affected_rows();
425  }
426
427
428  /**
429   * Create a contact group with the given name
430   *
431   * @param string The group name
432   * @return False on error, array with record props in success
433   */
434  function create_group($name)
435  {
436    $result = false;
437
438    // make sure we have a unique name
439    $name = $this->unique_groupname($name);
440   
441    $this->db->query(
442      "INSERT INTO ".get_table_name('contactgroups')." (user_id, changed, name)
443       VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
444      );
445   
446    if ($insert_id = $this->db->insert_id('contactgroups'))
447      $result = array('id' => $insert_id, 'name' => $name);
448   
449    return $result;
450  }
451
452  /**
453   * Delete the given group (and all linked group members)
454   *
455   * @param string Group identifier
456   * @return boolean True on success, false if no data was changed
457   */
458  function delete_group($gid)
459  {
460    // flag group record as deleted
461    $sql_result = $this->db->query(
462      "UPDATE ".get_table_name('contactgroups')."
463       SET del=1, changed=".$this->db->now()."
464       WHERE  contactgroup_id=?",
465      $gid);
466   
467    return $this->db->affected_rows();
468  }
469 
470  /**
471   * Rename a specific contact group
472   *
473   * @param string Group identifier
474   * @param string New name to set for this group
475   * @return boolean New name on success, false if no data was changed
476   */
477  function rename_group($gid, $newname)
478  {
479    // make sure we have a unique name
480    $name = $this->unique_groupname($newname);
481   
482    $sql_result = $this->db->query(
483      "UPDATE ".get_table_name('contactgroups')."
484       SET name=".$this->db->quote($name).", changed=".$this->db->now()."
485       WHERE  contactgroup_id=?",
486      $gid);
487   
488    return $this->db->affected_rows() ? $name : false;
489  }
490
491  /**
492   * Add the given contact records the a certain group
493   *
494   * @param string  Group identifier
495   * @param array   List of contact identifiers to be added
496   * @return int    Number of contacts added
497   */
498  function add_to_group($group_id, $ids)
499  {
500    if (!is_array($ids))
501      $ids = explode(',', $ids);
502   
503    $added = 0;
504   
505    foreach ($ids as $contact_id) {
506      $sql_result = $this->db->query(
507        "SELECT 1 FROM ".get_table_name('contactgroupmembers')."
508         WHERE  contactgroup_id=?
509         AND    contact_id=?",
510      $group_id,
511      $contact_id);
512     
513      if (!$this->db->num_rows($sql_result)) {
514        $this->db->query(
515          "INSERT INTO ".get_table_name('contactgroupmembers')." (contactgroup_id, contact_id, created)
516           VALUES (".intval($group_id).", ".intval($contact_id).", ".$this->db->now().")"
517        );
518        if (!$this->db->db_error)
519          $added++;
520      }
521    }
522   
523    return $added;
524  }
525 
526 
527  /**
528   * Remove the given contact records from a certain group
529   *
530   * @param string  Group identifier
531   * @param array   List of contact identifiers to be removed
532   * @return int    Number of deleted group members
533   */
534  function remove_from_group($group_id, $ids)
535  {
536    if (!is_array($ids))
537      $ids = explode(',', $ids);
538   
539    $sql_result = $this->db->query(
540      "DELETE FROM ".get_table_name('contactgroupmembers')."
541       WHERE  contactgroup_id=?
542       AND    contact_id IN (".join(',', array_map(array($this->db, 'quote'), $ids)).")",
543      $group_id);
544   
545    return $this->db->affected_rows();
546  }
547 
548  /**
549   * Check for existing groups with the same name
550   *
551   * @param string Name to check
552   * @return string A group name which is unique for the current use
553   */
554  private function unique_groupname($name)
555  {
556    $checkname = $name;
557    $num = 2; $hit = false;
558   
559    do {
560      $sql_result = $this->db->query(
561        "SELECT 1 FROM ".get_table_name('contactgroups')."
562         WHERE  del<>1
563         AND    user_id=?
564         AND    name LIKE ?",
565        $this->user_id,
566        $checkname);
567   
568      // append number to make name unique
569      if ($hit = $this->db->num_rows($sql_result))
570        $checkname = $name . ' ' . $num++;
571    } while ($hit > 0);
572   
573    return $checkname;
574  }
575}
Note: See TracBrowser for help on using the repository browser.