3 * functions/addressbook.php - Functions and classes for the addressbook system
5 * Functions require SM_PATH and support of forms.php functions
7 * @copyright © 1999-2007 The SquirrelMail Project Team
8 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 * @package squirrelmail
11 * @subpackage addressbook
15 * Create and initialize an addressbook object.
16 * @param boolean $showerr display any address book init errors. html page header
17 * must be created before calling addressbook_init() with $showerr enabled.
18 * @param boolean $onlylocal enable only local address book backends. Should
19 * be used when code does not need access to remote backends. Backends
20 * that provide read only address books with limited listing options can be
22 * @return object address book object.
24 function addressbook_init($showerr = true, $onlylocal = false) {
25 global $data_dir, $username, $ldap_server, $address_book_global_filename;
26 global $addrbook_dsn, $addrbook_table;
27 global $abook_global_file, $abook_global_file_writeable, $abook_global_file_listing;
28 global $addrbook_global_dsn, $addrbook_global_table, $addrbook_global_writeable, $addrbook_global_listing;
29 global $abook_file_line_length;
31 /* Create a new addressbook object */
32 $abook = new AddressBook
;
34 /* Create empty error message */
38 Always add a local backend. We use *either* file-based *or* a
39 database addressbook. If $addrbook_dsn is set, the database
40 backend is used. If not, addressbooks are stores in files.
42 if (isset($addrbook_dsn) && !empty($addrbook_dsn)) {
44 if (!isset($addrbook_table) ||
empty($addrbook_table)) {
45 $addrbook_table = 'address';
47 $r = $abook->add_backend('database', Array('dsn' => $addrbook_dsn,
49 'table' => $addrbook_table));
50 if (!$r && $showerr) {
51 $abook_init_error.=_("Error initializing address book database.") . "\n" . $abook->error
;
55 $filename = getHashedFile($username, $data_dir, "$username.abook");
56 $r = $abook->add_backend('local_file', Array('filename' => $filename,
57 'line_length' => $abook_file_line_length,
60 // no need to use $abook->error, because message explains error.
61 $abook_init_error.=sprintf( _("Error opening file %s"), $filename );
65 /* Global file based addressbook */
66 if (isset($abook_global_file) &&
67 isset($abook_global_file_writeable) &&
68 isset($abook_global_file_listing) &&
69 trim($abook_global_file)!=''){
71 // Detect place of address book
72 if (! preg_match("/[\/\\\]/",$abook_global_file)) {
73 /* no path chars, address book stored in data directory
74 * make sure that there is a slash between data directory
75 * and address book file name
77 $abook_global_filename=$data_dir
78 . ((substr($data_dir, -1) != '/') ?
'/' : '')
80 } elseif (preg_match("/^\/|\w:/",$abook_global_file)) {
81 // full path is set in options (starts with slash or x:)
82 $abook_global_filename=$abook_global_file;
84 $abook_global_filename=SM_PATH
. $abook_global_file;
87 $r = $abook->add_backend('local_file',array('filename'=>$abook_global_filename,
88 'name' => _("Global address book"),
89 'detect_writeable' => false,
90 'line_length' => $abook_file_line_length,
91 'writeable'=> $abook_global_file_writeable,
92 'listing' => $abook_global_file_listing));
94 /* global abook init error is not fatal. add error message and continue */
95 if (!$r && $showerr) {
96 if ($abook_init_error!='') $abook_init_error.="\n";
97 $abook_init_error.=_("Error initializing global address book.") . "\n" . $abook->error
;
101 /* Load global addressbook from SQL if configured */
102 if (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) {
103 /* Database configured */
104 if (!isset($addrbook_global_table) ||
empty($addrbook_global_table)) {
105 $addrbook_global_table = 'global_abook';
107 $r = $abook->add_backend('database',
108 Array('dsn' => $addrbook_global_dsn,
110 'name' => _("Global address book"),
111 'writeable' => $addrbook_global_writeable,
112 'listing' => $addrbook_global_listing,
113 'table' => $addrbook_global_table));
114 /* global abook init error is not fatal. add error message and continue */
115 if (!$r && $showerr) {
116 if ($abook_init_error!='') $abook_init_error.="\n";
117 $abook_init_error.=_("Error initializing global address book.") . "\n" . $abook->error
;
122 * hook allows to include different address book backends.
123 * plugins should extract $abook and $r from arguments
124 * and use same add_backend commands as above functions.
125 * Since 1.5.2 hook sends third ($onlylocal) argument to address book
126 * plugins in order to allow detection of local address book init.
127 * @since 1.5.1 and 1.4.5
128 * Since 1.5.2, the plugin arguments are passed inside an array
129 * and by reference, so plugins hooking in here need to accept arguments
130 * in an array and change those values as needed instead of returning
131 * the changed values.
133 $temp = array(&$abook, &$r, &$onlylocal);
134 do_hook('abook_init', $temp);
135 if (!$r && $showerr) {
136 if ($abook_init_error!='') $abook_init_error.="\n";
137 $abook_init_error.=_("Error initializing other address books.") . "\n" . $abook->error
;
140 /* Load configured LDAP servers (if PHP has LDAP support) */
141 if (isset($ldap_server) && is_array($ldap_server)) {
143 while (list($undef,$param) = each($ldap_server)) {
144 if (!is_array($param))
147 /* if onlylocal is true, we only add writeable ldap servers */
148 if ($onlylocal && (!isset($param['writeable']) ||
$param['writeable'] != true))
151 $r = $abook->add_backend('ldap_server', $param);
152 if (!$r && $showerr) {
153 if ($abook_init_error!='') $abook_init_error.="\n";
154 $abook_init_error.=sprintf(_("Error initializing LDAP server %s:"), $param['host'])."\n";
155 $abook_init_error.= $abook->error
;
158 } // end of ldap server init
161 * display address book init errors.
163 if ($abook_init_error!='' && $showerr) {
164 error_box(nl2br(htmlspecialchars($abook_init_error)));
167 /* Return the initialized object */
172 * Constructs the "new address" form
174 * NOTE! The form is not closed - the caller
175 * must add the closing form tag itself.
179 * @param string $form_url Form action url
180 * @param string $name Form name
181 * @param string $title Form title
182 * @param string $button Form button name
183 * @param int $backend The current backend being displayed
184 * @param array $defdata Values of form fields
186 * @return string The desired address form display code
189 function abook_create_form($form_url, $name, $title, $button,
190 $backend, $defdata=array()) {
194 $output = addForm($form_url, 'post', 'f_add');
196 if ($button == _("Update address")) {
201 $backends = getWritableBackends();
205 'nickname' => 'NickName',
206 'firstname' => 'FirstName',
207 'lastname' => 'LastName',
212 foreach ($fields as $sqm=>$template) {
213 $values[$template] = isset($defdata[$sqm]) ?
$defdata[$sqm] : '';
216 $oTemplate->assign('writable_backends', $backends);
217 $oTemplate->assign('values', $values);
218 $oTemplate->assign('edit', $edit);
219 $oTemplate->assign('current_backend', $backend);
221 $output .= $oTemplate->fetch('addrbook_addedit.tpl');
228 * Had to move this function outside of the Addressbook Class
229 * PHP 4.0.4 Seemed to be having problems with inline functions.
230 * Note: this can return now since we don't support 4.0.4 anymore.
232 function addressbook_cmp($a,$b) {
234 if($a['backend'] > $b['backend']) {
236 } else if($a['backend'] < $b['backend']) {
240 return (strtolower($a['name']) > strtolower($b['name'])) ?
1 : -1;
245 * Retrieve a list of writable backends
248 function getWritableBackends () {
252 $backends = $abook->get_backend_list();
253 while (list($undef,$v) = each($backends)) {
255 $write[$v->bnum
]=$v->sname
;
263 * Sort array by the key "name"
265 function alistcmp($a,$b) {
266 $abook_sort_order=get_abook_sort();
268 switch ($abook_sort_order) {
271 $abook_sort='nickname';
288 if ($a['backend'] > $b['backend']) {
291 if ($a['backend'] < $b['backend']) {
296 if( (($abook_sort_order+
2) %
2) == 1) {
297 return (strtolower($a[$abook_sort]) < strtolower($b[$abook_sort])) ?
1 : -1;
299 return (strtolower($a[$abook_sort]) > strtolower($b[$abook_sort])) ?
1 : -1;
304 * Address book sorting options
306 * returns address book sorting order
307 * @return integer book sorting options order
309 function get_abook_sort() {
310 global $data_dir, $username;
312 /* get sorting order */
313 if(sqgetGlobalVar('abook_sort_order', $temp, SQ_GET
)) {
314 $abook_sort_order = (int) $temp;
316 if ($abook_sort_order < 0 or $abook_sort_order > 8)
319 setPref($data_dir, $username, 'abook_sort_order', $abook_sort_order);
321 /* get previous sorting options. default to unsorted */
322 $abook_sort_order = getPref($data_dir, $username, 'abook_sort_order', 8);
325 return $abook_sort_order;
329 * This function shows the address book sort button.
331 * @param integer $abook_sort_order Current sort value
332 * @param string $alt_tag The alt tag value (string
333 * visible to text only browsers)
334 * @param integer $Down Sort value when list is sorted
336 * @param integer $Up Sort value when list is sorted
338 * @param array $uri_extra Any additional parameters to add
339 * to the button's link, as an
340 * associative array of key/value pairs
341 * (OPTIONAL; default none)
343 * @return string html code with sorting images and urls
346 function show_abook_sort_button($abook_sort_order, $alt_tag,
347 $Down, $Up, $uri_extra=array() ) {
349 global $form_url, $icon_theme_path;
351 /* Figure out which image we want to use. */
352 if ($abook_sort_order != $Up && $abook_sort_order != $Down) {
353 $img = 'sort_none.png';
354 $text_icon = '◻'; // U+25FB WHITE MEDIUM SQUARE
356 } elseif ($abook_sort_order == $Up) {
357 $img = 'up_pointer.png';
358 $text_icon = '⇧'; // U+21E7 UPWARDS WHITE ARROW
361 $img = 'down_pointer.png';
362 $text_icon = '⇩'; // U+21E9 DOWNWARDS WHITE ARROW
366 $uri = $form_url .'?abook_sort_order=' . $which;
367 foreach ($uri_extra as $key => $value)
368 $uri = set_url_var($uri, $key, $value, FALSE);
370 /* Now that we have everything figured out, show the actual button. */
371 return create_hyperlink($uri,
372 getIcon($icon_theme_path, $img, $text_icon, $alt_tag),
374 array('style' => 'text-decoration:none',
375 'title' => $alt_tag),
381 * This is the main address book class that connect all the
382 * backends and provide services to the functions above.
383 * @package squirrelmail
384 * @subpackage addressbook
388 * Enabled address book backends
391 var $backends = array();
393 * Number of enabled backends
396 var $numbackends = 0;
403 * id of backend with personal address book
406 var $localbackend = 0;
408 * Name of backend with personal address book
411 var $localbackendname = '';
413 * Controls use of 'extra' field
415 * Extra field can be used to add link to form, which allows
416 * to modify all fields supported by backend. This is the only field
417 * that is not sanitized with htmlspecialchars. Backends MUST make
418 * sure that field data is sanitized and displayed correctly inside
419 * table cell. Use of html formating in other address book fields is
420 * not allowed. Backends that don't return 'extra' row in address book
421 * data should not modify this object property.
425 var $add_extra_field = false;
428 * Constructor function.
430 function AddressBook() {
431 $this->localbackendname
= _("Personal address book");
435 * Return an array of backends of a given type,
436 * or all backends if no type is specified.
437 * @param string $type backend type
438 * @return array list of backends
440 function get_backend_list($type = '') {
442 for ($i = 1 ; $i <= $this->numbackends
; $i++
) {
443 if (empty($type) ||
$type == $this->backends
[$i]->btype
) {
444 $ret[] = &$this->backends
[$i];
451 /* ========================== Public ======================== */
456 * @param string $backend backend name (without the abook_ prefix)
457 * @param mixed optional variable that is passed to the backend constructor.
458 * See each of the backend classes for valid parameters
459 * @return integer number of backends
461 function add_backend($backend, $param = '') {
462 static $backend_classes;
463 if (!isset($backend_classes)) {
464 $backend_classes = array();
466 if (!isset($backend_classes[$backend])) {
468 * Support backend provided by plugins. Plugin function must
469 * return an associative array with as key the backend name ($backend)
470 * and as value the file including the path containing the backend class.
471 * i.e.: $aBackend = array('backend_template' => SM_PATH . 'plugins/abook_backend_template/functions.php')
473 * NB: Because the backend files are included from within this function they DO NOT have access to
474 * vars in the global scope. This function is the global scope for the included backend !!!
477 $aBackend = do_hook('abook_add_class', $null);
478 if (isset($aBackend) && is_array($aBackend) && isset($aBackend[$backend])) {
479 require_once($aBackend[$backend]);
481 require_once(SM_PATH
. 'functions/abook_'.$backend.'.php');
483 $backend_classes[$backend] = true;
485 $backend_name = 'abook_' . $backend;
486 $newback = new $backend_name($param);
487 //eval('$newback = new ' . $backend_name . '($param);');
488 if(!empty($newback->error
)) {
489 $this->error
= $newback->error
;
493 $this->numbackends++
;
495 $newback->bnum
= $this->numbackends
;
496 $this->backends
[$this->numbackends
] = $newback;
498 /* Store ID of first local backend added */
499 if ($this->localbackend
== 0 && $newback->btype
== 'local') {
500 $this->localbackend
= $this->numbackends
;
501 $this->localbackendname
= $newback->sname
;
504 return $this->numbackends
;
509 * create string with name and email address
511 * This function takes a $row array as returned by the addressbook
512 * search and returns an e-mail address with the full name or
513 * nickname optionally prepended.
514 * @param array $row address book entry
515 * @return string email address with real name prepended
517 function full_address($row) {
518 global $data_dir, $username;
519 $addrsrch_fullname = getPref($data_dir, $username, 'addrsrch_fullname');
520 if ($addrsrch_fullname == 'fullname')
521 return $row['name'] . ' <' . trim($row['email']) . '>';
522 else if ($addrsrch_fullname == 'nickname')
523 return $row['nickname'] . ' <' . trim($row['email']) . '>';
525 return trim($row['email']);
529 * Search for entries in address books
531 * Return a list of addresses matching expression in
532 * all backends of a given type.
533 * @param string $expression search expression
534 * @param integer $bnum backend number. default to search in all backends
535 * @return array search results
537 function search($expression, $bnum = -1) {
541 /* Search all backends */
543 $sel = $this->get_backend_list('');
545 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
546 $backend = &$sel[$i];
547 $backend->error
= '';
548 $res = $backend->search($expression);
549 if (is_array($res)) {
550 $ret = array_merge($ret, $res);
552 $this->error
.= "\n" . $backend->error
;
557 /* Only fail if all backends failed */
558 if( $failed >= sizeof( $sel ) ) {
562 } elseif (! isset($this->backends
[$bnum])) {
563 /* make sure that backend exists */
564 $this->error
= _("Unknown address book backend");
568 /* Search only one backend */
570 $ret = $this->backends
[$bnum]->search($expression);
571 if (!is_array($ret)) {
572 $this->error
.= "\n" . $this->backends
[$bnum]->error
;
583 * @param string $expression search expression
584 * @param integer $bnum backend number. default to search in all backends
585 * @return array search results
587 function s_search($expression, $bnum = -1) {
589 $ret = $this->search($expression, $bnum);
590 if ( is_array( $ret ) ) {
591 usort($ret, 'addressbook_cmp');
598 * Lookup an address by alias.
599 * Only possible in local backends.
600 * @param string $alias
601 * @param integer backend number
602 * @return array lookup results. False, if not found.
604 function lookup($alias, $bnum = -1) {
609 if (!isset($this->backends
[$bnum])) {
610 $this->error
= _("Unknown address book backend");
613 $res = $this->backends
[$bnum]->lookup($alias);
614 if (is_array($res)) {
617 $this->error
= $this->backends
[$bnum]->error
;
622 $sel = $this->get_backend_list('local');
623 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
624 $backend = &$sel[$i];
625 $backend->error
= '';
626 $res = $backend->lookup($alias);
627 if (is_array($res)) {
631 $this->error
= $backend->error
;
641 * Return all addresses
642 * @param integer $bnum backend number
643 * @return mixed array with search results or boolean false on error.
645 function list_addr($bnum = -1) {
649 $sel = $this->get_backend_list('');
650 } elseif (! isset($this->backends
[$bnum])) {
651 /* make sure that backend exists */
652 $this->error
= _("Unknown address book backend");
655 $sel = array(0 => &$this->backends
[$bnum]);
658 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
659 $backend = &$sel[$i];
660 $backend->error
= '';
661 $res = $backend->list_addr();
662 if (is_array($res)) {
663 $ret = array_merge($ret, $res);
665 $this->error
= $backend->error
;
674 * Create a new address
675 * @param array $userdata added address record
676 * @param integer $bnum backend number
677 * @return integer the backend number that the/ address was added
678 * to, or false if it failed.
680 function add($userdata, $bnum) {
683 if (!is_array($userdata)) {
684 $this->error
= _("Invalid input data");
687 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
688 $this->error
= _("Name is missing");
691 if (empty($userdata['email'])) {
692 $this->error
= _("E-mail address is missing");
695 if (empty($userdata['nickname'])) {
696 $userdata['nickname'] = $userdata['email'];
699 /* Blocks use of space, :, |, #, " and ! in nickname */
700 if (eregi('[ \\:\\|\\#\\"\\!]', $userdata['nickname'])) {
701 $this->error
= _("Nickname contains illegal characters");
705 /* make sure that backend exists */
706 if (! isset($this->backends
[$bnum])) {
707 $this->error
= _("Unknown address book backend");
711 /* Check that specified backend accept new entries */
712 if (!$this->backends
[$bnum]->writeable
) {
713 $this->error
= _("Address book is read-only");
717 /* Add address to backend */
718 $res = $this->backends
[$bnum]->add($userdata);
722 $this->error
= $this->backends
[$bnum]->error
;
726 return false; // Not reached
731 * Remove the entries from address book
732 * @param mixed $alias entries that have to be removed. Can be string with nickname or array with list of nicknames
733 * @param integer $bnum backend number
734 * @return bool true if removed successfully. false if there s an error. $this->error contains error message
736 function remove($alias, $bnum) {
743 /* Convert string to single element array */
744 if (!is_array($alias)) {
745 $alias = array(0 => $alias);
748 /* make sure that backend exists */
749 if (! isset($this->backends
[$bnum])) {
750 $this->error
= _("Unknown address book backend");
754 /* Check that specified backend is writable */
755 if (!$this->backends
[$bnum]->writeable
) {
756 $this->error
= _("Address book is read-only");
760 /* Remove user from backend */
761 $res = $this->backends
[$bnum]->remove($alias);
765 $this->error
= $this->backends
[$bnum]->error
;
769 return FALSE; /* Not reached */
770 } /* end of remove() */
774 * Modify entry in address book
775 * @param string $alias nickname
776 * @param array $userdata newdata
777 * @param integer $bnum backend number
779 function modify($alias, $userdata, $bnum) {
782 if (empty($alias) ||
!is_string($alias)) {
787 if(!is_array($userdata)) {
788 $this->error
= _("Invalid input data");
791 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
792 $this->error
= _("Name is missing");
795 if (empty($userdata['email'])) {
796 $this->error
= _("E-mail address is missing");
800 if (eregi('[\\: \\|\\#"\\!]', $userdata['nickname'])) {
801 $this->error
= _("Nickname contains illegal characters");
805 if (empty($userdata['nickname'])) {
806 $userdata['nickname'] = $userdata['email'];
809 /* make sure that backend exists */
810 if (! isset($this->backends
[$bnum])) {
811 $this->error
= _("Unknown address book backend");
815 /* Check that specified backend is writable */
816 if (!$this->backends
[$bnum]->writeable
) {
817 $this->error
= _("Address book is read-only");;
821 /* Modify user in backend */
822 $res = $this->backends
[$bnum]->modify($alias, $userdata);
826 $this->error
= $this->backends
[$bnum]->error
;
830 return FALSE; /* Not reached */
831 } /* end of modify() */
834 } /* End of class Addressbook */
837 * Generic backend that all other backends extend
838 * @package squirrelmail
839 * @subpackage addressbook
841 class addressbook_backend
{
843 /* Variables that all backends must provide. */
847 * Can be 'local' or 'remote'
848 * @var string backend type
850 var $btype = 'dummy';
852 * Internal backend name
855 var $bname = 'dummy';
857 * Displayed backend name
860 var $sname = 'Dummy backend';
863 * Variables common for all backends, but that
864 * should not be changed by the backends.
880 var $writeable = false;
884 * @param string $string error message
887 function set_error($string) {
888 $this->error
= '[' . $this->sname
. '] ' . $string;
893 /* ========================== Public ======================== */
896 * Search for entries in backend
898 * Working backend should support use of wildcards. * symbol
899 * should match one or more symbols. ? symbol should match any
901 * @param string $expression
904 function search($expression) {
905 $this->set_error('search is not implemented');
910 * Find entry in backend by alias
911 * @param string $alias name used for id
914 function lookup($alias) {
915 $this->set_error('lookup is not implemented');
920 * List all entries in backend
922 * Working backend should provide this function or at least
923 * dummy function that returns empty array.
926 function list_addr() {
927 $this->set_error('list_addr is not implemented');
932 * Add entry to backend
933 * @param array userdata
936 function add($userdata) {
937 $this->set_error('add is not implemented');
942 * Remove entry from backend
943 * @param string $alias name used for id
946 function remove($alias) {
947 $this->set_error('delete is not implemented');
952 * Modify entry in backend
953 * @param string $alias name used for id
954 * @param array $newuserdata new data
957 function modify($alias, $newuserdata) {
958 $this->set_error('modify is not implemented');
963 * Creates full name from given name and surname
965 * Handles name order differences. Function always runs in SquirrelMail gettext domain.
966 * Plugins don't have to switch domains before calling this function.
967 * @param string $firstname given name
968 * @param string $lastname surname
969 * @return string full name
972 function fullname($firstname,$lastname) {
974 * i18n: allows to control fullname layout in address book listing
975 * first %s is for first name, second %s is for last name.
976 * Translate it to '%2$s %1$s', if surname must be displayed first in your language.
977 * Please note that variables can be set to empty string and extra formating
978 * (for example '%2$s, %1$s' as in 'Smith, John') might break. Use it only for
979 * setting name and surname order. scripts will remove all prepended and appended
982 return trim(sprintf(dgettext('squirrelmail',"%s %s"),$firstname,$lastname));