4 +-----------------------------------------------------------------------+
5 | program/include/rcube_addressbook.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2006-2011, The Roundcube Dev Team |
9 | Licensed under the GNU GPL |
12 | Interface to the local address book database |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: rcube_addressbook.php 5415 2011-11-11 15:04:45Z alec $
24 * Abstract skeleton of an address book/repository
26 * @package Addressbook
28 abstract class rcube_addressbook
30 /** constants for error reporting **/
31 const ERROR_READ_ONLY = 1;
32 const ERROR_NO_CONNECTION = 2;
33 const ERROR_VALIDATE = 3;
34 const ERROR_SAVING = 4;
35 const ERROR_SEARCH = 5;
37 /** public properties (mandatory) */
39 public $groups = false;
40 public $readonly = true;
41 public $searchonly = false;
42 public $undelete = false;
43 public $ready = false;
44 public $group_id = null;
45 public $list_page = 1;
46 public $page_size = 10;
47 public $coltypes = array('name' => array('limit'=>1), 'firstname' => array('limit'=>1), 'surname' => array('limit'=>1), 'email' => array('limit'=>1));
52 * Returns addressbook name (e.g. for addressbooks listing)
54 abstract function get_name();
57 * Save a search string for future listings
59 * @param mixed Search params to use in listing method, obtained by get_search_set()
61 abstract function set_search_set($filter);
64 * Getter for saved search properties
66 * @return mixed Search properties used by this class
68 abstract function get_search_set();
71 * Reset saved results and search parameters
73 abstract function reset();
76 * Refresh saved search set after data has changed
78 * @return mixed New search set
80 function refresh_search()
82 return $this->get_search_set();
86 * List the current set of contact records
88 * @param array List of cols to show
89 * @param int Only return this number of records, use negative values for tail
90 * @return array Indexed list of contact records, each a hash array
92 abstract function list_records($cols=null, $subset=0);
97 * @param array List of fields to search in
98 * @param string Search value
99 * @param int Matching mode:
100 * 0 - partial (*abc*),
103 * @param boolean True if results are requested, False if count only
104 * @param boolean True to skip the count query (select only)
105 * @param array List of fields that cannot be empty
106 * @return object rcube_result_set List of contact records and 'count' value
108 abstract function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array());
111 * Count number of available contacts in database
113 * @return rcube_result_set Result set with values for 'count' and 'first'
115 abstract function count();
118 * Return the last result set
120 * @return rcube_result_set Current result set or NULL if nothing selected yet
122 abstract function get_result();
125 * Get a specific contact record
127 * @param mixed record identifier(s)
128 * @param boolean True to return record as associative array, otherwise a result set is returned
130 * @return mixed Result object with all record fields or False if not found
132 abstract function get_record($id, $assoc=false);
135 * Returns the last error occured (e.g. when updating/inserting failed)
137 * @return array Hash array with the following fields: type, message
145 * Setter for errors for internal use
147 * @param int Error type (one of this class' error constants)
148 * @param string Error message (name of a text label)
150 protected function set_error($type, $message)
152 $this->error = array('type' => $type, 'message' => $message);
156 * Close connection to source
157 * Called on script shutdown
162 * Set internal list page
164 * @param number Page number to list
167 function set_page($page)
169 $this->list_page = (int)$page;
173 * Set internal page size
175 * @param number Number of messages to display on one page
178 function set_pagesize($size)
180 $this->page_size = (int)$size;
185 * Check the given data before saving.
186 * If input isn't valid, the message to display can be fetched using get_error()
188 * @param array Assoziative array with data to save
189 * @param boolean Attempt to fix/complete record automatically
190 * @return boolean True if input is valid, False if not.
192 public function validate(&$save_data, $autofix = false)
194 // check validity of email addresses
195 foreach ($this->get_col_values('email', $save_data, true) as $email) {
196 if (strlen($email)) {
197 if (!check_email(rcube_idn_to_ascii($email))) {
198 $this->set_error(self::ERROR_VALIDATE, rcube_label(array('name' => 'emailformaterror', 'vars' => array('email' => $email))));
209 * Create a new contact record
211 * @param array Assoziative array with save data
212 * Keys: Field name with optional section in the form FIELD:SECTION
213 * Values: Field value. Can be either a string or an array of strings for multiple values
214 * @param boolean True to check for duplicates first
215 * @return mixed The created record ID on success, False on error
217 function insert($save_data, $check=false)
219 /* empty for read-only address books */
223 * Create new contact records for every item in the record set
225 * @param object rcube_result_set Recordset to insert
226 * @param boolean True to check for duplicates first
227 * @return array List of created record IDs
229 function insertMultiple($recset, $check=false)
232 if (is_object($recset) && is_a($recset, rcube_result_set)) {
233 while ($row = $recset->next()) {
234 if ($insert = $this->insert($row, $check))
242 * Update a specific contact record
244 * @param mixed Record identifier
245 * @param array Assoziative array with save data
246 * Keys: Field name with optional section in the form FIELD:SECTION
247 * Values: Field value. Can be either a string or an array of strings for multiple values
248 * @return boolean True on success, False on error
250 function update($id, $save_cols)
252 /* empty for read-only address books */
256 * Mark one or more contact records as deleted
258 * @param array Record identifiers
259 * @param bool Remove records irreversible (see self::undelete)
261 function delete($ids, $force=true)
263 /* empty for read-only address books */
267 * Unmark delete flag on contact record(s)
269 * @param array Record identifiers
271 function undelete($ids)
273 /* empty for read-only address books */
277 * Mark all records in database as deleted
279 function delete_all()
281 /* empty for read-only address books */
285 * Setter for the current group
286 * (empty, has to be re-implemented by extending class)
288 function set_group($gid) { }
291 * List all active contact groups of this source
293 * @param string Optional search string to match group name
294 * @return array Indexed list of contact groups, each a hash array
296 function list_groups($search = null)
298 /* empty for address books don't supporting groups */
303 * Get group properties such as name and email address(es)
305 * @param string Group identifier
306 * @return array Group properties as hash array
308 function get_group($group_id)
310 /* empty for address books don't supporting groups */
315 * Create a contact group with the given name
317 * @param string The group name
318 * @return mixed False on error, array with record props in success
320 function create_group($name)
322 /* empty for address books don't supporting groups */
327 * Delete the given group and all linked group members
329 * @param string Group identifier
330 * @return boolean True on success, false if no data was changed
332 function delete_group($gid)
334 /* empty for address books don't supporting groups */
339 * Rename a specific contact group
341 * @param string Group identifier
342 * @param string New name to set for this group
343 * @param string New group identifier (if changed, otherwise don't set)
344 * @return boolean New name on success, false if no data was changed
346 function rename_group($gid, $newname, &$newid)
348 /* empty for address books don't supporting groups */
353 * Add the given contact records the a certain group
355 * @param string Group identifier
356 * @param array List of contact identifiers to be added
357 * @return int Number of contacts added
359 function add_to_group($group_id, $ids)
361 /* empty for address books don't supporting groups */
366 * Remove the given contact records from a certain group
368 * @param string Group identifier
369 * @param array List of contact identifiers to be removed
370 * @return int Number of deleted group members
372 function remove_from_group($group_id, $ids)
374 /* empty for address books don't supporting groups */
379 * Get group assignments of a specific contact record
381 * @param mixed Record identifier
383 * @return array List of assigned groups as ID=>Name pairs
386 function get_record_groups($id)
388 /* empty for address books don't supporting groups */
394 * Utility function to return all values of a certain data column
395 * either as flat list or grouped by subtype
397 * @param string Col name
398 * @param array Record data array as used for saving
399 * @param boolean True to return one array with all values, False for hash array with values grouped by type
400 * @return array List of column values
402 function get_col_values($col, $data, $flat = false)
405 foreach ($data as $c => $values) {
406 if ($c === $col || strpos($c, $col.':') === 0) {
408 $out = array_merge($out, (array)$values);
411 list($f, $type) = explode(':', $c);
412 $out[$type] = array_merge((array)$out[$type], (array)$values);
422 * Normalize the given string for fulltext search.
423 * Currently only optimized for Latin-1 characters; to be extended
425 * @param string Input string (UTF-8)
426 * @return string Normalized string
428 protected static function normalize_string($str)
431 $arr = explode(" ", preg_replace(
432 array('/[\s;\+\-\/]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/'),
433 array(' ', '\\1\\2', ' '),
436 foreach ($arr as $i => $part) {
437 if (utf8_encode(utf8_decode($part)) == $part) { // is latin-1 ?
438 $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
439 'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
440 'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
441 array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
444 $arr[$i] = mb_strtolower($part);
447 return join(" ", $arr);
452 * Compose a valid display name from the given structured contact data
454 * @param array Hash array with contact data as key-value pairs
455 * @param bool The name will be used on the list
457 * @return string Display name
459 public static function compose_display_name($contact, $list_mode = false)
461 $contact = rcmail::get_instance()->plugins->exec_hook('contact_displayname', $contact);
462 $fn = $contact['name'];
465 $fn = join(' ', array_filter(array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix'])));
467 // use email address part for name
468 $email = is_array($contact['email']) ? $contact['email'][0] : $contact['email'];
470 if ($email && (empty($fn) || $fn == $email)) {
471 // Use full email address on contacts list
475 list($emailname) = explode('@', $email);
476 if (preg_match('/(.*)[\.\-\_](.*)/', $emailname, $match))
477 $fn = trim(ucfirst($match[1]).' '.ucfirst($match[2]));
479 $fn = ucfirst($emailname);