source: github/program/include/rcube_contacts.php @ a61bbb2

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

Added basic contact groups feature

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