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
15 global $addrbook_dsn, $addrbook_global_dsn;
18 Create and initialize an addressbook object.
19 Returns the created object
21 function addressbook_init($showerr = true, $onlylocal = false) {
22 global $data_dir, $username, $ldap_server, $address_book_global_filename;
23 global $addrbook_dsn, $addrbook_table;
24 global $abook_global_file, $abook_global_file_writeable;
25 global $addrbook_global_dsn, $addrbook_global_table, $addrbook_global_writeable, $addrbook_global_listing;
27 /* Create a new addressbook object */
28 $abook = new AddressBook
;
31 Always add a local backend. We use *either* file-based *or* a
32 database addressbook. If $addrbook_dsn is set, the database
33 backend is used. If not, addressbooks are stores in files.
35 if (isset($addrbook_dsn) && !empty($addrbook_dsn)) {
37 if (!isset($addrbook_table) ||
empty($addrbook_table)) {
38 $addrbook_table = 'address';
40 $r = $abook->add_backend('database', Array('dsn' => $addrbook_dsn,
42 'table' => $addrbook_table));
43 if (!$r && $showerr) {
44 echo _("Error initializing addressbook database.");
49 $filename = getHashedFile($username, $data_dir, "$username.abook");
50 $r = $abook->add_backend('local_file', Array('filename' => $filename,
53 printf( _("Error opening file %s"), $filename );
59 /* This would be for the global addressbook */
60 if (isset($abook_global_file) && isset($abook_global_file_writeable)
61 && trim($abook_global_file)!=''){
62 // Detect place of address book
63 if (! preg_match("/[\/\\\]/",$abook_global_file)) {
64 /* no path chars, address book stored in data directory
65 * make sure that there is a slash between data directory
66 * and address book file name
68 $abook_global_filename=$data_dir
69 . ((substr($data_dir, -1) != '/') ?
'/' : '')
71 } elseif (preg_match("/^\/|\w:/",$abook_global_file)) {
72 // full path is set in options (starts with slash or x:)
73 $abook_global_filename=$abook_global_file;
75 $abook_global_filename=SM_PATH
. $abook_global_file;
77 $r = $abook->add_backend('local_file',array('filename'=>$abook_global_filename,
78 'name' => _("Global address book"),
79 'detect_writeable' => false,
80 'writeable'=> $abook_global_file_writeable));
81 if (!$r && $showerr) {
82 echo _("Error initializing global addressbook.");
87 /* Load global addressbook from SQL if configured */
88 if (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) {
89 /* Database configured */
90 if (!isset($addrbook_global_table) ||
empty($addrbook_global_table)) {
91 $addrbook_global_table = 'global_abook';
93 $r = $abook->add_backend('database',
94 Array('dsn' => $addrbook_global_dsn,
96 'name' => _("Global address book"),
97 'writeable' => $addrbook_global_writeable,
98 'listing' => $addrbook_global_listing,
99 'table' => $addrbook_global_table));
103 * hook allows to include different address book backends.
104 * plugins should extract $abook and $r from arguments
105 * and use same add_backend commands as above functions.
108 $hookReturn = do_hook('abook_init', $abook, $r);
109 $abook = $hookReturn[1];
116 /* Load configured LDAP servers (if PHP has LDAP support) */
117 if (isset($ldap_server) && is_array($ldap_server) && function_exists('ldap_connect')) {
119 while (list($undef,$param) = each($ldap_server)) {
120 if (is_array($param)) {
121 $r = $abook->add_backend('ldap_server', $param);
122 if (!$r && $showerr) {
123 printf( ' ' . _("Error initializing LDAP server %s:") .
124 "<br />\n", $param['host']);
125 echo ' ' . $abook->error
;
132 /* Return the initialized object */
137 * Display the "new address" form
139 * Form is not closed and you must add closing form tag.
141 * @param string $form_url form action url
142 * @param string $name form name
143 * @param string $title form title
144 * @param string $button form button name
145 * @param array $defdata values of form fields
147 function abook_create_form($form_url,$name,$title,$button,$defdata=array()) {
149 echo addForm($form_url, 'post', 'f_add').
152 html_tag( 'td', "\n". '<strong>' . $title . '</strong>' . "\n",
156 , 'center', '', 'width="100%"' ) ."\n";
157 address_form($name, $button, $defdata);
162 * Had to move this function outside of the Addressbook Class
163 * PHP 4.0.4 Seemed to be having problems with inline functions.
164 * Note: this can return now since we don't support 4.0.4 anymore.
166 function addressbook_cmp($a,$b) {
168 if($a['backend'] > $b['backend']) {
170 } else if($a['backend'] < $b['backend']) {
174 return (strtolower($a['name']) > strtolower($b['name'])) ?
1 : -1;
179 * Make an input field
180 * @param string $label
181 * @param string $field
182 * @param string $name
183 * @param string $size
184 * @param array $values
187 function addressbook_inp_field($label, $field, $name, $size, $values, $add='') {
189 $value = ( isset($values[$field]) ?
$values[$field] : '');
191 if (is_array($value)) {
192 $td_str = addSelect($name.'['.$field.']', $value);
194 $td_str = addInput($name.'['.$field.']', $value, $size);
198 return html_tag( 'tr' ,
199 html_tag( 'td', $label . ':', 'right', $color[4]) .
200 html_tag( 'td', $td_str, 'left', $color[4])
206 * Output form to add and modify address data
208 function address_form($name, $submittext, $values = array()) {
209 global $color, $squirrelmail_language;
211 if ($squirrelmail_language == 'ja_JP') {
212 echo html_tag( 'table',
213 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
214 ' <small>' . _("Must be unique") . '</small>') .
215 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
216 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
217 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
218 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
219 list_writable_backends($name) .
222 addSubmit($submittext, $name.'[SUBMIT]'),
223 'center', $color[4], 'colspan="2"')
225 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
227 echo html_tag( 'table',
228 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
229 ' <small>' . _("Must be unique") . '</small>') .
230 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
231 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
232 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
233 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
234 list_writable_backends($name) .
237 addSubmit($submittext, $name.'[SUBMIT]') ,
238 'center', $color[4], 'colspan="2"')
240 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
245 * Provides list of writeable backends.
246 * Works only when address is added ($name='addaddr')
247 * @param string $name name of form
248 * @return string html formated backend field (select or hidden)
250 function list_writable_backends($name) {
251 global $color, $abook;
252 if ( $name != 'addaddr' ) { return; }
253 $writeable_abook = 1;
254 if ( $abook->numbackends
> 1 ) {
255 $backends = $abook->get_backend_list();
256 $writeable_abooks=array();
257 while (list($undef,$v) = each($backends)) {
259 // add each backend to array
260 $writeable_abooks[$v->bnum
]=$v->sname
;
261 // save backend number
262 $writeable_abook=$v->bnum
;
265 if (count($writeable_abooks)>1) {
266 // we have more than one writeable backend
267 $ret=addSelect('backend',$writeable_abooks,null,true);
268 return html_tag( 'tr',
269 html_tag( 'td', _("Add to:"),'right', $color[4] ) .
270 html_tag( 'td', $ret, 'left', $color[4] )) . "\n";
273 // Only one backend exists or is writeable.
274 return html_tag( 'tr',
276 addHidden('backend', $writeable_abook),
277 'center', $color[4], 'colspan="2"')) . "\n";
281 * Sort array by the key "name"
283 function alistcmp($a,$b) {
284 $abook_sort_order=get_abook_sort();
286 switch ($abook_sort_order) {
289 $abook_sort='nickname';
306 if ($a['backend'] > $b['backend']) {
309 if ($a['backend'] < $b['backend']) {
314 if( (($abook_sort_order+
2) %
2) == 1) {
315 return (strtolower($a[$abook_sort]) < strtolower($b[$abook_sort])) ?
1 : -1;
317 return (strtolower($a[$abook_sort]) > strtolower($b[$abook_sort])) ?
1 : -1;
322 * Address book sorting options
324 * returns address book sorting order
325 * @return integer book sorting options order
327 function get_abook_sort() {
328 global $data_dir, $username;
330 /* get sorting order */
331 if(sqgetGlobalVar('abook_sort_order', $temp, SQ_GET
)) {
332 $abook_sort_order = (int) $temp;
334 if ($abook_sort_order < 0 or $abook_sort_order > 8)
337 setPref($data_dir, $username, 'abook_sort_order', $abook_sort_order);
339 /* get previous sorting options. default to unsorted */
340 $abook_sort_order = getPref($data_dir, $username, 'abook_sort_order', 8);
343 return $abook_sort_order;
347 * This function shows the address book sort button.
349 * @param integer $abook_sort_order current sort value
350 * @param string $alt_tag alt tag value (string visible to text only browsers)
351 * @param integer $Down sort value when list is sorted ascending
352 * @param integer $Up sort value when list is sorted descending
353 * @return string html code with sorting images and urls
355 function show_abook_sort_button($abook_sort_order, $alt_tag, $Down, $Up ) {
358 /* Figure out which image we want to use. */
359 if ($abook_sort_order != $Up && $abook_sort_order != $Down) {
360 $img = 'sort_none.png';
362 } elseif ($abook_sort_order == $Up) {
363 $img = 'up_pointer.png';
366 $img = 'down_pointer.png';
370 /* Now that we have everything figured out, show the actual button. */
371 return ' <a href="' . $form_url .'?abook_sort_order=' . $which
372 . '"><img src="../images/' . $img
373 . '" border="0" width="12" height="10" alt="' . $alt_tag . '" title="'
374 . _("Click here to change the sorting of the address list") .'" /></a>';
379 * This is the main address book class that connect all the
380 * backends and provide services to the functions above.
381 * @package squirrelmail
382 * @subpackage addressbook
386 * Enabled address book backends
389 var $backends = array();
391 * Number of enabled backends
394 var $numbackends = 0;
401 * id of backend with personal address book
404 var $localbackend = 0;
406 * Name of backend with personal address book
409 var $localbackendname = '';
412 * Constructor function.
414 function AddressBook() {
415 $this->localbackendname
= _("Personal address book");
419 * Return an array of backends of a given type,
420 * or all backends if no type is specified.
421 * @param string $type backend type
422 * @return array list of backends
424 function get_backend_list($type = '') {
426 for ($i = 1 ; $i <= $this->numbackends
; $i++
) {
427 if (empty($type) ||
$type == $this->backends
[$i]->btype
) {
428 $ret[] = &$this->backends
[$i];
435 /* ========================== Public ======================== */
440 * @param string $backend backend name (without the abook_ prefix)
441 * @param mixed optional variable that is passed to the backend constructor.
442 * See each of the backend classes for valid parameters
443 * @return integer number of backends
445 function add_backend($backend, $param = '') {
446 $backend_name = 'abook_' . $backend;
447 eval('$newback = new ' . $backend_name . '($param);');
448 if(!empty($newback->error
)) {
449 $this->error
= $newback->error
;
453 $this->numbackends++
;
455 $newback->bnum
= $this->numbackends
;
456 $this->backends
[$this->numbackends
] = $newback;
458 /* Store ID of first local backend added */
459 if ($this->localbackend
== 0 && $newback->btype
== 'local') {
460 $this->localbackend
= $this->numbackends
;
461 $this->localbackendname
= $newback->sname
;
464 return $this->numbackends
;
469 * create string with name and email address
471 * This function takes a $row array as returned by the addressbook
472 * search and returns an e-mail address with the full name or
473 * nickname optionally prepended.
474 * @param array $row address book entry
475 * @return string email address with real name prepended
477 function full_address($row) {
478 global $addrsrch_fullname, $data_dir, $username;
479 $prefix = getPref($data_dir, $username, 'addrsrch_fullname');
480 if (($prefix != "" ||
(isset($addrsrch_fullname) &&
481 $prefix == $addrsrch_fullname)) && $prefix != 'noprefix') {
482 $name = ($prefix == 'nickname' ?
$row['nickname'] : $row['name']);
483 return $name . ' <' . trim($row['email']) . '>';
485 return trim($row['email']);
490 * Search for entries in address books
492 * Return a list of addresses matching expression in
493 * all backends of a given type.
494 * @param string $expression search expression
495 * @param integer $bnum backend number. default to search in all backends
496 * @return array search results
498 function search($expression, $bnum = -1) {
502 /* Search all backends */
504 $sel = $this->get_backend_list('');
506 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
507 $backend = &$sel[$i];
508 $backend->error
= '';
509 $res = $backend->search($expression);
510 if (is_array($res)) {
511 $ret = array_merge($ret, $res);
513 $this->error
.= "<br />\n" . $backend->error
;
518 /* Only fail if all backends failed */
519 if( $failed >= sizeof( $sel ) ) {
525 /* Search only one backend */
527 $ret = $this->backends
[$bnum]->search($expression);
528 if (!is_array($ret)) {
529 $this->error
.= "<br />\n" . $this->backends
[$bnum]->error
;
540 * @param string $expression search expression
541 * @param integer $bnum backend number. default to search in all backends
542 * @return array search results
544 function s_search($expression, $bnum = -1) {
546 $ret = $this->search($expression, $bnum);
547 if ( is_array( $ret ) ) {
548 usort($ret, 'addressbook_cmp');
555 * Lookup an address by alias.
556 * Only possible in local backends.
557 * @param string $alias
558 * @param integer backend number
559 * @return array lookup results. False, if not found.
561 function lookup($alias, $bnum = -1) {
566 $res = $this->backends
[$bnum]->lookup($alias);
567 if (is_array($res)) {
570 $this->error
= $backend->error
;
575 $sel = $this->get_backend_list('local');
576 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
577 $backend = &$sel[$i];
578 $backend->error
= '';
579 $res = $backend->lookup($alias);
580 if (is_array($res)) {
584 $this->error
= $backend->error
;
594 * Return all addresses
595 * @param integer $bnum backend number
596 * @return array search results
598 function list_addr($bnum = -1) {
602 $sel = $this->get_backend_list('');
604 $sel = array(0 => &$this->backends
[$bnum]);
607 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
608 $backend = &$sel[$i];
609 $backend->error
= '';
610 $res = $backend->list_addr();
611 if (is_array($res)) {
612 $ret = array_merge($ret, $res);
614 $this->error
= $backend->error
;
623 * Create a new address
624 * @param array $userdata added address record
625 * @param integer $bnum backend number
626 * @return integer the backend number that the/ address was added
627 * to, or false if it failed.
629 function add($userdata, $bnum) {
632 if (!is_array($userdata)) {
633 $this->error
= _("Invalid input data");
636 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
637 $this->error
= _("Name is missing");
640 if (empty($userdata['email'])) {
641 $this->error
= _("E-mail address is missing");
644 if (empty($userdata['nickname'])) {
645 $userdata['nickname'] = $userdata['email'];
648 if (eregi('[ \\:\\|\\#\\"\\!]', $userdata['nickname'])) {
649 $this->error
= _("Nickname contains illegal characters");
653 /* Check that specified backend accept new entries */
654 if (!$this->backends
[$bnum]->writeable
) {
655 $this->error
= _("Addressbook is read-only");
659 /* Add address to backend */
660 $res = $this->backends
[$bnum]->add($userdata);
664 $this->error
= $this->backends
[$bnum]->error
;
668 return false; // Not reached
673 * Remove the entries from address book
674 * @param mixed $alias entries that have to be removed. Can be string with nickname or array with list of nicknames
675 * @param integer $bnum backend number
676 * @return bool true if removed successfully. false if there s an error. $this->error contains error message
678 function remove($alias, $bnum) {
685 /* Convert string to single element array */
686 if (!is_array($alias)) {
687 $alias = array(0 => $alias);
690 /* Check that specified backend is writable */
691 if (!$this->backends
[$bnum]->writeable
) {
692 $this->error
= _("Addressbook is read-only");
696 /* Remove user from backend */
697 $res = $this->backends
[$bnum]->remove($alias);
701 $this->error
= $this->backends
[$bnum]->error
;
705 return FALSE; /* Not reached */
706 } /* end of remove() */
710 * Modify entry in address book
711 * @param string $alias nickname
712 * @param array $userdata newdata
713 * @param integer $bnum backend number
715 function modify($alias, $userdata, $bnum) {
718 if (empty($alias) ||
!is_string($alias)) {
723 if(!is_array($userdata)) {
724 $this->error
= _("Invalid input data");
727 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
728 $this->error
= _("Name is missing");
731 if (empty($userdata['email'])) {
732 $this->error
= _("E-mail address is missing");
736 if (eregi('[\\: \\|\\#"\\!]', $userdata['nickname'])) {
737 $this->error
= _("Nickname contains illegal characters");
741 if (empty($userdata['nickname'])) {
742 $userdata['nickname'] = $userdata['email'];
745 /* Check that specified backend is writable */
746 if (!$this->backends
[$bnum]->writeable
) {
747 $this->error
= _("Addressbook is read-only");;
751 /* Modify user in backend */
752 $res = $this->backends
[$bnum]->modify($alias, $userdata);
756 $this->error
= $this->backends
[$bnum]->error
;
760 return FALSE; /* Not reached */
761 } /* end of modify() */
764 } /* End of class Addressbook */
767 * Generic backend that all other backends extend
768 * @package squirrelmail
769 * @subpackage addressbook
771 class addressbook_backend
{
773 /* Variables that all backends must provide. */
777 * Can be 'local' or 'remote'
778 * @var string backend type
780 var $btype = 'dummy';
782 * Internal backend name
785 var $bname = 'dummy';
787 * Displayed backend name
790 var $sname = 'Dummy backend';
793 * Variables common for all backends, but that
794 * should not be changed by the backends.
810 var $writeable = false;
814 * @param string $string error message
817 function set_error($string) {
818 $this->error
= '[' . $this->sname
. '] ' . $string;
823 /* ========================== Public ======================== */
826 * Search for entries in backend
827 * @param string $expression
830 function search($expression) {
831 $this->set_error('search not implemented');
836 * Find entry in backend by alias
837 * @param string $alias name used for id
840 function lookup($alias) {
841 $this->set_error('lookup not implemented');
846 * List all entries in backend
849 function list_addr() {
850 $this->set_error('list_addr not implemented');
855 * Add entry to backend
856 * @param array userdata
859 function add($userdata) {
860 $this->set_error('add not implemented');
865 * Remove entry from backend
866 * @param string $alias name used for id
869 function remove($alias) {
870 $this->set_error('delete not implemented');
875 * Modify entry in backend
876 * @param string $alias name used for id
877 * @param array $newuserdata new data
880 function modify($alias, $newuserdata) {
881 $this->set_error('modify not implemented');
887 PHP 5 requires that the class be made first, which seems rather
888 logical, and should have been the way it was generated the first time.
891 require_once(SM_PATH
. 'functions/abook_local_file.php');
892 require_once(SM_PATH
. 'functions/abook_ldap_server.php');
894 /* Only load database backend if database is configured */
895 if((isset($addrbook_dsn) && !empty($addrbook_dsn)) ||
896 (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) ) {
897 include_once(SM_PATH
. 'functions/abook_database.php');
901 * hook allows adding different address book classes.
902 * class must follow address book class coding standards.
904 * see addressbook_backend class and functions/abook_*.php files.
907 do_hook('abook_add_class');