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 5873 2012-02-11 13:50:04Z thomasb $
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 $sort_col = 'name';
48 public $sort_order = 'ASC';
49 public $coltypes = array('name' => array('limit'=>1), 'firstname' => array('limit'=>1), 'surname' => array('limit'=>1), 'email' => array('limit'=>1));
54 * Returns addressbook name (e.g. for addressbooks listing)
56 abstract function get_name();
59 * Save a search string for future listings
61 * @param mixed Search params to use in listing method, obtained by get_search_set()
63 abstract function set_search_set($filter);
66 * Getter for saved search properties
68 * @return mixed Search properties used by this class
70 abstract function get_search_set();
73 * Reset saved results and search parameters
75 abstract function reset();
78 * Refresh saved search set after data has changed
80 * @return mixed New search set
82 function refresh_search()
84 return $this->get_search_set();
88 * List the current set of contact records
90 * @param array List of cols to show
91 * @param int Only return this number of records, use negative values for tail
92 * @return array Indexed list of contact records, each a hash array
94 abstract function list_records($cols=null, $subset=0);
99 * @param array List of fields to search in
100 * @param string Search value
101 * @param int Matching mode:
102 * 0 - partial (*abc*),
105 * @param boolean True if results are requested, False if count only
106 * @param boolean True to skip the count query (select only)
107 * @param array List of fields that cannot be empty
108 * @return object rcube_result_set List of contact records and 'count' value
110 abstract function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array());
113 * Count number of available contacts in database
115 * @return rcube_result_set Result set with values for 'count' and 'first'
117 abstract function count();
120 * Return the last result set
122 * @return rcube_result_set Current result set or NULL if nothing selected yet
124 abstract function get_result();
127 * Get a specific contact record
129 * @param mixed record identifier(s)
130 * @param boolean True to return record as associative array, otherwise a result set is returned
132 * @return mixed Result object with all record fields or False if not found
134 abstract function get_record($id, $assoc=false);
137 * Returns the last error occured (e.g. when updating/inserting failed)
139 * @return array Hash array with the following fields: type, message
147 * Setter for errors for internal use
149 * @param int Error type (one of this class' error constants)
150 * @param string Error message (name of a text label)
152 protected function set_error($type, $message)
154 $this->error = array('type' => $type, 'message' => $message);
158 * Close connection to source
159 * Called on script shutdown
164 * Set internal list page
166 * @param number Page number to list
169 function set_page($page)
171 $this->list_page = (int)$page;
175 * Set internal page size
177 * @param number Number of messages to display on one page
180 function set_pagesize($size)
182 $this->page_size = (int)$size;
186 * Set internal sort settings
188 * @param string $sort_col Sort column
189 * @param string $sort_order Sort order
191 function set_sort_order($sort_col, $sort_order = null)
193 if ($sort_col != null && ($this->coltypes[$sort_col] || in_array($sort_col, $this->coltypes))) {
194 $this->sort_col = $sort_col;
196 if ($sort_order != null) {
197 $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
202 * Check the given data before saving.
203 * If input isn't valid, the message to display can be fetched using get_error()
205 * @param array Assoziative array with data to save
206 * @param boolean Attempt to fix/complete record automatically
207 * @return boolean True if input is valid, False if not.
209 public function validate(&$save_data, $autofix = false)
211 // check validity of email addresses
212 foreach ($this->get_col_values('email', $save_data, true) as $email) {
213 if (strlen($email)) {
214 if (!check_email(rcube_idn_to_ascii($email))) {
215 $this->set_error(self::ERROR_VALIDATE, rcube_label(array('name' => 'emailformaterror', 'vars' => array('email' => $email))));
226 * Create a new contact record
228 * @param array Assoziative array with save data
229 * Keys: Field name with optional section in the form FIELD:SECTION
230 * Values: Field value. Can be either a string or an array of strings for multiple values
231 * @param boolean True to check for duplicates first
232 * @return mixed The created record ID on success, False on error
234 function insert($save_data, $check=false)
236 /* empty for read-only address books */
240 * Create new contact records for every item in the record set
242 * @param object rcube_result_set Recordset to insert
243 * @param boolean True to check for duplicates first
244 * @return array List of created record IDs
246 function insertMultiple($recset, $check=false)
249 if (is_object($recset) && is_a($recset, rcube_result_set)) {
250 while ($row = $recset->next()) {
251 if ($insert = $this->insert($row, $check))
259 * Update a specific contact record
261 * @param mixed Record identifier
262 * @param array Assoziative array with save data
263 * Keys: Field name with optional section in the form FIELD:SECTION
264 * Values: Field value. Can be either a string or an array of strings for multiple values
265 * @return boolean True on success, False on error
267 function update($id, $save_cols)
269 /* empty for read-only address books */
273 * Mark one or more contact records as deleted
275 * @param array Record identifiers
276 * @param bool Remove records irreversible (see self::undelete)
278 function delete($ids, $force=true)
280 /* empty for read-only address books */
284 * Unmark delete flag on contact record(s)
286 * @param array Record identifiers
288 function undelete($ids)
290 /* empty for read-only address books */
294 * Mark all records in database as deleted
296 function delete_all()
298 /* empty for read-only address books */
302 * Setter for the current group
303 * (empty, has to be re-implemented by extending class)
305 function set_group($gid) { }
308 * List all active contact groups of this source
310 * @param string Optional search string to match group name
311 * @return array Indexed list of contact groups, each a hash array
313 function list_groups($search = null)
315 /* empty for address books don't supporting groups */
320 * Get group properties such as name and email address(es)
322 * @param string Group identifier
323 * @return array Group properties as hash array
325 function get_group($group_id)
327 /* empty for address books don't supporting groups */
332 * Create a contact group with the given name
334 * @param string The group name
335 * @return mixed False on error, array with record props in success
337 function create_group($name)
339 /* empty for address books don't supporting groups */
344 * Delete the given group and all linked group members
346 * @param string Group identifier
347 * @return boolean True on success, false if no data was changed
349 function delete_group($gid)
351 /* empty for address books don't supporting groups */
356 * Rename a specific contact group
358 * @param string Group identifier
359 * @param string New name to set for this group
360 * @param string New group identifier (if changed, otherwise don't set)
361 * @return boolean New name on success, false if no data was changed
363 function rename_group($gid, $newname, &$newid)
365 /* empty for address books don't supporting groups */
370 * Add the given contact records the a certain group
372 * @param string Group identifier
373 * @param array List of contact identifiers to be added
374 * @return int Number of contacts added
376 function add_to_group($group_id, $ids)
378 /* empty for address books don't supporting groups */
383 * Remove the given contact records from a certain group
385 * @param string Group identifier
386 * @param array List of contact identifiers to be removed
387 * @return int Number of deleted group members
389 function remove_from_group($group_id, $ids)
391 /* empty for address books don't supporting groups */
396 * Get group assignments of a specific contact record
398 * @param mixed Record identifier
400 * @return array List of assigned groups as ID=>Name pairs
403 function get_record_groups($id)
405 /* empty for address books don't supporting groups */
411 * Utility function to return all values of a certain data column
412 * either as flat list or grouped by subtype
414 * @param string Col name
415 * @param array Record data array as used for saving
416 * @param boolean True to return one array with all values, False for hash array with values grouped by type
417 * @return array List of column values
419 function get_col_values($col, $data, $flat = false)
422 foreach ($data as $c => $values) {
423 if ($c === $col || strpos($c, $col.':') === 0) {
425 $out = array_merge($out, (array)$values);
428 list($f, $type) = explode(':', $c);
429 $out[$type] = array_merge((array)$out[$type], (array)$values);
439 * Normalize the given string for fulltext search.
440 * Currently only optimized for Latin-1 characters; to be extended
442 * @param string Input string (UTF-8)
443 * @return string Normalized string
445 protected static function normalize_string($str)
448 $arr = explode(" ", preg_replace(
449 array('/[\s;\+\-\/]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/'),
450 array(' ', '\\1\\2', ' '),
453 foreach ($arr as $i => $part) {
454 if (utf8_encode(utf8_decode($part)) == $part) { // is latin-1 ?
455 $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
456 'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
457 'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
458 array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
461 $arr[$i] = mb_strtolower($part);
464 return join(" ", $arr);
469 * Compose a valid display name from the given structured contact data
471 * @param array Hash array with contact data as key-value pairs
472 * @param bool Don't attempt to extract components from the email address
474 * @return string Display name
476 public static function compose_display_name($contact, $full_email = false)
478 $contact = rcmail::get_instance()->plugins->exec_hook('contact_displayname', $contact);
479 $fn = $contact['name'];
481 if (!$fn) // default display name composition according to vcard standard
482 $fn = join(' ', array_filter(array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix'])));
484 // use email address part for name
485 $email = is_array($contact['email']) ? $contact['email'][0] : $contact['email'];
487 if ($email && (empty($fn) || $fn == $email)) {
492 list($emailname) = explode('@', $email);
493 if (preg_match('/(.*)[\.\-\_](.*)/', $emailname, $match))
494 $fn = trim(ucfirst($match[1]).' '.ucfirst($match[2]));
496 $fn = ucfirst($emailname);
504 * Compose the name to display in the contacts list for the given contact record.
505 * This respects the settings parameter how to list conacts.
507 * @param array Hash array with contact data as key-value pairs
508 * @return string List name
510 public static function compose_list_name($contact)
512 static $compose_mode;
514 if (!isset($compose_mode)) // cache this
515 $compose_mode = rcmail::get_instance()->config->get('addressbook_name_listing', 0);
517 if ($compose_mode == 3)
518 $fn = join(' ', array($contact['surname'] . ',', $contact['firstname'], $contact['middlename']));
519 else if ($compose_mode == 2)
520 $fn = join(' ', array($contact['surname'], $contact['firstname'], $contact['middlename']));
521 else if ($compose_mode == 1)
522 $fn = join(' ', array($contact['firstname'], $contact['middlename'], $contact['surname']));
524 $fn = !empty($contact['name']) ? $contact['name'] : join(' ', array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix']));
526 $fn = trim($fn, ', ');
528 // fallback to display name
529 if (empty($fn) && $contact['name'])
530 $fn = $contact['name'];
532 // fallback to email address
533 $email = is_array($contact['email']) ? $contact['email'][0] : $contact['email'];
534 if (empty($fn) && $email)