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-2006 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
129 $hookReturn = do_hook('abook_init', $abook, $r, $onlylocal);
130 $abook = $hookReturn[1];
132 if (!$r && $showerr) {
133 if ($abook_init_error!='') $abook_init_error.="\n";
134 $abook_init_error.=_("Error initializing other address books.") . "\n" . $abook->error
;
137 /* Load configured LDAP servers (if PHP has LDAP support) */
138 if (isset($ldap_server) && is_array($ldap_server)) {
140 while (list($undef,$param) = each($ldap_server)) {
141 if (!is_array($param))
144 /* if onlylocal is true, we only add writeable ldap servers */
145 if ($onlylocal && (!isset($param['writeable']) ||
$param['writeable'] != true))
148 $r = $abook->add_backend('ldap_server', $param);
149 if (!$r && $showerr) {
150 if ($abook_init_error!='') $abook_init_error.="\n";
151 $abook_init_error.=sprintf(_("Error initializing LDAP server %s:"), $param['host'])."\n";
152 $abook_init_error.= $abook->error
;
155 } // end of ldap server init
158 * display address book init errors.
160 if ($abook_init_error!='' && $showerr) {
161 error_box(nl2br(htmlspecialchars($abook_init_error)));
164 /* Return the initialized object */
169 * Display the "new address" form
171 * Form is not closed and you must add closing form tag.
173 * @param string $form_url form action url
174 * @param string $name form name
175 * @param string $title form title
176 * @param string $button form button name
177 * @param array $defdata values of form fields
179 function abook_create_form($form_url,$name,$title,$button,$defdata=array()) {
182 echo addForm($form_url, 'post', 'f_add');
184 if ($button == _("Update address")) {
189 $backends = getWritableBackends();
193 'nickname' => 'NickName',
194 'firstname' => 'FirstName',
195 'lastname' => 'LastName',
200 foreach ($fields as $sqm=>$template) {
201 $values[$template] = isset($defdata[$sqm]) ?
$defdata[$sqm] : '';
204 $oTemplate->assign('writable_backends', $backends);
205 $oTemplate->assign('values', $values);
206 $oTemplate->assign('edit', $edit);
208 $oTemplate->display('addrbook_addedit.tpl');
213 * Had to move this function outside of the Addressbook Class
214 * PHP 4.0.4 Seemed to be having problems with inline functions.
215 * Note: this can return now since we don't support 4.0.4 anymore.
217 function addressbook_cmp($a,$b) {
219 if($a['backend'] > $b['backend']) {
221 } else if($a['backend'] < $b['backend']) {
225 return (strtolower($a['name']) > strtolower($b['name'])) ?
1 : -1;
230 * Retrieve a list of writable backends
232 * @author Steve Brown
235 function getWritableBackends () {
239 $backends = $abook->get_backend_list();
240 while (list($undef,$v) = each($backends)) {
242 $write[$v->bnum
]=$v->sname
;
250 * Sort array by the key "name"
252 function alistcmp($a,$b) {
253 $abook_sort_order=get_abook_sort();
255 switch ($abook_sort_order) {
258 $abook_sort='nickname';
275 if ($a['backend'] > $b['backend']) {
278 if ($a['backend'] < $b['backend']) {
283 if( (($abook_sort_order+
2) %
2) == 1) {
284 return (strtolower($a[$abook_sort]) < strtolower($b[$abook_sort])) ?
1 : -1;
286 return (strtolower($a[$abook_sort]) > strtolower($b[$abook_sort])) ?
1 : -1;
291 * Address book sorting options
293 * returns address book sorting order
294 * @return integer book sorting options order
296 function get_abook_sort() {
297 global $data_dir, $username;
299 /* get sorting order */
300 if(sqgetGlobalVar('abook_sort_order', $temp, SQ_GET
)) {
301 $abook_sort_order = (int) $temp;
303 if ($abook_sort_order < 0 or $abook_sort_order > 8)
306 setPref($data_dir, $username, 'abook_sort_order', $abook_sort_order);
308 /* get previous sorting options. default to unsorted */
309 $abook_sort_order = getPref($data_dir, $username, 'abook_sort_order', 8);
312 return $abook_sort_order;
316 * This function shows the address book sort button.
318 * @param integer $abook_sort_order current sort value
319 * @param string $alt_tag alt tag value (string visible to text only browsers)
320 * @param integer $Down sort value when list is sorted ascending
321 * @param integer $Up sort value when list is sorted descending
322 * @return string html code with sorting images and urls
324 function show_abook_sort_button($abook_sort_order, $alt_tag, $Down, $Up ) {
325 global $form_url, $icon_theme_path;
327 /* Figure out which image we want to use. */
328 if ($abook_sort_order != $Up && $abook_sort_order != $Down) {
329 $img = 'sort_none.png';
330 $text_icon = '◻'; // U+25FB WHITE MEDIUM SQUARE
332 } elseif ($abook_sort_order == $Up) {
333 $img = 'up_pointer.png';
334 $text_icon = '⇧'; // U+21E7 UPWARDS WHITE ARROW
337 $img = 'down_pointer.png';
338 $text_icon = '⇩'; // U+21E9 DOWNWARDS WHITE ARROW
342 /* Now that we have everything figured out, show the actual button. */
343 return ' <a href="' . $form_url .'?abook_sort_order=' . $which .
344 '" style="text-decoration:none" title="'.$alt_tag.'">' .
345 getIcon($icon_theme_path, $img, $text_icon, $alt_tag) .
351 * This is the main address book class that connect all the
352 * backends and provide services to the functions above.
353 * @package squirrelmail
354 * @subpackage addressbook
358 * Enabled address book backends
361 var $backends = array();
363 * Number of enabled backends
366 var $numbackends = 0;
373 * id of backend with personal address book
376 var $localbackend = 0;
378 * Name of backend with personal address book
381 var $localbackendname = '';
383 * Controls use of 'extra' field
385 * Extra field can be used to add link to form, which allows
386 * to modify all fields supported by backend. This is the only field
387 * that is not sanitized with htmlspecialchars. Backends MUST make
388 * sure that field data is sanitized and displayed correctly inside
389 * table cell. Use of html formating in other address book fields is
390 * not allowed. Backends that don't return 'extra' row in address book
391 * data should not modify this object property.
395 var $add_extra_field = false;
398 * Constructor function.
400 function AddressBook() {
401 $this->localbackendname
= _("Personal address book");
405 * Return an array of backends of a given type,
406 * or all backends if no type is specified.
407 * @param string $type backend type
408 * @return array list of backends
410 function get_backend_list($type = '') {
412 for ($i = 1 ; $i <= $this->numbackends
; $i++
) {
413 if (empty($type) ||
$type == $this->backends
[$i]->btype
) {
414 $ret[] = &$this->backends
[$i];
421 /* ========================== Public ======================== */
426 * @param string $backend backend name (without the abook_ prefix)
427 * @param mixed optional variable that is passed to the backend constructor.
428 * See each of the backend classes for valid parameters
429 * @return integer number of backends
431 function add_backend($backend, $param = '') {
432 static $backend_classes;
433 if (!isset($backend_classes)) {
434 $backend_classes = array();
436 if (!isset($backend_classes[$backend])) {
438 * Support backend provided by plugins. Plugin function must
439 * return an associative array with as key the backend name ($backend)
440 * and as value the file including the path containing the backend class.
441 * i.e.: $aBackend = array('backend_template' => SM_PATH . 'plugins/abook_backend_template/functions.php')
443 * NB: Because the backend files are included from within this function they DO NOT have access to
444 * vars in the global scope. This function is the global scope for the included backend !!!
446 $aBackend = do_hook('abook_add_class');
447 if (isset($aBackend) && is_array($aBackend) && isset($aBackend[$backend])) {
448 require_once($aBackend[$backend]);
450 require_once(SM_PATH
. 'functions/abook_'.$backend.'.php');
452 $backend_classes[$backend] = true;
454 $backend_name = 'abook_' . $backend;
455 $newback = new $backend_name($param);
456 //eval('$newback = new ' . $backend_name . '($param);');
457 if(!empty($newback->error
)) {
458 $this->error
= $newback->error
;
462 $this->numbackends++
;
464 $newback->bnum
= $this->numbackends
;
465 $this->backends
[$this->numbackends
] = $newback;
467 /* Store ID of first local backend added */
468 if ($this->localbackend
== 0 && $newback->btype
== 'local') {
469 $this->localbackend
= $this->numbackends
;
470 $this->localbackendname
= $newback->sname
;
473 return $this->numbackends
;
478 * create string with name and email address
480 * This function takes a $row array as returned by the addressbook
481 * search and returns an e-mail address with the full name or
482 * nickname optionally prepended.
483 * @param array $row address book entry
484 * @return string email address with real name prepended
486 function full_address($row) {
487 global $addrsrch_fullname, $data_dir, $username;
488 $prefix = getPref($data_dir, $username, 'addrsrch_fullname');
489 if (($prefix != "" ||
(isset($addrsrch_fullname) &&
490 $prefix == $addrsrch_fullname)) && $prefix != 'noprefix') {
491 $name = ($prefix == 'nickname' ?
$row['nickname'] : $row['name']);
492 return $name . ' <' . trim($row['email']) . '>';
494 return trim($row['email']);
499 * Search for entries in address books
501 * Return a list of addresses matching expression in
502 * all backends of a given type.
503 * @param string $expression search expression
504 * @param integer $bnum backend number. default to search in all backends
505 * @return array search results
507 function search($expression, $bnum = -1) {
511 /* Search all backends */
513 $sel = $this->get_backend_list('');
515 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
516 $backend = &$sel[$i];
517 $backend->error
= '';
518 $res = $backend->search($expression);
519 if (is_array($res)) {
520 $ret = array_merge($ret, $res);
522 $this->error
.= "\n" . $backend->error
;
527 /* Only fail if all backends failed */
528 if( $failed >= sizeof( $sel ) ) {
532 } elseif (! isset($this->backends
[$bnum])) {
533 /* make sure that backend exists */
534 $this->error
= _("Unknown address book backend");
538 /* Search only one backend */
540 $ret = $this->backends
[$bnum]->search($expression);
541 if (!is_array($ret)) {
542 $this->error
.= "\n" . $this->backends
[$bnum]->error
;
553 * @param string $expression search expression
554 * @param integer $bnum backend number. default to search in all backends
555 * @return array search results
557 function s_search($expression, $bnum = -1) {
559 $ret = $this->search($expression, $bnum);
560 if ( is_array( $ret ) ) {
561 usort($ret, 'addressbook_cmp');
568 * Lookup an address by alias.
569 * Only possible in local backends.
570 * @param string $alias
571 * @param integer backend number
572 * @return array lookup results. False, if not found.
574 function lookup($alias, $bnum = -1) {
579 if (!isset($this->backends
[$bnum])) {
580 $this->error
= _("Unknown address book backend");
583 $res = $this->backends
[$bnum]->lookup($alias);
584 if (is_array($res)) {
587 $this->error
= $this->backends
[$bnum]->error
;
592 $sel = $this->get_backend_list('local');
593 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
594 $backend = &$sel[$i];
595 $backend->error
= '';
596 $res = $backend->lookup($alias);
597 if (is_array($res)) {
601 $this->error
= $backend->error
;
611 * Return all addresses
612 * @param integer $bnum backend number
613 * @return mixed array with search results or boolean false on error.
615 function list_addr($bnum = -1) {
619 $sel = $this->get_backend_list('');
620 } elseif (! isset($this->backends
[$bnum])) {
621 /* make sure that backend exists */
622 $this->error
= _("Unknown address book backend");
625 $sel = array(0 => &$this->backends
[$bnum]);
628 for ($i = 0 ; $i < sizeof($sel) ; $i++
) {
629 $backend = &$sel[$i];
630 $backend->error
= '';
631 $res = $backend->list_addr();
632 if (is_array($res)) {
633 $ret = array_merge($ret, $res);
635 $this->error
= $backend->error
;
644 * Create a new address
645 * @param array $userdata added address record
646 * @param integer $bnum backend number
647 * @return integer the backend number that the/ address was added
648 * to, or false if it failed.
650 function add($userdata, $bnum) {
653 if (!is_array($userdata)) {
654 $this->error
= _("Invalid input data");
657 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
658 $this->error
= _("Name is missing");
661 if (empty($userdata['email'])) {
662 $this->error
= _("E-mail address is missing");
665 if (empty($userdata['nickname'])) {
666 $userdata['nickname'] = $userdata['email'];
669 /* Blocks use of space, :, |, #, " and ! in nickname */
670 if (eregi('[ \\:\\|\\#\\"\\!]', $userdata['nickname'])) {
671 $this->error
= _("Nickname contains illegal characters");
675 /* make sure that backend exists */
676 if (! isset($this->backends
[$bnum])) {
677 $this->error
= _("Unknown address book backend");
681 /* Check that specified backend accept new entries */
682 if (!$this->backends
[$bnum]->writeable
) {
683 $this->error
= _("Address book is read-only");
687 /* Add address to backend */
688 $res = $this->backends
[$bnum]->add($userdata);
692 $this->error
= $this->backends
[$bnum]->error
;
696 return false; // Not reached
701 * Remove the entries from address book
702 * @param mixed $alias entries that have to be removed. Can be string with nickname or array with list of nicknames
703 * @param integer $bnum backend number
704 * @return bool true if removed successfully. false if there s an error. $this->error contains error message
706 function remove($alias, $bnum) {
713 /* Convert string to single element array */
714 if (!is_array($alias)) {
715 $alias = array(0 => $alias);
718 /* make sure that backend exists */
719 if (! isset($this->backends
[$bnum])) {
720 $this->error
= _("Unknown address book backend");
724 /* Check that specified backend is writable */
725 if (!$this->backends
[$bnum]->writeable
) {
726 $this->error
= _("Address book is read-only");
730 /* Remove user from backend */
731 $res = $this->backends
[$bnum]->remove($alias);
735 $this->error
= $this->backends
[$bnum]->error
;
739 return FALSE; /* Not reached */
740 } /* end of remove() */
744 * Modify entry in address book
745 * @param string $alias nickname
746 * @param array $userdata newdata
747 * @param integer $bnum backend number
749 function modify($alias, $userdata, $bnum) {
752 if (empty($alias) ||
!is_string($alias)) {
757 if(!is_array($userdata)) {
758 $this->error
= _("Invalid input data");
761 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
762 $this->error
= _("Name is missing");
765 if (empty($userdata['email'])) {
766 $this->error
= _("E-mail address is missing");
770 if (eregi('[\\: \\|\\#"\\!]', $userdata['nickname'])) {
771 $this->error
= _("Nickname contains illegal characters");
775 if (empty($userdata['nickname'])) {
776 $userdata['nickname'] = $userdata['email'];
779 /* make sure that backend exists */
780 if (! isset($this->backends
[$bnum])) {
781 $this->error
= _("Unknown address book backend");
785 /* Check that specified backend is writable */
786 if (!$this->backends
[$bnum]->writeable
) {
787 $this->error
= _("Address book is read-only");;
791 /* Modify user in backend */
792 $res = $this->backends
[$bnum]->modify($alias, $userdata);
796 $this->error
= $this->backends
[$bnum]->error
;
800 return FALSE; /* Not reached */
801 } /* end of modify() */
804 } /* End of class Addressbook */
807 * Generic backend that all other backends extend
808 * @package squirrelmail
809 * @subpackage addressbook
811 class addressbook_backend
{
813 /* Variables that all backends must provide. */
817 * Can be 'local' or 'remote'
818 * @var string backend type
820 var $btype = 'dummy';
822 * Internal backend name
825 var $bname = 'dummy';
827 * Displayed backend name
830 var $sname = 'Dummy backend';
833 * Variables common for all backends, but that
834 * should not be changed by the backends.
850 var $writeable = false;
854 * @param string $string error message
857 function set_error($string) {
858 $this->error
= '[' . $this->sname
. '] ' . $string;
863 /* ========================== Public ======================== */
866 * Search for entries in backend
868 * Working backend should support use of wildcards. * symbol
869 * should match one or more symbols. ? symbol should match any
871 * @param string $expression
874 function search($expression) {
875 $this->set_error('search is not implemented');
880 * Find entry in backend by alias
881 * @param string $alias name used for id
884 function lookup($alias) {
885 $this->set_error('lookup is not implemented');
890 * List all entries in backend
892 * Working backend should provide this function or at least
893 * dummy function that returns empty array.
896 function list_addr() {
897 $this->set_error('list_addr is not implemented');
902 * Add entry to backend
903 * @param array userdata
906 function add($userdata) {
907 $this->set_error('add is not implemented');
912 * Remove entry from backend
913 * @param string $alias name used for id
916 function remove($alias) {
917 $this->set_error('delete is not implemented');
922 * Modify entry in backend
923 * @param string $alias name used for id
924 * @param array $newuserdata new data
927 function modify($alias, $newuserdata) {
928 $this->set_error('modify is not implemented');
933 * Creates full name from given name and surname
935 * Handles name order differences. Function always runs in SquirrelMail gettext domain.
936 * Plugins don't have to switch domains before calling this function.
937 * @param string $firstname given name
938 * @param string $lastname surname
939 * @return string full name
942 function fullname($firstname,$lastname) {
944 * i18n: allows to control fullname layout in address book listing
945 * first %s is for first name, second %s is for last name.
946 * Translate it to '%2$s %1$s', if surname must be displayed first in your language.
947 * Please note that variables can be set to empty string and extra formating
948 * (for example '%2$s, %1$s' as in 'Smith, John') might break. Use it only for
949 * setting name and surname order. scripts will remove all prepended and appended
952 return trim(sprintf(dgettext('squirrelmail',"%s %s"),$firstname,$lastname));