source: github/program/include/rcube_contacts.php @ 8e3a603

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 8e3a603 was 8e3a603, checked in by thomascube <thomas@…>, 3 years ago

Assign newly created contacts to the active group (#1486626) and fix group selection display (#1486619)

  • Property mode set to 100644
File size: 15.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-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    // delete all group members linked with these contacts
407    if ($this->groups) {
408      $this->db->query(
409        "DELETE FROM ".get_table_name('contactgroupmembers')."
410         WHERE  contact_id IN (".$ids.")");
411    }
412
413    $this->db->query(
414      "UPDATE ".$this->db_name."
415       SET    del=1
416       WHERE  user_id=?
417       AND    contact_id IN (".$ids.")",
418      $this->user_id);
419
420    return $this->db->affected_rows();
421  }
422 
423 
424  /**
425   * Remove all records from the database
426   */
427  function delete_all()
428  {
429    $this->db->query("DELETE FROM {$this->db_name} WHERE user_id=?", $this->user_id);
430    return $this->db->affected_rows();
431  }
432
433
434  /**
435   * Create a contact group with the given name
436   *
437   * @param string The group name
438   * @return False on error, array with record props in success
439   */
440  function create_group($name)
441  {
442    $result = false;
443
444    // make sure we have a unique name
445    $name = $this->unique_groupname($name);
446   
447    $this->db->query(
448      "INSERT INTO ".get_table_name('contactgroups')." (user_id, changed, name)
449       VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
450      );
451   
452    if ($insert_id = $this->db->insert_id('contactgroups'))
453      $result = array('id' => $insert_id, 'name' => $name);
454   
455    return $result;
456  }
457
458  /**
459   * Delete the given group and all linked group members
460   *
461   * @param string Group identifier
462   * @return boolean True on success, false if no data was changed
463   */
464  function delete_group($gid)
465  {
466    $sql_result = $this->db->query(
467      "DELETE FROM ".get_table_name('contactgroupmembers')."
468       WHERE  contactgroup_id=?",
469      $gid);
470   
471    $sql_result = $this->db->query(
472      "UPDATE ".get_table_name('contactgroups')."
473       SET del=1, changed=".$this->db->now()."
474       WHERE  contactgroup_id=?",
475      $gid);
476   
477    return $this->db->affected_rows();
478  }
479 
480  /**
481   * Rename a specific contact group
482   *
483   * @param string Group identifier
484   * @param string New name to set for this group
485   * @return boolean New name on success, false if no data was changed
486   */
487  function rename_group($gid, $newname)
488  {
489    // make sure we have a unique name
490    $name = $this->unique_groupname($newname);
491   
492    $sql_result = $this->db->query(
493      "UPDATE ".get_table_name('contactgroups')."
494       SET name=".$this->db->quote($name).", changed=".$this->db->now()."
495       WHERE  contactgroup_id=?",
496      $gid);
497   
498    return $this->db->affected_rows() ? $name : false;
499  }
500
501  /**
502   * Add the given contact records the a certain group
503   *
504   * @param string  Group identifier
505   * @param array   List of contact identifiers to be added
506   * @return int    Number of contacts added
507   */
508  function add_to_group($group_id, $ids)
509  {
510    if (!is_array($ids))
511      $ids = explode(',', $ids);
512   
513    $added = 0;
514   
515    foreach ($ids as $contact_id) {
516      $sql_result = $this->db->query(
517        "SELECT 1 FROM ".get_table_name('contactgroupmembers')."
518         WHERE  contactgroup_id=?
519         AND    contact_id=?",
520      $group_id,
521      $contact_id);
522     
523      if (!$this->db->num_rows($sql_result)) {
524        $this->db->query(
525          "INSERT INTO ".get_table_name('contactgroupmembers')." (contactgroup_id, contact_id, created)
526           VALUES (".intval($group_id).", ".intval($contact_id).", ".$this->db->now().")"
527        );
528        if (!$this->db->db_error)
529          $added++;
530      }
531    }
532   
533    return $added;
534  }
535 
536 
537  /**
538   * Remove the given contact records from a certain group
539   *
540   * @param string  Group identifier
541   * @param array   List of contact identifiers to be removed
542   * @return int    Number of deleted group members
543   */
544  function remove_from_group($group_id, $ids)
545  {
546    if (!is_array($ids))
547      $ids = explode(',', $ids);
548   
549    $sql_result = $this->db->query(
550      "DELETE FROM ".get_table_name('contactgroupmembers')."
551       WHERE  contactgroup_id=?
552       AND    contact_id IN (".join(',', array_map(array($this->db, 'quote'), $ids)).")",
553      $group_id);
554   
555    return $this->db->affected_rows();
556  }
557 
558  /**
559   * Check for existing groups with the same name
560   *
561   * @param string Name to check
562   * @return string A group name which is unique for the current use
563   */
564  private function unique_groupname($name)
565  {
566    $checkname = $name;
567    $num = 2; $hit = false;
568   
569    do {
570      $sql_result = $this->db->query(
571        "SELECT 1 FROM ".get_table_name('contactgroups')."
572         WHERE  del<>1
573         AND    user_id=?
574         AND    name LIKE ?",
575        $this->user_id,
576        $checkname);
577   
578      // append number to make name unique
579      if ($hit = $this->db->num_rows($sql_result))
580        $checkname = $name . ' ' . $num++;
581    } while ($hit > 0);
582   
583    return $checkname;
584  }
585}
Note: See TracBrowser for help on using the repository browser.