alecpl
2011-12-29 08ffd939a7530c44cd68b455f75175f79698073c
commit | author | age
cc97ea 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_addressbook.php                                 |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
0501b6 8  | Copyright (C) 2006-2011, The Roundcube Dev Team                       |
cc97ea 9  | Licensed under the GNU GPL                                            |
T 10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Interface to the local address book database                        |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
1d786c 18  $Id$
cc97ea 19
T 20 */
21
22
23 /**
24  * Abstract skeleton of an address book/repository
25  *
26  * @package Addressbook
27  */
28 abstract class rcube_addressbook
29 {
0501b6 30     /** constants for error reporting **/
T 31     const ERROR_READ_ONLY = 1;
32     const ERROR_NO_CONNECTION = 2;
39cafa 33     const ERROR_VALIDATE = 3;
0501b6 34     const ERROR_SAVING = 4;
3e2637 35     const ERROR_SEARCH = 5;
cc90ed 36
0501b6 37     /** public properties (mandatory) */
T 38     public $primary_key;
39     public $groups = false;
40     public $readonly = true;
2d3e2b 41     public $searchonly = false;
7f5a84 42     public $undelete = false;
0501b6 43     public $ready = false;
06670e 44     public $group_id = null;
0501b6 45     public $list_page = 1;
T 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));
cc90ed 48
0501b6 49     protected $error;
cc90ed 50
A 51     /**
52      * Returns addressbook name (e.g. for addressbooks listing)
53      */
54     abstract function get_name();
cc97ea 55
T 56     /**
57      * Save a search string for future listings
58      *
59      * @param mixed Search params to use in listing method, obtained by get_search_set()
60      */
61     abstract function set_search_set($filter);
62
63     /**
64      * Getter for saved search properties
65      *
66      * @return mixed Search properties used by this class
67      */
68     abstract function get_search_set();
69
70     /**
71      * Reset saved results and search parameters
72      */
73     abstract function reset();
74
75     /**
0501b6 76      * Refresh saved search set after data has changed
T 77      *
78      * @return mixed New search set
79      */
80     function refresh_search()
81     {
82         return $this->get_search_set();
83     }
84
85     /**
cc97ea 86      * List the current set of contact records
T 87      *
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
91      */
92     abstract function list_records($cols=null, $subset=0);
a61bbb 93
T 94     /**
cc97ea 95      * Search records
T 96      *
97      * @param array   List of fields to search in
98      * @param string  Search value
f21a04 99      * @param int     Matching mode:
A 100      *                0 - partial (*abc*),
101      *                1 - strict (=),
102      *                2 - prefix (abc*)
cc97ea 103      * @param boolean True if results are requested, False if count only
0501b6 104      * @param boolean True to skip the count query (select only)
T 105      * @param array   List of fields that cannot be empty
106      * @return object rcube_result_set List of contact records and 'count' value
cc97ea 107      */
f21a04 108     abstract function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array());
cc97ea 109
T 110     /**
111      * Count number of available contacts in database
112      *
5c461b 113      * @return rcube_result_set Result set with values for 'count' and 'first'
cc97ea 114      */
T 115     abstract function count();
116
117     /**
118      * Return the last result set
119      *
5c461b 120      * @return rcube_result_set Current result set or NULL if nothing selected yet
cc97ea 121      */
T 122     abstract function get_result();
123
124     /**
125      * Get a specific contact record
126      *
127      * @param mixed record identifier(s)
128      * @param boolean True to return record as associative array, otherwise a result set is returned
b393e5 129      *
cc97ea 130      * @return mixed Result object with all record fields or False if not found
T 131      */
132     abstract function get_record($id, $assoc=false);
0501b6 133
T 134     /**
135      * Returns the last error occured (e.g. when updating/inserting failed)
136      *
137      * @return array Hash array with the following fields: type, message
138      */
139     function get_error()
140     {
141       return $this->error;
142     }
cc90ed 143
0501b6 144     /**
T 145      * Setter for errors for internal use
146      *
147      * @param int Error type (one of this class' error constants)
148      * @param string Error message (name of a text label)
149      */
150     protected function set_error($type, $message)
151     {
152       $this->error = array('type' => $type, 'message' => $message);
153     }
cc97ea 154
T 155     /**
156      * Close connection to source
157      * Called on script shutdown
158      */
159     function close() { }
160
161     /**
162      * Set internal list page
163      *
164      * @param  number  Page number to list
165      * @access public
166      */
167     function set_page($page)
168     {
2eb794 169         $this->list_page = (int)$page;
cc97ea 170     }
T 171
172     /**
173      * Set internal page size
174      *
175      * @param  number  Number of messages to display on one page
176      * @access public
177      */
178     function set_pagesize($size)
179     {
2eb794 180         $this->page_size = (int)$size;
cc97ea 181     }
a61bbb 182
07b95d 183
T 184     /**
185      * Check the given data before saving.
e84818 186      * If input isn't valid, the message to display can be fetched using get_error()
07b95d 187      *
T 188      * @param array Assoziative array with data to save
39cafa 189      * @param boolean Attempt to fix/complete record automatically
07b95d 190      * @return boolean True if input is valid, False if not.
T 191      */
39cafa 192     public function validate(&$save_data, $autofix = false)
07b95d 193     {
T 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))) {
39cafa 198                     $this->set_error(self::ERROR_VALIDATE, rcube_label(array('name' => 'emailformaterror', 'vars' => array('email' => $email))));
07b95d 199                     return false;
T 200                 }
201             }
202         }
203
204         return true;
205     }
206
207
a61bbb 208     /**
cc97ea 209      * Create a new contact record
T 210      *
211      * @param array Assoziative array with save data
0501b6 212      *  Keys:   Field name with optional section in the form FIELD:SECTION
T 213      *  Values: Field value. Can be either a string or an array of strings for multiple values
cc97ea 214      * @param boolean True to check for duplicates first
5c461b 215      * @return mixed The created record ID on success, False on error
cc97ea 216      */
T 217     function insert($save_data, $check=false)
218     {
2eb794 219         /* empty for read-only address books */
cc97ea 220     }
T 221
222     /**
0501b6 223      * Create new contact records for every item in the record set
T 224      *
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
228      */
229     function insertMultiple($recset, $check=false)
230     {
231         $ids = array();
232         if (is_object($recset) && is_a($recset, rcube_result_set)) {
233             while ($row = $recset->next()) {
234                 if ($insert = $this->insert($row, $check))
235                     $ids[] = $insert;
236             }
237         }
238         return $ids;
239     }
240
241     /**
cc97ea 242      * Update a specific contact record
T 243      *
244      * @param mixed Record identifier
245      * @param array Assoziative array with save data
0501b6 246      *  Keys:   Field name with optional section in the form FIELD:SECTION
T 247      *  Values: Field value. Can be either a string or an array of strings for multiple values
5c461b 248      * @return boolean True on success, False on error
cc97ea 249      */
T 250     function update($id, $save_cols)
251     {
2eb794 252         /* empty for read-only address books */
cc97ea 253     }
T 254
255     /**
256      * Mark one or more contact records as deleted
257      *
258      * @param array  Record identifiers
63fda8 259      * @param bool   Remove records irreversible (see self::undelete)
cc97ea 260      */
63fda8 261     function delete($ids, $force=true)
cc97ea 262     {
2eb794 263         /* empty for read-only address books */
cc97ea 264     }
T 265
266     /**
7f5a84 267      * Unmark delete flag on contact record(s)
A 268      *
269      * @param array  Record identifiers
270      */
271     function undelete($ids)
272     {
273         /* empty for read-only address books */
274     }
275
276     /**
277      * Mark all records in database as deleted
cc97ea 278      */
T 279     function delete_all()
280     {
2eb794 281         /* empty for read-only address books */
cc97ea 282     }
T 283
04adaa 284     /**
b393e5 285      * Setter for the current group
A 286      * (empty, has to be re-implemented by extending class)
287      */
288     function set_group($gid) { }
289
290     /**
291      * List all active contact groups of this source
292      *
0501b6 293      * @param string  Optional search string to match group name
b393e5 294      * @return array  Indexed list of contact groups, each a hash array
A 295      */
0501b6 296     function list_groups($search = null)
b393e5 297     {
A 298         /* empty for address books don't supporting groups */
299         return array();
300     }
301
302     /**
dc6c4f 303      * Get group properties such as name and email address(es)
T 304      *
305      * @param string Group identifier
306      * @return array Group properties as hash array
307      */
308     function get_group($group_id)
309     {
310         /* empty for address books don't supporting groups */
311         return null;
312     }
313
314     /**
04adaa 315      * Create a contact group with the given name
T 316      *
317      * @param string The group name
5c461b 318      * @return mixed False on error, array with record props in success
04adaa 319      */
T 320     function create_group($name)
321     {
2eb794 322         /* empty for address books don't supporting groups */
A 323         return false;
04adaa 324     }
b393e5 325
04adaa 326     /**
T 327      * Delete the given group and all linked group members
328      *
329      * @param string Group identifier
330      * @return boolean True on success, false if no data was changed
331      */
332     function delete_group($gid)
333     {
2eb794 334         /* empty for address books don't supporting groups */
A 335         return false;
04adaa 336     }
b393e5 337
04adaa 338     /**
T 339      * Rename a specific contact group
340      *
341      * @param string Group identifier
342      * @param string New name to set for this group
360bd3 343      * @param string New group identifier (if changed, otherwise don't set)
04adaa 344      * @return boolean New name on success, false if no data was changed
T 345      */
360bd3 346     function rename_group($gid, $newname, &$newid)
04adaa 347     {
2eb794 348         /* empty for address books don't supporting groups */
A 349         return false;
04adaa 350     }
b393e5 351
04adaa 352     /**
T 353      * Add the given contact records the a certain group
354      *
355      * @param string  Group identifier
356      * @param array   List of contact identifiers to be added
b393e5 357      * @return int    Number of contacts added
04adaa 358      */
T 359     function add_to_group($group_id, $ids)
360     {
2eb794 361         /* empty for address books don't supporting groups */
A 362         return 0;
04adaa 363     }
b393e5 364
04adaa 365     /**
T 366      * Remove the given contact records from a certain group
367      *
368      * @param string  Group identifier
369      * @param array   List of contact identifiers to be removed
370      * @return int    Number of deleted group members
371      */
372     function remove_from_group($group_id, $ids)
373     {
2eb794 374         /* empty for address books don't supporting groups */
A 375         return 0;
04adaa 376     }
b393e5 377
A 378     /**
379      * Get group assignments of a specific contact record
380      *
381      * @param mixed Record identifier
382      *
383      * @return array List of assigned groups as ID=>Name pairs
384      * @since 0.5-beta
385      */
386     function get_record_groups($id)
387     {
388         /* empty for address books don't supporting groups */
389         return array();
390     }
0501b6 391
T 392
393     /**
394      * Utility function to return all values of a certain data column
395      * either as flat list or grouped by subtype
396      *
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
401      */
402     function get_col_values($col, $data, $flat = false)
403     {
404         $out = array();
405         foreach ($data as $c => $values) {
bed577 406             if ($c === $col || strpos($c, $col.':') === 0) {
0501b6 407                 if ($flat) {
T 408                     $out = array_merge($out, (array)$values);
409                 }
410                 else {
411                     list($f, $type) = explode(':', $c);
412                     $out[$type] = array_merge((array)$out[$type], (array)$values);
413                 }
414             }
415         }
cc90ed 416
0501b6 417         return $out;
T 418     }
3e2637 419
T 420
421     /**
422      * Normalize the given string for fulltext search.
423      * Currently only optimized for Latin-1 characters; to be extended
424      *
425      * @param string Input string (UTF-8)
426      * @return string Normalized string
427      */
428     protected static function normalize_string($str)
429     {
12dac4 430         // split by words
T 431         $arr = explode(" ", preg_replace(
432             array('/[\s;\+\-\/]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/'),
3e2637 433             array(' ', '\\1\\2', ' '),
12dac4 434             $str));
cc90ed 435
12dac4 436         foreach ($arr as $i => $part) {
T 437             if (utf8_encode(utf8_decode($part)) == $part) {  // is latin-1 ?
e5e1eb 438                 $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
12dac4 439                     'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
T 440                     'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
e5e1eb 441                     array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
12dac4 442             }
T 443             else
34d728 444                 $arr[$i] = mb_strtolower($part);
12dac4 445         }
cc90ed 446
12dac4 447         return join(" ", $arr);
3e2637 448     }
e84818 449
T 450
451     /**
452      * Compose a valid display name from the given structured contact data
453      *
454      * @param array  Hash array with contact data as key-value pairs
71e8cc 455      * @param bool   The name will be used on the list
A 456      *
e84818 457      * @return string Display name
T 458      */
71e8cc 459     public static function compose_display_name($contact, $list_mode = false)
e84818 460     {
T 461         $contact = rcmail::get_instance()->plugins->exec_hook('contact_displayname', $contact);
462         $fn = $contact['name'];
463
464         if (!$fn)
465             $fn = join(' ', array_filter(array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix'])));
466
467         // use email address part for name
468         $email = is_array($contact['email']) ? $contact['email'][0] : $contact['email'];
71e8cc 469
e84818 470         if ($email && (empty($fn) || $fn == $email)) {
71e8cc 471             // Use full email address on contacts list
A 472             if ($list_mode)
473                 return $email;
474
e84818 475             list($emailname) = explode('@', $email);
T 476             if (preg_match('/(.*)[\.\-\_](.*)/', $emailname, $match))
477                 $fn = trim(ucfirst($match[1]).' '.ucfirst($match[2]));
478             else
479                 $fn = ucfirst($emailname);
480         }
481
482         return $fn;
483     }
484
cc97ea 485 }
b393e5 486