4 * functions/addressbook.php - Functions and classes for the addressbook system
6 * Functions require SM_PATH and support of forms.php functions
8 * @copyright © 1999-2006 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @package squirrelmail
12 * @subpackage addressbook
15 /** required includes */
16 // FIXME, NO display code in functions files
17 include_once(SM_PATH
. 'templates/util_global.php');
20 * Create and initialize an addressbook object.
21 * @param boolean $showerr display any address book init errors. html page header
22 * must be created before calling addressbook_init() with $showerr enabled.
23 * @param boolean $onlylocal enable only local address book backends. Should
24 * be used when code does not need access to remote backends. Backends
25 * that provide read only address books with limited listing options can be
27 * @return object address book object.
29 function addressbook_init($showerr = true, $onlylocal = false) {
30 global $data_dir, $username, $ldap_server, $address_book_global_filename;
31 global $addrbook_dsn, $addrbook_table;
32 global $abook_global_file, $abook_global_file_writeable, $abook_global_file_listing;
33 global $addrbook_global_dsn, $addrbook_global_table, $addrbook_global_writeable, $addrbook_global_listing;
35 /* Create a new addressbook object */
36 $abook = new AddressBook
;
38 /* Create empty error message */
42 Always add a local backend. We use *either* file-based *or* a
43 database addressbook. If $addrbook_dsn is set, the database
44 backend is used. If not, addressbooks are stores in files.
46 if (isset($addrbook_dsn) && !empty($addrbook_dsn)) {
48 if (!isset($addrbook_table) ||
empty($addrbook_table)) {
49 $addrbook_table = 'address';
51 $r = $abook->add_backend('database', Array('dsn' => $addrbook_dsn,
53 'table' => $addrbook_table));
54 if (!$r && $showerr) {
55 $abook_init_error.=_("Error initializing address book database.") . "\n" . $abook->error
;
59 $filename = getHashedFile($username, $data_dir, "$username.abook");
60 $r = $abook->add_backend('local_file', Array('filename' => $filename,
63 // no need to use $abook->error, because message explains error.
64 $abook_init_error.=sprintf( _("Error opening file %s"), $filename );
68 /* Global file based addressbook */
69 if (isset($abook_global_file) &&
70 isset($abook_global_file_writeable) &&
71 isset($abook_global_file_listing) &&
72 trim($abook_global_file)!=''){
74 // Detect place of address book
75 if (! preg_match("/[\/\\\]/",$abook_global_file)) {
76 /* no path chars, address book stored in data directory
77 * make sure that there is a slash between data directory
78 * and address book file name
80 $abook_global_filename=$data_dir
81 . ((substr($data_dir, -1) != '/') ?
'/' : '')
83 } elseif (preg_match("/^\/|\w:/",$abook_global_file)) {
84 // full path is set in options (starts with slash or x:)
85 $abook_global_filename=$abook_global_file;
87 $abook_global_filename=SM_PATH
. $abook_global_file;
90 $r = $abook->add_backend('local_file',array('filename'=>$abook_global_filename,
91 'name' => _("Global address book"),
92 'detect_writeable' => false,
93 'writeable'=> $abook_global_file_writeable,
94 'listing' => $abook_global_file_listing));
96 /* global abook init error is not fatal. add error message and continue */
97 if (!$r && $showerr) {
98 if ($abook_init_error!='') $abook_init_error.="\n";
99 $abook_init_error.=_("Error initializing global address book.") . "\n" . $abook->error
;
103 /* Load global addressbook from SQL if configured */
104 if (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) {
105 /* Database configured */
106 if (!isset($addrbook_global_table) ||
empty($addrbook_global_table)) {
107 $addrbook_global_table = 'global_abook';
109 $r = $abook->add_backend('database',
110 Array('dsn' => $addrbook_global_dsn,
112 'name' => _("Global address book"),
113 'writeable' => $addrbook_global_writeable,
114 'listing' => $addrbook_global_listing,
115 'table' => $addrbook_global_table));
116 /* global abook init error is not fatal. add error message and continue */
117 if (!$r && $showerr) {
118 if ($abook_init_error!='') $abook_init_error.="\n";
119 $abook_init_error.=_("Error initializing global address book.") . "\n" . $abook->error
;
124 * hook allows to include different address book backends.
125 * plugins should extract $abook and $r from arguments
126 * and use same add_backend commands as above functions.
127 * Since 1.5.2 hook sends third ($onlylocal) argument to address book
128 * plugins in order to allow detection of local address book init.
129 * @since 1.5.1 and 1.4.5
131 $hookReturn = do_hook('abook_init', $abook, $r, $onlylocal);
132 $abook = $hookReturn[1];
134 if (!$r && $showerr) {
135 if ($abook_init_error!='') $abook_init_error.="\n";
136 $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 * Display the "new address" form
174 * Form is not closed and you must add closing form tag.
176 * @param string $form_url form action url
177 * @param string $name form name
178 * @param string $title form title
179 * @param string $button form button name
180 * @param array $defdata values of form fields
182 function abook_create_form($form_url,$name,$title,$button,$defdata=array()) {
184 echo addForm($form_url, 'post', 'f_add').
187 html_tag( 'td', "\n". '<strong>' . $title . '</strong>' . "\n",
191 , 'center', '', 'width="90%"' ) ."\n";
192 address_form($name, $button, $defdata);
197 * Had to move this function outside of the Addressbook Class
198 * PHP 4.0.4 Seemed to be having problems with inline functions.
199 * Note: this can return now since we don't support 4.0.4 anymore.
201 function addressbook_cmp($a,$b) {
203 if($a['backend'] > $b['backend']) {
205 } else if($a['backend'] < $b['backend']) {
209 return (strtolower($a['name']) > strtolower($b['name'])) ?
1 : -1;
214 * Make an input field
215 * @param string $label
216 * @param string $field
217 * @param string $name
218 * @param string $size
219 * @param array $values
222 function addressbook_inp_field($label, $field, $name, $size, $values, $add='') {
224 $value = ( isset($values[$field]) ?
$values[$field] : '');
226 if (is_array($value)) {
227 $td_str = addSelect($name.'['.$field.']', $value);
229 $td_str = addInput($name.'['.$field.']', $value, $size);
233 return html_tag( 'tr' ,
234 html_tag( 'td', $label . ':', 'right', $color[4]) .
235 html_tag( 'td', $td_str, 'left', $color[4])
241 * Output form to add and modify address data
243 function address_form($name, $submittext, $values = array()) {
244 global $color, $squirrelmail_language;
246 if ($squirrelmail_language == 'ja_JP') {
247 echo html_tag( 'table',
248 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
249 ' <small>' . _("Must be unique") . '</small>') .
250 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
251 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
252 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
253 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
254 list_writable_backends($name) .
257 addSubmit($submittext, $name.'[SUBMIT]'),
258 'center', $color[4], 'colspan="2"')
260 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
262 echo html_tag( 'table',
263 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
264 ' <small>' . _("Must be unique") . '</small>') .
265 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
266 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
267 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
268 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
269 list_writable_backends($name) .
272 addSubmit($submittext, $name.'[SUBMIT]') ,
273 'center', $color[4], 'colspan="2"')
275 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
280 * Provides list of writeable backends.
281 * Works only when address is added ($name='addaddr')
282 * @param string $name name of form
283 * @return string html formated backend field (select or hidden)
285 function list_writable_backends($name) {
286 global $color, $abook;
287 if ( $name != 'addaddr' ) { return; }
288 $writeable_abook = 1;
289 if ( $abook->numbackends
> 1 ) {
290 $backends = $abook->get_backend_list();
291 $writeable_abooks=array();
292 while (list($undef,$v) = each($backends)) {
294 // add each backend to array
295 $writeable_abooks[$v->bnum
]=$v->sname
;
296 // save backend number
297 $writeable_abook=$v->bnum
;
300 if (count($writeable_abooks)>1) {
301 // we have more than one writeable backend
302 $ret=addSelect('backend',$writeable_abooks,null,true);
303 return html_tag( 'tr',
304 html_tag( 'td', _("Add to:"),'right', $color[4] ) .
305 html_tag( 'td', $ret, 'left', $color[4] )) . "\n";
308 // Only one backend exists or is writeable.
309 return html_tag( 'tr',
311 addHidden('backend', $writeable_abook),
312 'center', $color[4], 'colspan="2"')) . "\n";
316 * Sort array by the key "name"
318 function alistcmp($a,$b) {
319 $abook_sort_order=get_abook_sort();
321 switch ($abook_sort_order) {
324 $abook_sort='nickname';
341 if ($a['backend'] > $b['backend']) {
344 if ($a['backend'] < $b['backend']) {
349 if( (($abook_sort_order+
2) %
2) == 1) {
350 return (strtolower($a[$abook_sort]) < strtolower($b[$abook_sort])) ?
1 : -1;
352 return (strtolower($a[$abook_sort]) > strtolower($b[$abook_sort])) ?
1 : -1;
357 * Address book sorting options
359 * returns address book sorting order
360 * @return integer book sorting options order
362 function get_abook_sort() {
363 global $data_dir, $username;
365 /* get sorting order */
366 if(sqgetGlobalVar('abook_sort_order', $temp, SQ_GET
)) {
367 $abook_sort_order = (int) $temp;
369 if ($abook_sort_order < 0 or $abook_sort_order > 8)
372 setPref($data_dir, $username, 'abook_sort_order', $abook_sort_order);
374 /* get previous sorting options. default to unsorted */
375 $abook_sort_order = getPref($data_dir, $username, 'abook_sort_order', 8);
378 return $abook_sort_order;
382 * This function shows the address book sort button.
384 * @param integer $abook_sort_order current sort value
385 * @param string $alt_tag alt tag value (string visible to text only browsers)
386 * @param integer $Down sort value when list is sorted ascending
387 * @param integer $Up sort value when list is sorted descending
388 * @return string html code with sorting images and urls
390 function show_abook_sort_button($abook_sort_order, $alt_tag, $Down, $Up ) {
391 global $form_url, $icon_theme_path;
393 /* Figure out which image we want to use. */
394 if ($abook_sort_order != $Up && $abook_sort_order != $Down) {
395 $img = 'sort_none.png';
396 $text_icon = '◻'; // U+25FB WHITE MEDIUM SQUARE
398 } elseif ($abook_sort_order == $Up) {
399 $img = 'up_pointer.png';
400 $text_icon = '⇧'; // U+21E7 UPWARDS WHITE ARROW
403 $img = 'down_pointer.png';
404 $text_icon = '⇩'; // U+21E9 DOWNWARDS WHITE ARROW
408 /* Now that we have everything figured out, show the actual button. */
409 return ' <a href="' . $form_url .'?abook_sort_order=' . $which .
410 '" style="text-decoration:none" title="'.$alt_tag.'">' .
411 getIcon($icon_theme_path, $img, $text_icon, $alt_tag) .
417 * This is the main address book class that connect all the
418 * backends and provide services to the functions above.
419 * @package squirrelmail
420 * @subpackage addressbook
424 * Enabled address book backends
427 var $backends = array();
429 * Number of enabled backends
432 var $numbackends = 0;
439 * id of backend with personal address book
442 var $localbackend = 0;
444 * Name of backend with personal address book
447 var $localbackendname = '';
449 * Controls use of 'extra' field
451 * Extra field can be used to add link to form, which allows
452 * to modify all fields supported by backend. This is the only field
453 * that is not sanitized with htmlspecialchars. Backends MUST make
454 * sure that field data is sanitized and displayed correctly inside
455 * table cell. Use of html formating in other address book fields is
456 * not allowed. Backends that don't return 'extra' row in address book
457 * data should not modify this object property.
461 var $add_extra_field = false;
464 * Constructor function.
466 function AddressBook() {
467 $this->localbackendname
= _("Personal address book");
471 * Return an array of backends of a given type,
472 * or all backends if no type is specified.
473 * @param string $type backend type
474 * @return array list of backends
476 function get_backend_list($type = '') {
478 for ($i = 1 ; $i <= $this->numbackends
; $i++
) {
479 if (empty($type) ||
$type == $this->backends
[$i]->btype
) {
480 $ret[] = &$this->backends
[$i];
487 /* ========================== Public ======================== */
492 * @param string $backend backend name (without the abook_ prefix)
493 * @param mixed optional variable that is passed to the backend constructor.
494 * See each of the backend classes for valid parameters
495 * @return integer number of backends
497 function add_backend($backend, $param = '') {
498 static $backend_classes;
499 if (!isset($backend_classes)) {
500 $backend_classes = array();
502 if (!isset($backend_classes[$backend])) {
504 * Support backend provided by plugins. Plugin function must
505 * return an associative array with as key the backend name ($backend)
506 * and as value the file including the path containing the backend class.
507 * i.e.: $aBackend = array('backend_template' => SM_PATH . 'plugins/abook_backend_template/functions.php')
509 * NB: Because the backend files are included from within this function they DO NOT have access to
510 * vars in the global scope. This function is the global scope for the included backend !!!
512 $aBackend = do_hook('abook_add_class');
513 if (isset($aBackend) && is_array($aBackend) && isset($aBackend[$backend])) {
514 require_once($aBackend[$backend]);
516 require_once(SM_PATH
. 'functions/abook_'.$backend.'.php');
518 $backend_classes[$backend] = true;
520 $backend_name = 'abook_' . $backend;
521 $newback = new $backend_name($param);
522 //eval('$newback = new ' . $backend_name . '($param);');
523 if(!empty($newback->error
)) {
524 $this->error
= $newback->error
;
528 $this->numbackends++
;
530 $newback->bnum
= $this->numbackends
;
531 $this->backends
[$this->numbackends
] = $newback;
533 /* Store ID of first local backend added */
534 if ($this->localbackend
== 0 && $newback->btype
== 'local') {
535 $this->localbackend
= $this->numbackends
;
536 $this->localbackendname
= $newback->sname
;
539 return $this->numbackends
;
544 * create string with name and email address
546 * This function takes a $row array as returned by the addressbook
547 * search and returns an e-mail address with the full name or
548 * nickname optionally prepended.
549 * @param array $row address book entry
550 * @return string email address with real name prepended
552 function full_address($row) {
553 global $addrsrch_fullname, $data_dir, $username;
554 $prefix = getPref($data_dir, $username, 'addrsrch_fullname');
555 if (($prefix != "" ||
(isset($addrsrch_fullname) &&
556 $prefix == $addrsrch_fullname)) && $prefix != 'noprefix') {
557 $name = ($prefix == 'nickname' ?
$row['nickname'] : $row['name']);
558 return $name . ' <' . trim($row['email']) . '>';
560 return trim($row['email']);
565 * Search for entries in address books
567 * Return a list of addresses matching expression in
568 * all backends of a given type.
569 * @param string $expression search expression
570 * @param integer $bnum backend number. default to search in all backends
571 * @return array search results
573 function search($expression, $bnum = -1) {
577 /* Search all backends */
579 $sel = $this->get_backend_list('');
581 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
582 $backend = &$sel[$i];
583 $backend->error
= '';
584 $res = $backend->search($expression);
585 if (is_array($res)) {
586 $ret = array_merge($ret, $res);
588 $this->error
.= "\n" . $backend->error
;
593 /* Only fail if all backends failed */
594 if( $failed >= sizeof( $sel ) ) {
600 /* Search only one backend */
602 $ret = $this->backends
[$bnum]->search($expression);
603 if (!is_array($ret)) {
604 $this->error
.= "\n" . $this->backends
[$bnum]->error
;
615 * @param string $expression search expression
616 * @param integer $bnum backend number. default to search in all backends
617 * @return array search results
619 function s_search($expression, $bnum = -1) {
621 $ret = $this->search($expression, $bnum);
622 if ( is_array( $ret ) ) {
623 usort($ret, 'addressbook_cmp');
630 * Lookup an address by alias.
631 * Only possible in local backends.
632 * @param string $alias
633 * @param integer backend number
634 * @return array lookup results. False, if not found.
636 function lookup($alias, $bnum = -1) {
641 $res = $this->backends
[$bnum]->lookup($alias);
642 if (is_array($res)) {
645 $this->error
= $this->backends
[$bnum]->error
;
650 $sel = $this->get_backend_list('local');
651 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
652 $backend = &$sel[$i];
653 $backend->error
= '';
654 $res = $backend->lookup($alias);
655 if (is_array($res)) {
659 $this->error
= $backend->error
;
669 * Return all addresses
670 * @param integer $bnum backend number
671 * @return array search results
673 function list_addr($bnum = -1) {
677 $sel = $this->get_backend_list('');
679 $sel = array(0 => &$this->backends
[$bnum]);
682 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
683 $backend = &$sel[$i];
684 $backend->error
= '';
685 $res = $backend->list_addr();
686 if (is_array($res)) {
687 $ret = array_merge($ret, $res);
689 $this->error
= $backend->error
;
698 * Create a new address
699 * @param array $userdata added address record
700 * @param integer $bnum backend number
701 * @return integer the backend number that the/ address was added
702 * to, or false if it failed.
704 function add($userdata, $bnum) {
707 if (!is_array($userdata)) {
708 $this->error
= _("Invalid input data");
711 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
712 $this->error
= _("Name is missing");
715 if (empty($userdata['email'])) {
716 $this->error
= _("E-mail address is missing");
719 if (empty($userdata['nickname'])) {
720 $userdata['nickname'] = $userdata['email'];
723 /* Blocks use of space, :, |, #, " and ! in nickname */
724 if (eregi('[ \\:\\|\\#\\"\\!]', $userdata['nickname'])) {
725 $this->error
= _("Nickname contains illegal characters");
729 /* Check that specified backend accept new entries */
730 if (!$this->backends
[$bnum]->writeable
) {
731 $this->error
= _("Address book is read-only");
735 /* Add address to backend */
736 $res = $this->backends
[$bnum]->add($userdata);
740 $this->error
= $this->backends
[$bnum]->error
;
744 return false; // Not reached
749 * Remove the entries from address book
750 * @param mixed $alias entries that have to be removed. Can be string with nickname or array with list of nicknames
751 * @param integer $bnum backend number
752 * @return bool true if removed successfully. false if there s an error. $this->error contains error message
754 function remove($alias, $bnum) {
761 /* Convert string to single element array */
762 if (!is_array($alias)) {
763 $alias = array(0 => $alias);
766 /* Check that specified backend is writable */
767 if (!$this->backends
[$bnum]->writeable
) {
768 $this->error
= _("Address book is read-only");
772 /* Remove user from backend */
773 $res = $this->backends
[$bnum]->remove($alias);
777 $this->error
= $this->backends
[$bnum]->error
;
781 return FALSE; /* Not reached */
782 } /* end of remove() */
786 * Modify entry in address book
787 * @param string $alias nickname
788 * @param array $userdata newdata
789 * @param integer $bnum backend number
791 function modify($alias, $userdata, $bnum) {
794 if (empty($alias) ||
!is_string($alias)) {
799 if(!is_array($userdata)) {
800 $this->error
= _("Invalid input data");
803 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
804 $this->error
= _("Name is missing");
807 if (empty($userdata['email'])) {
808 $this->error
= _("E-mail address is missing");
812 if (eregi('[\\: \\|\\#"\\!]', $userdata['nickname'])) {
813 $this->error
= _("Nickname contains illegal characters");
817 if (empty($userdata['nickname'])) {
818 $userdata['nickname'] = $userdata['email'];
821 /* Check that specified backend is writable */
822 if (!$this->backends
[$bnum]->writeable
) {
823 $this->error
= _("Address book is read-only");;
827 /* Modify user in backend */
828 $res = $this->backends
[$bnum]->modify($alias, $userdata);
832 $this->error
= $this->backends
[$bnum]->error
;
836 return FALSE; /* Not reached */
837 } /* end of modify() */
840 } /* End of class Addressbook */
843 * Generic backend that all other backends extend
844 * @package squirrelmail
845 * @subpackage addressbook
847 class addressbook_backend
{
849 /* Variables that all backends must provide. */
853 * Can be 'local' or 'remote'
854 * @var string backend type
856 var $btype = 'dummy';
858 * Internal backend name
861 var $bname = 'dummy';
863 * Displayed backend name
866 var $sname = 'Dummy backend';
869 * Variables common for all backends, but that
870 * should not be changed by the backends.
886 var $writeable = false;
890 * @param string $string error message
893 function set_error($string) {
894 $this->error
= '[' . $this->sname
. '] ' . $string;
899 /* ========================== Public ======================== */
902 * Search for entries in backend
904 * Working backend should support use of wildcards. * symbol
905 * should match one or more symbols. ? symbol should match any
907 * @param string $expression
910 function search($expression) {
911 $this->set_error('search is not implemented');
916 * Find entry in backend by alias
917 * @param string $alias name used for id
920 function lookup($alias) {
921 $this->set_error('lookup is not implemented');
926 * List all entries in backend
928 * Working backend should provide this function or at least
929 * dummy function that returns empty array.
932 function list_addr() {
933 $this->set_error('list_addr is not implemented');
938 * Add entry to backend
939 * @param array userdata
942 function add($userdata) {
943 $this->set_error('add is not implemented');
948 * Remove entry from backend
949 * @param string $alias name used for id
952 function remove($alias) {
953 $this->set_error('delete is not implemented');
958 * Modify entry in backend
959 * @param string $alias name used for id
960 * @param array $newuserdata new data
963 function modify($alias, $newuserdata) {
964 $this->set_error('modify is not implemented');
969 * Creates full name from given name and surname
971 * Handles name order differences
972 * @param string $firstname given name
973 * @param string $lastname surname
974 * @return string full name
977 function fullname($firstname,$lastname) {
978 global $squirrelmail_language;
979 if ($squirrelmail_language=='ja_JP') {
980 return trim($lastname . ' ' . $firstname);
982 return trim($firstname . ' ' . $lastname);