4 * functions/addressbook.php - Functions and classes for the addressbook system
6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * Functions require SM_PATH and support of forms.php functions
12 * @package squirrelmail
13 * @subpackage addressbook
17 * If SM_PATH isn't defined, define it. Required to include files.
20 if (!defined('SM_PATH')) {
21 define('SM_PATH','../');
24 /* make sure that display_messages.php is loaded */
25 include_once(SM_PATH
. 'functions/display_messages.php');
27 global $addrbook_dsn, $addrbook_global_dsn;
30 * Create and initialize an addressbook object.
31 * @param boolean $showerr display any address book init errors. html page header
32 * must be created before calling addressbook_init() with $showerr enabled.
33 * @param boolean $onlylocal enable only local address book backends
34 * @return object address book object.
36 function addressbook_init($showerr = true, $onlylocal = false) {
37 global $data_dir, $username, $color, $ldap_server, $address_book_global_filename;
38 global $addrbook_dsn, $addrbook_table;
39 global $abook_global_file, $abook_global_file_writeable, $abook_global_file_listing;
40 global $addrbook_global_dsn, $addrbook_global_table, $addrbook_global_writeable, $addrbook_global_listing;
42 /* Create a new addressbook object */
43 $abook = new AddressBook
;
45 /* Create empty error message */
49 Always add a local backend. We use *either* file-based *or* a
50 database addressbook. If $addrbook_dsn is set, the database
51 backend is used. If not, addressbooks are stores in files.
53 if (isset($addrbook_dsn) && !empty($addrbook_dsn)) {
55 if (!isset($addrbook_table) ||
empty($addrbook_table)) {
56 $addrbook_table = 'address';
58 $r = $abook->add_backend('database', Array('dsn' => $addrbook_dsn,
60 'table' => $addrbook_table));
61 if (!$r && $showerr) {
62 $abook_init_error.=_("Error initializing addressbook database.") . "<br />\n" . $abook->error
;
66 $filename = getHashedFile($username, $data_dir, "$username.abook");
67 $r = $abook->add_backend('local_file', Array('filename' => $filename,
70 // no need to use $abook->error, because message explains error.
71 $abook_init_error.=sprintf( _("Error opening file %s"), $filename );
75 /* Global file based addressbook */
76 if (isset($abook_global_file) &&
77 isset($abook_global_file_writeable) &&
78 isset($abook_global_file_listing) &&
79 trim($abook_global_file)!=''){
81 // Detect place of address book
82 if (! preg_match("/[\/\\\]/",$abook_global_file)) {
83 /* no path chars, address book stored in data directory
84 * make sure that there is a slash between data directory
85 * and address book file name
87 $abook_global_filename=$data_dir
88 . ((substr($data_dir, -1) != '/') ?
'/' : '')
90 } elseif (preg_match("/^\/|\w:/",$abook_global_file)) {
91 // full path is set in options (starts with slash or x:)
92 $abook_global_filename=$abook_global_file;
94 $abook_global_filename=SM_PATH
. $abook_global_file;
97 $r = $abook->add_backend('local_file',array('filename'=>$abook_global_filename,
98 'name' => _("Global address book"),
99 'detect_writeable' => false,
100 'writeable'=> $abook_global_file_writeable,
101 'listing' => $abook_global_file_listing));
103 /* global abook init error is not fatal. add error message and continue */
104 if (!$r && $showerr) {
105 if ($abook_init_error!='') $abook_init_error.="<br />\n";
106 $abook_init_error.=_("Error initializing global addressbook.") . "<br />\n" . $abook->error
;
110 /* Load global addressbook from SQL if configured */
111 if (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) {
112 /* Database configured */
113 if (!isset($addrbook_global_table) ||
empty($addrbook_global_table)) {
114 $addrbook_global_table = 'global_abook';
116 $r = $abook->add_backend('database',
117 Array('dsn' => $addrbook_global_dsn,
119 'name' => _("Global address book"),
120 'writeable' => $addrbook_global_writeable,
121 'listing' => $addrbook_global_listing,
122 'table' => $addrbook_global_table));
123 /* global abook init error is not fatal. add error message and continue */
124 if (!$r && $showerr) {
125 if ($abook_init_error!='') $abook_init_error.="<br />\n";
126 $abook_init_error.=_("Error initializing global addressbook.") . "<br />\n" . $abook->error
;
131 * hook allows to include different address book backends.
132 * plugins should extract $abook and $r from arguments
133 * and use same add_backend commands as above functions.
134 * @since 1.5.1 and 1.4.5
136 $hookReturn = do_hook('abook_init', $abook, $r);
137 $abook = $hookReturn[1];
141 /* Load configured LDAP servers (if PHP has LDAP support) */
142 if (isset($ldap_server) && is_array($ldap_server)) {
144 while (list($undef,$param) = each($ldap_server)) {
145 if (is_array($param)) {
146 $r = $abook->add_backend('ldap_server', $param);
147 if (!$r && $showerr) {
148 if ($abook_init_error!='') $abook_init_error.="<br />\n";
149 $abook_init_error.=sprintf(_("Error initializing LDAP server %s:") .
150 "<br />\n", $param['host']);
151 $abook_init_error.= $abook->error
;
155 } // end of ldap server init
156 } // end of remote abook backend init
159 * display address book init errors.
161 if ($abook_init_error!='' && $showerr) {
162 error_box($abook_init_error,$color);
165 /* Return the initialized object */
170 * Display the "new address" form
172 * Form is not closed and you must add closing form tag.
174 * @param string $form_url form action url
175 * @param string $name form name
176 * @param string $title form title
177 * @param string $button form button name
178 * @param array $defdata values of form fields
180 function abook_create_form($form_url,$name,$title,$button,$defdata=array()) {
182 echo addForm($form_url, 'post', 'f_add').
185 html_tag( 'td', "\n". '<strong>' . $title . '</strong>' . "\n",
189 , 'center', '', 'width="90%"' ) ."\n";
190 address_form($name, $button, $defdata);
195 * Had to move this function outside of the Addressbook Class
196 * PHP 4.0.4 Seemed to be having problems with inline functions.
197 * Note: this can return now since we don't support 4.0.4 anymore.
199 function addressbook_cmp($a,$b) {
201 if($a['backend'] > $b['backend']) {
203 } else if($a['backend'] < $b['backend']) {
207 return (strtolower($a['name']) > strtolower($b['name'])) ?
1 : -1;
212 * Make an input field
213 * @param string $label
214 * @param string $field
215 * @param string $name
216 * @param string $size
217 * @param array $values
220 function addressbook_inp_field($label, $field, $name, $size, $values, $add='') {
222 $value = ( isset($values[$field]) ?
$values[$field] : '');
224 if (is_array($value)) {
225 $td_str = addSelect($name.'['.$field.']', $value);
227 $td_str = addInput($name.'['.$field.']', $value, $size);
231 return html_tag( 'tr' ,
232 html_tag( 'td', $label . ':', 'right', $color[4]) .
233 html_tag( 'td', $td_str, 'left', $color[4])
239 * Output form to add and modify address data
241 function address_form($name, $submittext, $values = array()) {
242 global $color, $squirrelmail_language;
244 if ($squirrelmail_language == 'ja_JP') {
245 echo html_tag( 'table',
246 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
247 ' <small>' . _("Must be unique") . '</small>') .
248 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
249 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
250 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
251 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
252 list_writable_backends($name) .
255 addSubmit($submittext, $name.'[SUBMIT]'),
256 'center', $color[4], 'colspan="2"')
258 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
260 echo html_tag( 'table',
261 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
262 ' <small>' . _("Must be unique") . '</small>') .
263 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
264 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
265 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
266 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
267 list_writable_backends($name) .
270 addSubmit($submittext, $name.'[SUBMIT]') ,
271 'center', $color[4], 'colspan="2"')
273 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
278 * Provides list of writeable backends.
279 * Works only when address is added ($name='addaddr')
280 * @param string $name name of form
281 * @return string html formated backend field (select or hidden)
283 function list_writable_backends($name) {
284 global $color, $abook;
285 if ( $name != 'addaddr' ) { return; }
286 $writeable_abook = 1;
287 if ( $abook->numbackends
> 1 ) {
288 $backends = $abook->get_backend_list();
289 $writeable_abooks=array();
290 while (list($undef,$v) = each($backends)) {
292 // add each backend to array
293 $writeable_abooks[$v->bnum
]=$v->sname
;
294 // save backend number
295 $writeable_abook=$v->bnum
;
298 if (count($writeable_abooks)>1) {
299 // we have more than one writeable backend
300 $ret=addSelect('backend',$writeable_abooks,null,true);
301 return html_tag( 'tr',
302 html_tag( 'td', _("Add to:"),'right', $color[4] ) .
303 html_tag( 'td', $ret, 'left', $color[4] )) . "\n";
306 // Only one backend exists or is writeable.
307 return html_tag( 'tr',
309 addHidden('backend', $writeable_abook),
310 'center', $color[4], 'colspan="2"')) . "\n";
314 * Sort array by the key "name"
316 function alistcmp($a,$b) {
317 $abook_sort_order=get_abook_sort();
319 switch ($abook_sort_order) {
322 $abook_sort='nickname';
339 if ($a['backend'] > $b['backend']) {
342 if ($a['backend'] < $b['backend']) {
347 if( (($abook_sort_order+
2) %
2) == 1) {
348 return (strtolower($a[$abook_sort]) < strtolower($b[$abook_sort])) ?
1 : -1;
350 return (strtolower($a[$abook_sort]) > strtolower($b[$abook_sort])) ?
1 : -1;
355 * Address book sorting options
357 * returns address book sorting order
358 * @return integer book sorting options order
360 function get_abook_sort() {
361 global $data_dir, $username;
363 /* get sorting order */
364 if(sqgetGlobalVar('abook_sort_order', $temp, SQ_GET
)) {
365 $abook_sort_order = (int) $temp;
367 if ($abook_sort_order < 0 or $abook_sort_order > 8)
370 setPref($data_dir, $username, 'abook_sort_order', $abook_sort_order);
372 /* get previous sorting options. default to unsorted */
373 $abook_sort_order = getPref($data_dir, $username, 'abook_sort_order', 8);
376 return $abook_sort_order;
380 * This function shows the address book sort button.
382 * @param integer $abook_sort_order current sort value
383 * @param string $alt_tag alt tag value (string visible to text only browsers)
384 * @param integer $Down sort value when list is sorted ascending
385 * @param integer $Up sort value when list is sorted descending
386 * @return string html code with sorting images and urls
388 function show_abook_sort_button($abook_sort_order, $alt_tag, $Down, $Up ) {
391 /* Figure out which image we want to use. */
392 if ($abook_sort_order != $Up && $abook_sort_order != $Down) {
393 $img = 'sort_none.png';
395 } elseif ($abook_sort_order == $Up) {
396 $img = 'up_pointer.png';
399 $img = 'down_pointer.png';
403 /* Now that we have everything figured out, show the actual button. */
404 return ' <a href="' . $form_url .'?abook_sort_order=' . $which
405 . '"><img src="../images/' . $img
406 . '" border="0" width="12" height="10" alt="' . $alt_tag . '" title="'
407 . _("Click here to change the sorting of the address list") .'" /></a>';
412 * This is the main address book class that connect all the
413 * backends and provide services to the functions above.
414 * @package squirrelmail
415 * @subpackage addressbook
420 Cleaning errors from html with htmlspecialchars:
421 Errors from the backend are cleaned up in this class because we not always
422 have control over it when error output is generated in the backend.
423 If this appears to be wrong place then clean it up at the source (the backend)
427 * Enabled address book backends
430 var $backends = array();
432 * Number of enabled backends
435 var $numbackends = 0;
442 * id of backend with personal address book
445 var $localbackend = 0;
447 * Name of backend with personal address book
450 var $localbackendname = '';
453 * Constructor function.
455 function AddressBook() {
456 $this->localbackendname
= _("Personal address book");
460 * Return an array of backends of a given type,
461 * or all backends if no type is specified.
462 * @param string $type backend type
463 * @return array list of backends
465 function get_backend_list($type = '') {
467 for ($i = 1 ; $i <= $this->numbackends
; $i++
) {
468 if (empty($type) ||
$type == $this->backends
[$i]->btype
) {
469 $ret[] = &$this->backends
[$i];
476 /* ========================== Public ======================== */
481 * @param string $backend backend name (without the abook_ prefix)
482 * @param mixed optional variable that is passed to the backend constructor.
483 * See each of the backend classes for valid parameters
484 * @return integer number of backends
486 function add_backend($backend, $param = '') {
487 $backend_name = 'abook_' . $backend;
488 eval('$newback = new ' . $backend_name . '($param);');
489 if(!empty($newback->error
)) {
490 $this->error
= $newback->error
;
494 $this->numbackends++
;
496 $newback->bnum
= $this->numbackends
;
497 $this->backends
[$this->numbackends
] = $newback;
499 /* Store ID of first local backend added */
500 if ($this->localbackend
== 0 && $newback->btype
== 'local') {
501 $this->localbackend
= $this->numbackends
;
502 $this->localbackendname
= $newback->sname
;
505 return $this->numbackends
;
510 * create string with name and email address
512 * This function takes a $row array as returned by the addressbook
513 * search and returns an e-mail address with the full name or
514 * nickname optionally prepended.
515 * @param array $row address book entry
516 * @return string email address with real name prepended
518 function full_address($row) {
519 global $addrsrch_fullname, $data_dir, $username;
520 $prefix = getPref($data_dir, $username, 'addrsrch_fullname');
521 if (($prefix != "" ||
(isset($addrsrch_fullname) &&
522 $prefix == $addrsrch_fullname)) && $prefix != 'noprefix') {
523 $name = ($prefix == 'nickname' ?
$row['nickname'] : $row['name']);
524 return $name . ' <' . trim($row['email']) . '>';
526 return trim($row['email']);
531 * Search for entries in address books
533 * Return a list of addresses matching expression in
534 * all backends of a given type.
535 * @param string $expression search expression
536 * @param integer $bnum backend number. default to search in all backends
537 * @return array search results
539 function search($expression, $bnum = -1) {
543 /* Search all backends */
545 $sel = $this->get_backend_list('');
547 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
548 $backend = &$sel[$i];
549 $backend->error
= '';
550 $res = $backend->search($expression);
551 if (is_array($res)) {
552 $ret = array_merge($ret, $res);
554 $this->error
.= "<br />\n" . htmlspecialchars($backend->error
);
559 /* Only fail if all backends failed */
560 if( $failed >= sizeof( $sel ) ) {
566 /* Search only one backend */
568 $ret = $this->backends
[$bnum]->search($expression);
569 if (!is_array($ret)) {
570 $this->error
.= "<br />\n" . htmlspecialchars($this->backends
[$bnum]->error
);
581 * @param string $expression search expression
582 * @param integer $bnum backend number. default to search in all backends
583 * @return array search results
585 function s_search($expression, $bnum = -1) {
587 $ret = $this->search($expression, $bnum);
588 if ( is_array( $ret ) ) {
589 usort($ret, 'addressbook_cmp');
596 * Lookup an address by alias.
597 * Only possible in local backends.
598 * @param string $alias
599 * @param integer backend number
600 * @return array lookup results. False, if not found.
602 function lookup($alias, $bnum = -1) {
607 $res = $this->backends
[$bnum]->lookup($alias);
608 if (is_array($res)) {
611 $this->error
= htmlspecialchars($backend->error
);
616 $sel = $this->get_backend_list('local');
617 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
618 $backend = &$sel[$i];
619 $backend->error
= '';
620 $res = $backend->lookup($alias);
621 if (is_array($res)) {
625 $this->error
= htmlspecialchars($backend->error
);
635 * Return all addresses
636 * @param integer $bnum backend number
637 * @return array search results
639 function list_addr($bnum = -1) {
643 $sel = $this->get_backend_list('');
645 $sel = array(0 => &$this->backends
[$bnum]);
648 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
649 $backend = &$sel[$i];
650 $backend->error
= '';
651 $res = $backend->list_addr();
652 if (is_array($res)) {
653 $ret = array_merge($ret, $res);
655 $this->error
= htmlspecialchars($backend->error
);
664 * Create a new address
665 * @param array $userdata added address record
666 * @param integer $bnum backend number
667 * @return integer the backend number that the/ address was added
668 * to, or false if it failed.
670 function add($userdata, $bnum) {
673 if (!is_array($userdata)) {
674 $this->error
= _("Invalid input data");
677 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
678 $this->error
= _("Name is missing");
681 if (empty($userdata['email'])) {
682 $this->error
= _("E-mail address is missing");
685 if (empty($userdata['nickname'])) {
686 $userdata['nickname'] = $userdata['email'];
689 if (eregi('[ \\:\\|\\#\\"\\!]', $userdata['nickname'])) {
690 $this->error
= _("Nickname contains illegal characters");
694 /* Check that specified backend accept new entries */
695 if (!$this->backends
[$bnum]->writeable
) {
696 $this->error
= _("Addressbook is read-only");
700 /* Add address to backend */
701 $res = $this->backends
[$bnum]->add($userdata);
705 $this->error
= htmlspecialchars($this->backends
[$bnum]->error
);
709 return false; // Not reached
714 * Remove the entries from address book
715 * @param mixed $alias entries that have to be removed. Can be string with nickname or array with list of nicknames
716 * @param integer $bnum backend number
717 * @return bool true if removed successfully. false if there s an error. $this->error contains error message
719 function remove($alias, $bnum) {
726 /* Convert string to single element array */
727 if (!is_array($alias)) {
728 $alias = array(0 => $alias);
731 /* Check that specified backend is writable */
732 if (!$this->backends
[$bnum]->writeable
) {
733 $this->error
= _("Addressbook is read-only");
737 /* Remove user from backend */
738 $res = $this->backends
[$bnum]->remove($alias);
742 $this->error
= htmlspecialchars($this->backends
[$bnum]->error
);
746 return FALSE; /* Not reached */
747 } /* end of remove() */
751 * Modify entry in address book
752 * @param string $alias nickname
753 * @param array $userdata newdata
754 * @param integer $bnum backend number
756 function modify($alias, $userdata, $bnum) {
759 if (empty($alias) ||
!is_string($alias)) {
764 if(!is_array($userdata)) {
765 $this->error
= _("Invalid input data");
768 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
769 $this->error
= _("Name is missing");
772 if (empty($userdata['email'])) {
773 $this->error
= _("E-mail address is missing");
777 if (eregi('[\\: \\|\\#"\\!]', $userdata['nickname'])) {
778 $this->error
= _("Nickname contains illegal characters");
782 if (empty($userdata['nickname'])) {
783 $userdata['nickname'] = $userdata['email'];
786 /* Check that specified backend is writable */
787 if (!$this->backends
[$bnum]->writeable
) {
788 $this->error
= _("Addressbook is read-only");;
792 /* Modify user in backend */
793 $res = $this->backends
[$bnum]->modify($alias, $userdata);
797 $this->error
= htmlspecialchars($this->backends
[$bnum]->error
);
801 return FALSE; /* Not reached */
802 } /* end of modify() */
805 } /* End of class Addressbook */
808 * Generic backend that all other backends extend
809 * @package squirrelmail
810 * @subpackage addressbook
812 class addressbook_backend
{
814 /* Variables that all backends must provide. */
818 * Can be 'local' or 'remote'
819 * @var string backend type
821 var $btype = 'dummy';
823 * Internal backend name
826 var $bname = 'dummy';
828 * Displayed backend name
831 var $sname = 'Dummy backend';
834 * Variables common for all backends, but that
835 * should not be changed by the backends.
851 var $writeable = false;
855 * @param string $string error message
858 function set_error($string) {
859 $this->error
= '[' . $this->sname
. '] ' . $string;
864 /* ========================== Public ======================== */
867 * Search for entries in backend
869 * Working backend should support use of wildcards. * symbol
870 * should match one or more symbols. ? symbol should match any
872 * @param string $expression
875 function search($expression) {
876 $this->set_error('search not implemented');
881 * Find entry in backend by alias
882 * @param string $alias name used for id
885 function lookup($alias) {
886 $this->set_error('lookup not implemented');
891 * List all entries in backend
893 * Working backend should provide this function or at least
894 * dummy function that returns empty array.
897 function list_addr() {
898 $this->set_error('list_addr not implemented');
903 * Add entry to backend
904 * @param array userdata
907 function add($userdata) {
908 $this->set_error('add not implemented');
913 * Remove entry from backend
914 * @param string $alias name used for id
917 function remove($alias) {
918 $this->set_error('delete not implemented');
923 * Modify entry in backend
924 * @param string $alias name used for id
925 * @param array $newuserdata new data
928 function modify($alias, $newuserdata) {
929 $this->set_error('modify not implemented');
935 PHP 5 requires that the class be made first, which seems rather
936 logical, and should have been the way it was generated the first time.
939 require_once(SM_PATH
. 'functions/abook_local_file.php');
940 require_once(SM_PATH
. 'functions/abook_ldap_server.php');
942 /* Only load database backend if database is configured */
943 if((isset($addrbook_dsn) && !empty($addrbook_dsn)) ||
944 (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn))) {
945 include_once(SM_PATH
. 'functions/abook_database.php');
949 * hook allows adding different address book classes.
950 * class must follow address book class coding standards.
952 * see addressbook_backend class and functions/abook_*.php files.
953 * @since 1.5.1 and 1.4.5
955 do_hook('abook_add_class');