3 * functions/addressbook.php - Functions and classes for the addressbook system
5 * Copyright (c) 1999-2005 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 * Functions require SM_PATH and support of forms.php functions
11 * @package squirrelmail
12 * @subpackage addressbook
16 * If SM_PATH isn't defined, define it. Required to include files.
19 if (!defined('SM_PATH')) {
20 define('SM_PATH','../');
23 /* make sure that display_messages.php is loaded */
24 include_once(SM_PATH
. 'functions/display_messages.php');
26 global $addrbook_dsn, $addrbook_global_dsn;
29 * Create and initialize an addressbook object.
30 * @param boolean $showerr display any address book init errors. html page header
31 * must be created before calling addressbook_init() with $showerr enabled.
32 * @param boolean $onlylocal enable only local address book backends
33 * @return object address book object.
35 function addressbook_init($showerr = true, $onlylocal = false) {
36 global $data_dir, $username, $color, $ldap_server, $address_book_global_filename;
37 global $addrbook_dsn, $addrbook_table;
38 global $abook_global_file, $abook_global_file_writeable;
39 global $addrbook_global_dsn, $addrbook_global_table, $addrbook_global_writeable, $addrbook_global_listing;
41 /* Create a new addressbook object */
42 $abook = new AddressBook
;
44 /* Create empty error message */
48 Always add a local backend. We use *either* file-based *or* a
49 database addressbook. If $addrbook_dsn is set, the database
50 backend is used. If not, addressbooks are stores in files.
52 if (isset($addrbook_dsn) && !empty($addrbook_dsn)) {
54 if (!isset($addrbook_table) ||
empty($addrbook_table)) {
55 $addrbook_table = 'address';
57 $r = $abook->add_backend('database', Array('dsn' => $addrbook_dsn,
59 'table' => $addrbook_table));
60 if (!$r && $showerr) {
61 $abook_init_error.=_("Error initializing addressbook database.") . "<br />\n" . $abook->error
;
65 $filename = getHashedFile($username, $data_dir, "$username.abook");
66 $r = $abook->add_backend('local_file', Array('filename' => $filename,
69 // no need to use $abook->error, because message explains error.
70 $abook_init_error.=sprintf( _("Error opening file %s"), $filename );
75 /* This would be for the global addressbook */
76 if (isset($abook_global_file) && isset($abook_global_file_writeable)
77 && trim($abook_global_file)!=''){
78 // Detect place of address book
79 if (! preg_match("/[\/\\\]/",$abook_global_file)) {
80 /* no path chars, address book stored in data directory
81 * make sure that there is a slash between data directory
82 * and address book file name
84 $abook_global_filename=$data_dir
85 . ((substr($data_dir, -1) != '/') ?
'/' : '')
87 } elseif (preg_match("/^\/|\w:/",$abook_global_file)) {
88 // full path is set in options (starts with slash or x:)
89 $abook_global_filename=$abook_global_file;
91 $abook_global_filename=SM_PATH
. $abook_global_file;
93 $r = $abook->add_backend('local_file',array('filename'=>$abook_global_filename,
94 'name' => _("Global address book"),
95 'detect_writeable' => false,
96 'writeable'=> $abook_global_file_writeable));
98 /* global abook init error is not fatal. add error message and continue */
99 if (!$r && $showerr) {
100 if ($abook_init_error!='') $abook_init_error.="<br />\n";
101 $abook_init_error.=_("Error initializing global addressbook.") . "<br />\n" . $abook->error
;
105 /* Load global addressbook from SQL if configured */
106 if (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) {
107 /* Database configured */
108 if (!isset($addrbook_global_table) ||
empty($addrbook_global_table)) {
109 $addrbook_global_table = 'global_abook';
111 $r = $abook->add_backend('database',
112 Array('dsn' => $addrbook_global_dsn,
114 'name' => _("Global address book"),
115 'writeable' => $addrbook_global_writeable,
116 'listing' => $addrbook_global_listing,
117 'table' => $addrbook_global_table));
118 /* global abook init error is not fatal. add error message and continue */
119 if (!$r && $showerr) {
120 if ($abook_init_error!='') $abook_init_error.="<br />\n";
121 $abook_init_error.=_("Error initializing global addressbook.") . "<br />\n" . $abook->error
;
126 * hook allows to include different address book backends.
127 * plugins should extract $abook and $r from arguments
128 * and use same add_backend commands as above functions.
131 $hookReturn = do_hook('abook_init', $abook, $r);
132 $abook = $hookReturn[1];
136 /* Load configured LDAP servers (if PHP has LDAP support) */
137 if (isset($ldap_server) && is_array($ldap_server) && function_exists('ldap_connect')) {
139 while (list($undef,$param) = each($ldap_server)) {
140 if (is_array($param)) {
141 $r = $abook->add_backend('ldap_server', $param);
142 if (!$r && $showerr) {
143 if ($abook_init_error!='') $abook_init_error.="<br />\n";
144 $abook_init_error.=sprintf(_("Error initializing LDAP server %s:") .
145 "<br />\n", $param['host']);
146 $abook_init_error.= $abook->error
;
150 } // end of ldap server init
151 } // end of remote abook backend init
154 * display address book init errors.
156 if ($abook_init_error!='' && $showerr) {
157 error_box($abook_init_error,$color);
159 /* Return the initialized object */
164 * Display the "new address" form
166 * Form is not closed and you must add closing form tag.
168 * @param string $form_url form action url
169 * @param string $name form name
170 * @param string $title form title
171 * @param string $button form button name
172 * @param array $defdata values of form fields
174 function abook_create_form($form_url,$name,$title,$button,$defdata=array()) {
176 echo addForm($form_url, 'post', 'f_add').
179 html_tag( 'td', "\n". '<strong>' . $title . '</strong>' . "\n",
183 , 'center', '', 'width="90%"' ) ."\n";
184 address_form($name, $button, $defdata);
189 * Had to move this function outside of the Addressbook Class
190 * PHP 4.0.4 Seemed to be having problems with inline functions.
191 * Note: this can return now since we don't support 4.0.4 anymore.
193 function addressbook_cmp($a,$b) {
195 if($a['backend'] > $b['backend']) {
197 } else if($a['backend'] < $b['backend']) {
201 return (strtolower($a['name']) > strtolower($b['name'])) ?
1 : -1;
206 * Make an input field
207 * @param string $label
208 * @param string $field
209 * @param string $name
210 * @param string $size
211 * @param array $values
214 function addressbook_inp_field($label, $field, $name, $size, $values, $add='') {
216 $value = ( isset($values[$field]) ?
$values[$field] : '');
218 if (is_array($value)) {
219 $td_str = addSelect($name.'['.$field.']', $value);
221 $td_str = addInput($name.'['.$field.']', $value, $size);
225 return html_tag( 'tr' ,
226 html_tag( 'td', $label . ':', 'right', $color[4]) .
227 html_tag( 'td', $td_str, 'left', $color[4])
233 * Output form to add and modify address data
235 function address_form($name, $submittext, $values = array()) {
236 global $color, $squirrelmail_language;
238 if ($squirrelmail_language == 'ja_JP') {
239 echo html_tag( 'table',
240 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
241 ' <small>' . _("Must be unique") . '</small>') .
242 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
243 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
244 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
245 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
246 list_writable_backends($name) .
249 addSubmit($submittext, $name.'[SUBMIT]'),
250 'center', $color[4], 'colspan="2"')
252 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
254 echo html_tag( 'table',
255 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
256 ' <small>' . _("Must be unique") . '</small>') .
257 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
258 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
259 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
260 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
261 list_writable_backends($name) .
264 addSubmit($submittext, $name.'[SUBMIT]') ,
265 'center', $color[4], 'colspan="2"')
267 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
272 * Provides list of writeable backends.
273 * Works only when address is added ($name='addaddr')
274 * @param string $name name of form
275 * @return string html formated backend field (select or hidden)
277 function list_writable_backends($name) {
278 global $color, $abook;
279 if ( $name != 'addaddr' ) { return; }
280 $writeable_abook = 1;
281 if ( $abook->numbackends
> 1 ) {
282 $backends = $abook->get_backend_list();
283 $writeable_abooks=array();
284 while (list($undef,$v) = each($backends)) {
286 // add each backend to array
287 $writeable_abooks[$v->bnum
]=$v->sname
;
288 // save backend number
289 $writeable_abook=$v->bnum
;
292 if (count($writeable_abooks)>1) {
293 // we have more than one writeable backend
294 $ret=addSelect('backend',$writeable_abooks,null,true);
295 return html_tag( 'tr',
296 html_tag( 'td', _("Add to:"),'right', $color[4] ) .
297 html_tag( 'td', $ret, 'left', $color[4] )) . "\n";
300 // Only one backend exists or is writeable.
301 return html_tag( 'tr',
303 addHidden('backend', $writeable_abook),
304 'center', $color[4], 'colspan="2"')) . "\n";
308 * Sort array by the key "name"
310 function alistcmp($a,$b) {
311 $abook_sort_order=get_abook_sort();
313 switch ($abook_sort_order) {
316 $abook_sort='nickname';
333 if ($a['backend'] > $b['backend']) {
336 if ($a['backend'] < $b['backend']) {
341 if( (($abook_sort_order+
2) %
2) == 1) {
342 return (strtolower($a[$abook_sort]) < strtolower($b[$abook_sort])) ?
1 : -1;
344 return (strtolower($a[$abook_sort]) > strtolower($b[$abook_sort])) ?
1 : -1;
349 * Address book sorting options
351 * returns address book sorting order
352 * @return integer book sorting options order
354 function get_abook_sort() {
355 global $data_dir, $username;
357 /* get sorting order */
358 if(sqgetGlobalVar('abook_sort_order', $temp, SQ_GET
)) {
359 $abook_sort_order = (int) $temp;
361 if ($abook_sort_order < 0 or $abook_sort_order > 8)
364 setPref($data_dir, $username, 'abook_sort_order', $abook_sort_order);
366 /* get previous sorting options. default to unsorted */
367 $abook_sort_order = getPref($data_dir, $username, 'abook_sort_order', 8);
370 return $abook_sort_order;
374 * This function shows the address book sort button.
376 * @param integer $abook_sort_order current sort value
377 * @param string $alt_tag alt tag value (string visible to text only browsers)
378 * @param integer $Down sort value when list is sorted ascending
379 * @param integer $Up sort value when list is sorted descending
380 * @return string html code with sorting images and urls
382 function show_abook_sort_button($abook_sort_order, $alt_tag, $Down, $Up ) {
385 /* Figure out which image we want to use. */
386 if ($abook_sort_order != $Up && $abook_sort_order != $Down) {
387 $img = 'sort_none.png';
389 } elseif ($abook_sort_order == $Up) {
390 $img = 'up_pointer.png';
393 $img = 'down_pointer.png';
397 /* Now that we have everything figured out, show the actual button. */
398 return ' <a href="' . $form_url .'?abook_sort_order=' . $which
399 . '"><img src="../images/' . $img
400 . '" border="0" width="12" height="10" alt="' . $alt_tag . '" title="'
401 . _("Click here to change the sorting of the address list") .'" /></a>';
406 * This is the main address book class that connect all the
407 * backends and provide services to the functions above.
408 * @package squirrelmail
409 * @subpackage addressbook
413 * Enabled address book backends
416 var $backends = array();
418 * Number of enabled backends
421 var $numbackends = 0;
428 * id of backend with personal address book
431 var $localbackend = 0;
433 * Name of backend with personal address book
436 var $localbackendname = '';
439 * Constructor function.
441 function AddressBook() {
442 $this->localbackendname
= _("Personal address book");
446 * Return an array of backends of a given type,
447 * or all backends if no type is specified.
448 * @param string $type backend type
449 * @return array list of backends
451 function get_backend_list($type = '') {
453 for ($i = 1 ; $i <= $this->numbackends
; $i++
) {
454 if (empty($type) ||
$type == $this->backends
[$i]->btype
) {
455 $ret[] = &$this->backends
[$i];
462 /* ========================== Public ======================== */
467 * @param string $backend backend name (without the abook_ prefix)
468 * @param mixed optional variable that is passed to the backend constructor.
469 * See each of the backend classes for valid parameters
470 * @return integer number of backends
472 function add_backend($backend, $param = '') {
473 $backend_name = 'abook_' . $backend;
474 eval('$newback = new ' . $backend_name . '($param);');
475 if(!empty($newback->error
)) {
476 $this->error
= $newback->error
;
480 $this->numbackends++
;
482 $newback->bnum
= $this->numbackends
;
483 $this->backends
[$this->numbackends
] = $newback;
485 /* Store ID of first local backend added */
486 if ($this->localbackend
== 0 && $newback->btype
== 'local') {
487 $this->localbackend
= $this->numbackends
;
488 $this->localbackendname
= $newback->sname
;
491 return $this->numbackends
;
496 * create string with name and email address
498 * This function takes a $row array as returned by the addressbook
499 * search and returns an e-mail address with the full name or
500 * nickname optionally prepended.
501 * @param array $row address book entry
502 * @return string email address with real name prepended
504 function full_address($row) {
505 global $addrsrch_fullname, $data_dir, $username;
506 $prefix = getPref($data_dir, $username, 'addrsrch_fullname');
507 if (($prefix != "" ||
(isset($addrsrch_fullname) &&
508 $prefix == $addrsrch_fullname)) && $prefix != 'noprefix') {
509 $name = ($prefix == 'nickname' ?
$row['nickname'] : $row['name']);
510 return $name . ' <' . trim($row['email']) . '>';
512 return trim($row['email']);
517 * Search for entries in address books
519 * Return a list of addresses matching expression in
520 * all backends of a given type.
521 * @param string $expression search expression
522 * @param integer $bnum backend number. default to search in all backends
523 * @return array search results
525 function search($expression, $bnum = -1) {
529 /* Search all backends */
531 $sel = $this->get_backend_list('');
533 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
534 $backend = &$sel[$i];
535 $backend->error
= '';
536 $res = $backend->search($expression);
537 if (is_array($res)) {
538 $ret = array_merge($ret, $res);
540 $this->error
.= "<br />\n" . $backend->error
;
545 /* Only fail if all backends failed */
546 if( $failed >= sizeof( $sel ) ) {
552 /* Search only one backend */
554 $ret = $this->backends
[$bnum]->search($expression);
555 if (!is_array($ret)) {
556 $this->error
.= "<br />\n" . $this->backends
[$bnum]->error
;
567 * @param string $expression search expression
568 * @param integer $bnum backend number. default to search in all backends
569 * @return array search results
571 function s_search($expression, $bnum = -1) {
573 $ret = $this->search($expression, $bnum);
574 if ( is_array( $ret ) ) {
575 usort($ret, 'addressbook_cmp');
582 * Lookup an address by alias.
583 * Only possible in local backends.
584 * @param string $alias
585 * @param integer backend number
586 * @return array lookup results. False, if not found.
588 function lookup($alias, $bnum = -1) {
593 $res = $this->backends
[$bnum]->lookup($alias);
594 if (is_array($res)) {
597 $this->error
= $backend->error
;
602 $sel = $this->get_backend_list('local');
603 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
604 $backend = &$sel[$i];
605 $backend->error
= '';
606 $res = $backend->lookup($alias);
607 if (is_array($res)) {
611 $this->error
= $backend->error
;
621 * Return all addresses
622 * @param integer $bnum backend number
623 * @return array search results
625 function list_addr($bnum = -1) {
629 $sel = $this->get_backend_list('');
631 $sel = array(0 => &$this->backends
[$bnum]);
634 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
635 $backend = &$sel[$i];
636 $backend->error
= '';
637 $res = $backend->list_addr();
638 if (is_array($res)) {
639 $ret = array_merge($ret, $res);
641 $this->error
= $backend->error
;
650 * Create a new address
651 * @param array $userdata added address record
652 * @param integer $bnum backend number
653 * @return integer the backend number that the/ address was added
654 * to, or false if it failed.
656 function add($userdata, $bnum) {
659 if (!is_array($userdata)) {
660 $this->error
= _("Invalid input data");
663 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
664 $this->error
= _("Name is missing");
667 if (empty($userdata['email'])) {
668 $this->error
= _("E-mail address is missing");
671 if (empty($userdata['nickname'])) {
672 $userdata['nickname'] = $userdata['email'];
675 if (eregi('[ \\:\\|\\#\\"\\!]', $userdata['nickname'])) {
676 $this->error
= _("Nickname contains illegal characters");
680 /* Check that specified backend accept new entries */
681 if (!$this->backends
[$bnum]->writeable
) {
682 $this->error
= _("Addressbook is read-only");
686 /* Add address to backend */
687 $res = $this->backends
[$bnum]->add($userdata);
691 $this->error
= $this->backends
[$bnum]->error
;
695 return false; // Not reached
700 * Remove the entries from address book
701 * @param mixed $alias entries that have to be removed. Can be string with nickname or array with list of nicknames
702 * @param integer $bnum backend number
703 * @return bool true if removed successfully. false if there s an error. $this->error contains error message
705 function remove($alias, $bnum) {
712 /* Convert string to single element array */
713 if (!is_array($alias)) {
714 $alias = array(0 => $alias);
717 /* Check that specified backend is writable */
718 if (!$this->backends
[$bnum]->writeable
) {
719 $this->error
= _("Addressbook is read-only");
723 /* Remove user from backend */
724 $res = $this->backends
[$bnum]->remove($alias);
728 $this->error
= $this->backends
[$bnum]->error
;
732 return FALSE; /* Not reached */
733 } /* end of remove() */
737 * Modify entry in address book
738 * @param string $alias nickname
739 * @param array $userdata newdata
740 * @param integer $bnum backend number
742 function modify($alias, $userdata, $bnum) {
745 if (empty($alias) ||
!is_string($alias)) {
750 if(!is_array($userdata)) {
751 $this->error
= _("Invalid input data");
754 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
755 $this->error
= _("Name is missing");
758 if (empty($userdata['email'])) {
759 $this->error
= _("E-mail address is missing");
763 if (eregi('[\\: \\|\\#"\\!]', $userdata['nickname'])) {
764 $this->error
= _("Nickname contains illegal characters");
768 if (empty($userdata['nickname'])) {
769 $userdata['nickname'] = $userdata['email'];
772 /* Check that specified backend is writable */
773 if (!$this->backends
[$bnum]->writeable
) {
774 $this->error
= _("Addressbook is read-only");;
778 /* Modify user in backend */
779 $res = $this->backends
[$bnum]->modify($alias, $userdata);
783 $this->error
= $this->backends
[$bnum]->error
;
787 return FALSE; /* Not reached */
788 } /* end of modify() */
791 } /* End of class Addressbook */
794 * Generic backend that all other backends extend
795 * @package squirrelmail
796 * @subpackage addressbook
798 class addressbook_backend
{
800 /* Variables that all backends must provide. */
804 * Can be 'local' or 'remote'
805 * @var string backend type
807 var $btype = 'dummy';
809 * Internal backend name
812 var $bname = 'dummy';
814 * Displayed backend name
817 var $sname = 'Dummy backend';
820 * Variables common for all backends, but that
821 * should not be changed by the backends.
837 var $writeable = false;
841 * @param string $string error message
844 function set_error($string) {
845 $this->error
= '[' . $this->sname
. '] ' . $string;
850 /* ========================== Public ======================== */
853 * Search for entries in backend
854 * @param string $expression
857 function search($expression) {
858 $this->set_error('search not implemented');
863 * Find entry in backend by alias
864 * @param string $alias name used for id
867 function lookup($alias) {
868 $this->set_error('lookup not implemented');
873 * List all entries in backend
876 function list_addr() {
877 $this->set_error('list_addr not implemented');
882 * Add entry to backend
883 * @param array userdata
886 function add($userdata) {
887 $this->set_error('add not implemented');
892 * Remove entry from backend
893 * @param string $alias name used for id
896 function remove($alias) {
897 $this->set_error('delete not implemented');
902 * Modify entry in backend
903 * @param string $alias name used for id
904 * @param array $newuserdata new data
907 function modify($alias, $newuserdata) {
908 $this->set_error('modify not implemented');
914 PHP 5 requires that the class be made first, which seems rather
915 logical, and should have been the way it was generated the first time.
918 require_once(SM_PATH
. 'functions/abook_local_file.php');
919 require_once(SM_PATH
. 'functions/abook_ldap_server.php');
921 /* Only load database backend if database is configured */
922 if((isset($addrbook_dsn) && !empty($addrbook_dsn)) ||
923 (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) ) {
924 include_once(SM_PATH
. 'functions/abook_database.php');
928 * hook allows adding different address book classes.
929 * class must follow address book class coding standards.
931 * see addressbook_backend class and functions/abook_*.php files.
934 do_hook('abook_add_class');