]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_addressbook.php
Fix symlink mess
[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 5873 2012-02-11 13:50:04Z thomasb $
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 $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));
50
51     protected $error;
52
53     /**
54      * Returns addressbook name (e.g. for addressbooks listing)
55      */
56     abstract function get_name();
57
58     /**
59      * Save a search string for future listings
60      *
61      * @param mixed Search params to use in listing method, obtained by get_search_set()
62      */
63     abstract function set_search_set($filter);
64
65     /**
66      * Getter for saved search properties
67      *
68      * @return mixed Search properties used by this class
69      */
70     abstract function get_search_set();
71
72     /**
73      * Reset saved results and search parameters
74      */
75     abstract function reset();
76
77     /**
78      * Refresh saved search set after data has changed
79      *
80      * @return mixed New search set
81      */
82     function refresh_search()
83     {
84         return $this->get_search_set();
85     }
86
87     /**
88      * List the current set of contact records
89      *
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
93      */
94     abstract function list_records($cols=null, $subset=0);
95
96     /**
97      * Search records
98      *
99      * @param array   List of fields to search in
100      * @param string  Search value
101      * @param int     Matching mode:
102      *                0 - partial (*abc*),
103      *                1 - strict (=),
104      *                2 - prefix (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
109      */
110     abstract function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array());
111
112     /**
113      * Count number of available contacts in database
114      *
115      * @return rcube_result_set Result set with values for 'count' and 'first'
116      */
117     abstract function count();
118
119     /**
120      * Return the last result set
121      *
122      * @return rcube_result_set Current result set or NULL if nothing selected yet
123      */
124     abstract function get_result();
125
126     /**
127      * Get a specific contact record
128      *
129      * @param mixed record identifier(s)
130      * @param boolean True to return record as associative array, otherwise a result set is returned
131      *
132      * @return mixed Result object with all record fields or False if not found
133      */
134     abstract function get_record($id, $assoc=false);
135
136     /**
137      * Returns the last error occured (e.g. when updating/inserting failed)
138      *
139      * @return array Hash array with the following fields: type, message
140      */
141     function get_error()
142     {
143       return $this->error;
144     }
145
146     /**
147      * Setter for errors for internal use
148      *
149      * @param int Error type (one of this class' error constants)
150      * @param string Error message (name of a text label)
151      */
152     protected function set_error($type, $message)
153     {
154       $this->error = array('type' => $type, 'message' => $message);
155     }
156
157     /**
158      * Close connection to source
159      * Called on script shutdown
160      */
161     function close() { }
162
163     /**
164      * Set internal list page
165      *
166      * @param  number  Page number to list
167      * @access public
168      */
169     function set_page($page)
170     {
171         $this->list_page = (int)$page;
172     }
173
174     /**
175      * Set internal page size
176      *
177      * @param  number  Number of messages to display on one page
178      * @access public
179      */
180     function set_pagesize($size)
181     {
182         $this->page_size = (int)$size;
183     }
184
185     /**
186      * Set internal sort settings
187      *
188      * @param string $sort_col Sort column
189      * @param string $sort_order Sort order
190      */
191     function set_sort_order($sort_col, $sort_order = null)
192     {
193         if ($sort_col != null && ($this->coltypes[$sort_col] || in_array($sort_col, $this->coltypes))) {
194             $this->sort_col = $sort_col;
195         }
196         if ($sort_order != null) {
197             $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
198         }
199     }
200
201     /**
202      * Check the given data before saving.
203      * If input isn't valid, the message to display can be fetched using get_error()
204      *
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.
208      */
209     public function validate(&$save_data, $autofix = false)
210     {
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))));
216                     return false;
217                 }
218             }
219         }
220
221         return true;
222     }
223
224
225     /**
226      * Create a new contact record
227      *
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
233      */
234     function insert($save_data, $check=false)
235     {
236         /* empty for read-only address books */
237     }
238
239     /**
240      * Create new contact records for every item in the record set
241      *
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
245      */
246     function insertMultiple($recset, $check=false)
247     {
248         $ids = array();
249         if (is_object($recset) && is_a($recset, rcube_result_set)) {
250             while ($row = $recset->next()) {
251                 if ($insert = $this->insert($row, $check))
252                     $ids[] = $insert;
253             }
254         }
255         return $ids;
256     }
257
258     /**
259      * Update a specific contact record
260      *
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
266      */
267     function update($id, $save_cols)
268     {
269         /* empty for read-only address books */
270     }
271
272     /**
273      * Mark one or more contact records as deleted
274      *
275      * @param array  Record identifiers
276      * @param bool   Remove records irreversible (see self::undelete)
277      */
278     function delete($ids, $force=true)
279     {
280         /* empty for read-only address books */
281     }
282
283     /**
284      * Unmark delete flag on contact record(s)
285      *
286      * @param array  Record identifiers
287      */
288     function undelete($ids)
289     {
290         /* empty for read-only address books */
291     }
292
293     /**
294      * Mark all records in database as deleted
295      */
296     function delete_all()
297     {
298         /* empty for read-only address books */
299     }
300
301     /**
302      * Setter for the current group
303      * (empty, has to be re-implemented by extending class)
304      */
305     function set_group($gid) { }
306
307     /**
308      * List all active contact groups of this source
309      *
310      * @param string  Optional search string to match group name
311      * @return array  Indexed list of contact groups, each a hash array
312      */
313     function list_groups($search = null)
314     {
315         /* empty for address books don't supporting groups */
316         return array();
317     }
318
319     /**
320      * Get group properties such as name and email address(es)
321      *
322      * @param string Group identifier
323      * @return array Group properties as hash array
324      */
325     function get_group($group_id)
326     {
327         /* empty for address books don't supporting groups */
328         return null;
329     }
330
331     /**
332      * Create a contact group with the given name
333      *
334      * @param string The group name
335      * @return mixed False on error, array with record props in success
336      */
337     function create_group($name)
338     {
339         /* empty for address books don't supporting groups */
340         return false;
341     }
342
343     /**
344      * Delete the given group and all linked group members
345      *
346      * @param string Group identifier
347      * @return boolean True on success, false if no data was changed
348      */
349     function delete_group($gid)
350     {
351         /* empty for address books don't supporting groups */
352         return false;
353     }
354
355     /**
356      * Rename a specific contact group
357      *
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
362      */
363     function rename_group($gid, $newname, &$newid)
364     {
365         /* empty for address books don't supporting groups */
366         return false;
367     }
368
369     /**
370      * Add the given contact records the a certain group
371      *
372      * @param string  Group identifier
373      * @param array   List of contact identifiers to be added
374      * @return int    Number of contacts added
375      */
376     function add_to_group($group_id, $ids)
377     {
378         /* empty for address books don't supporting groups */
379         return 0;
380     }
381
382     /**
383      * Remove the given contact records from a certain group
384      *
385      * @param string  Group identifier
386      * @param array   List of contact identifiers to be removed
387      * @return int    Number of deleted group members
388      */
389     function remove_from_group($group_id, $ids)
390     {
391         /* empty for address books don't supporting groups */
392         return 0;
393     }
394
395     /**
396      * Get group assignments of a specific contact record
397      *
398      * @param mixed Record identifier
399      *
400      * @return array List of assigned groups as ID=>Name pairs
401      * @since 0.5-beta
402      */
403     function get_record_groups($id)
404     {
405         /* empty for address books don't supporting groups */
406         return array();
407     }
408
409
410     /**
411      * Utility function to return all values of a certain data column
412      * either as flat list or grouped by subtype
413      *
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
418      */
419     function get_col_values($col, $data, $flat = false)
420     {
421         $out = array();
422         foreach ($data as $c => $values) {
423             if ($c === $col || strpos($c, $col.':') === 0) {
424                 if ($flat) {
425                     $out = array_merge($out, (array)$values);
426                 }
427                 else {
428                     list($f, $type) = explode(':', $c);
429                     $out[$type] = array_merge((array)$out[$type], (array)$values);
430                 }
431             }
432         }
433
434         return $out;
435     }
436
437
438     /**
439      * Normalize the given string for fulltext search.
440      * Currently only optimized for Latin-1 characters; to be extended
441      *
442      * @param string Input string (UTF-8)
443      * @return string Normalized string
444      */
445     protected static function normalize_string($str)
446     {
447         // split by words
448         $arr = explode(" ", preg_replace(
449             array('/[\s;\+\-\/]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/'),
450             array(' ', '\\1\\2', ' '),
451             $str));
452
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')));
459             }
460             else
461                 $arr[$i] = mb_strtolower($part);
462         }
463
464         return join(" ", $arr);
465     }
466
467
468     /**
469      * Compose a valid display name from the given structured contact data
470      *
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
473      *
474      * @return string Display name
475      */
476     public static function compose_display_name($contact, $full_email = false)
477     {
478         $contact = rcmail::get_instance()->plugins->exec_hook('contact_displayname', $contact);
479         $fn = $contact['name'];
480
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'])));
483
484         // use email address part for name
485         $email = is_array($contact['email']) ? $contact['email'][0] : $contact['email'];
486
487         if ($email && (empty($fn) || $fn == $email)) {
488             // return full email
489             if ($full_email)
490                 return $email;
491
492             list($emailname) = explode('@', $email);
493             if (preg_match('/(.*)[\.\-\_](.*)/', $emailname, $match))
494                 $fn = trim(ucfirst($match[1]).' '.ucfirst($match[2]));
495             else
496                 $fn = ucfirst($emailname);
497         }
498
499         return $fn;
500     }
501
502
503     /**
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.
506      *
507      * @param array  Hash array with contact data as key-value pairs
508      * @return string List name
509      */
510     public static function compose_list_name($contact)
511     {
512         static $compose_mode;
513
514         if (!isset($compose_mode))  // cache this
515             $compose_mode = rcmail::get_instance()->config->get('addressbook_name_listing', 0);
516
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']));
523         else
524             $fn = !empty($contact['name']) ? $contact['name'] : join(' ', array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix']));
525
526         $fn = trim($fn, ', ');
527
528         // fallback to display name
529         if (empty($fn) && $contact['name'])
530             $fn = $contact['name'];
531
532         // fallback to email address
533         $email = is_array($contact['email']) ? $contact['email'][0] : $contact['email'];
534         if (empty($fn) && $email)
535             return $email;
536
537         return $fn;
538     }
539
540 }
541