]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_addressbook.php
Imported Upstream version 0.7
[roundcube.git] / program / include / rcube_addressbook.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_addressbook.php                                 |
6  |                                                                       |
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                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Interface to the local address book database                        |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: rcube_addressbook.php 5415 2011-11-11 15:04:45Z alec $
19
20 */
21
22
23 /**
24  * Abstract skeleton of an address book/repository
25  *
26  * @package Addressbook
27  */
28 abstract class rcube_addressbook
29 {
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;
36
37     /** public properties (mandatory) */
38     public $primary_key;
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));
48
49     protected $error;
50
51     /**
52      * Returns addressbook name (e.g. for addressbooks listing)
53      */
54     abstract function get_name();
55
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     /**
76      * Refresh saved search set after data has changed
77      *
78      * @return mixed New search set
79      */
80     function refresh_search()
81     {
82         return $this->get_search_set();
83     }
84
85     /**
86      * List the current set of contact records
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);
93
94     /**
95      * Search records
96      *
97      * @param array   List of fields to search in
98      * @param string  Search value
99      * @param int     Matching mode:
100      *                0 - partial (*abc*),
101      *                1 - strict (=),
102      *                2 - prefix (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
107      */
108     abstract function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array());
109
110     /**
111      * Count number of available contacts in database
112      *
113      * @return rcube_result_set Result set with values for 'count' and 'first'
114      */
115     abstract function count();
116
117     /**
118      * Return the last result set
119      *
120      * @return rcube_result_set Current result set or NULL if nothing selected yet
121      */
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
129      *
130      * @return mixed Result object with all record fields or False if not found
131      */
132     abstract function get_record($id, $assoc=false);
133
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     }
143
144     /**
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     }
154
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     {
169         $this->list_page = (int)$page;
170     }
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     {
180         $this->page_size = (int)$size;
181     }
182
183
184     /**
185      * Check the given data before saving.
186      * If input isn't valid, the message to display can be fetched using get_error()
187      *
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.
191      */
192     public function validate(&$save_data, $autofix = false)
193     {
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))));
199                     return false;
200                 }
201             }
202         }
203
204         return true;
205     }
206
207
208     /**
209      * Create a new contact record
210      *
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
216      */
217     function insert($save_data, $check=false)
218     {
219         /* empty for read-only address books */
220     }
221
222     /**
223      * Create new contact records for every item in the record set
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     /**
242      * Update a specific contact record
243      *
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
249      */
250     function update($id, $save_cols)
251     {
252         /* empty for read-only address books */
253     }
254
255     /**
256      * Mark one or more contact records as deleted
257      *
258      * @param array  Record identifiers
259      * @param bool   Remove records irreversible (see self::undelete)
260      */
261     function delete($ids, $force=true)
262     {
263         /* empty for read-only address books */
264     }
265
266     /**
267      * Unmark delete flag on contact record(s)
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
278      */
279     function delete_all()
280     {
281         /* empty for read-only address books */
282     }
283
284     /**
285      * Setter for the current group
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      *
293      * @param string  Optional search string to match group name
294      * @return array  Indexed list of contact groups, each a hash array
295      */
296     function list_groups($search = null)
297     {
298         /* empty for address books don't supporting groups */
299         return array();
300     }
301
302     /**
303      * Get group properties such as name and email address(es)
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     /**
315      * Create a contact group with the given name
316      *
317      * @param string The group name
318      * @return mixed False on error, array with record props in success
319      */
320     function create_group($name)
321     {
322         /* empty for address books don't supporting groups */
323         return false;
324     }
325
326     /**
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     {
334         /* empty for address books don't supporting groups */
335         return false;
336     }
337
338     /**
339      * Rename a specific contact group
340      *
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
345      */
346     function rename_group($gid, $newname, &$newid)
347     {
348         /* empty for address books don't supporting groups */
349         return false;
350     }
351
352     /**
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
357      * @return int    Number of contacts added
358      */
359     function add_to_group($group_id, $ids)
360     {
361         /* empty for address books don't supporting groups */
362         return 0;
363     }
364
365     /**
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     {
374         /* empty for address books don't supporting groups */
375         return 0;
376     }
377
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     }
391
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) {
406             if ($c === $col || strpos($c, $col.':') === 0) {
407                 if ($flat) {
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         }
416
417         return $out;
418     }
419
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     {
430         // split by words
431         $arr = explode(" ", preg_replace(
432             array('/[\s;\+\-\/]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/'),
433             array(' ', '\\1\\2', ' '),
434             $str));
435
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')));
442             }
443             else
444                 $arr[$i] = mb_strtolower($part);
445         }
446
447         return join(" ", $arr);
448     }
449
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
455      * @param bool   The name will be used on the list
456      *
457      * @return string Display name
458      */
459     public static function compose_display_name($contact, $list_mode = false)
460     {
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'];
469
470         if ($email && (empty($fn) || $fn == $email)) {
471             // Use full email address on contacts list
472             if ($list_mode)
473                 return $email;
474
475             list($emailname) = explode('@', $email);
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
485 }
486