Minor Bug fix, localbackendname was being set in the wrong "scope".
[squirrelmail.git] / functions / addressbook.php
1 <?php
2 /**
3 * addressbook.php
4 *
5 * Copyright (c) 1999-2004 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 *
8 * Functions and classes for the addressbook system.
9 *
10 * @version $Id$
11 * @package squirrelmail
12 * @subpackage addressbook
13 */
14
15 /**
16 This is the path to the global site-wide addressbook.
17 It looks and feels just like a user's .abook file
18 If this is in the data directory, use "$data_dir/global.abook"
19 If not, specify the path as though it was accessed from the
20 src/ directory ("../global.abook" -> in main directory)
21
22 If you don't want a global site-wide addressbook, comment these
23 two lines out. (They are disabled by default.)
24
25 The global addressbook is unmodifiable by anyone. You must actually
26 use a shell script or whatnot to modify the contents.
27
28 global $data_dir, $address_book_global_filename;
29 $address_book_global_filename = "$data_dir/global.abook";
30
31 */
32
33 global $addrbook_dsn, $addrbook_global_dsn;
34
35 /**
36 Create and initialize an addressbook object.
37 Returns the created object
38 */
39 function addressbook_init($showerr = true, $onlylocal = false) {
40 global $data_dir, $username, $ldap_server, $address_book_global_filename;
41 global $addrbook_dsn, $addrbook_table;
42 global $addrbook_global_dsn, $addrbook_global_table, $addrbook_global_writeable, $addrbook_global_listing;
43
44 /* Create a new addressbook object */
45 $abook = new AddressBook;
46
47 /*
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.
51 */
52 if (isset($addrbook_dsn) && !empty($addrbook_dsn)) {
53 /* Database */
54 if (!isset($addrbook_table) || empty($addrbook_table)) {
55 $addrbook_table = 'address';
56 }
57 $r = $abook->add_backend('database', Array('dsn' => $addrbook_dsn,
58 'owner' => $username,
59 'table' => $addrbook_table));
60 if (!$r && $showerr) {
61 echo _("Error initializing addressbook database.");
62 exit;
63 }
64 } else {
65 /* File */
66 $filename = getHashedFile($username, $data_dir, "$username.abook");
67 $r = $abook->add_backend('local_file', Array('filename' => $filename,
68 'create' => true));
69 if(!$r && $showerr) {
70 printf( _("Error opening file %s"), $filename );
71 exit;
72 }
73
74 }
75
76 /* This would be for the global addressbook */
77 if (isset($address_book_global_filename)) {
78 $r = $abook->add_backend('global_file');
79 if (!$r && $showerr) {
80 echo _("Error initializing global addressbook.");
81 exit;
82 }
83 }
84
85 /* Load global addressbook from SQL if configured */
86 if (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) {
87 /* Database configured */
88 if (!isset($addrbook_global_table) || empty($addrbook_global_table)) {
89 $addrbook_global_table = 'global_abook';
90 }
91 $r = $abook->add_backend('database',
92 Array('dsn' => $addrbook_global_dsn,
93 'owner' => 'global',
94 'name' => _("Global address book"),
95 'writeable' => $addrbook_global_writeable,
96 'listing' => $addrbook_global_listing,
97 'table' => $addrbook_global_table));
98 }
99
100 /*
101 * hook allows to include different address book backends.
102 * plugins should extract $abook and $r from arguments
103 * and use same add_backend commands as above functions.
104 */
105 $hookReturn = do_hook('abook_init', $abook, $r);
106 $abook = $hookReturn[1];
107 $r = $hookReturn[2];
108
109 if ($onlylocal) {
110 return $abook;
111 }
112
113 /* Load configured LDAP servers (if PHP has LDAP support) */
114 if (isset($ldap_server) && is_array($ldap_server) && function_exists('ldap_connect')) {
115 reset($ldap_server);
116 while (list($undef,$param) = each($ldap_server)) {
117 if (is_array($param)) {
118 $r = $abook->add_backend('ldap_server', $param);
119 if (!$r && $showerr) {
120 printf( '&nbsp;' . _("Error initializing LDAP server %s:") .
121 "<br />\n", $param['host']);
122 echo '&nbsp;' . $abook->error;
123 exit;
124 }
125 }
126 }
127 }
128
129 /* Return the initialized object */
130 return $abook;
131 }
132
133 /**
134 * Display the "new address" form
135 *
136 * Form is not closed and you must add closing form tag.
137 * @since 1.5.1
138 * @param string $form_url form action url
139 * @param string $name form name
140 * @param string $title form title
141 * @param string $button form button name
142 * @param array $defdata values of form fields
143 */
144 function abook_create_form($form_url,$name,$title,$button,$defdata=array()) {
145 global $color;
146 echo addForm($form_url, 'post', 'f_add').
147 html_tag( 'table',
148 html_tag( 'tr',
149 html_tag( 'td', "\n". '<strong>' . $title . '</strong>' . "\n",
150 'center', $color[0]
151 )
152 )
153 , 'center', '', 'width="100%"' ) ."\n";
154 address_form($name, $button, $defdata);
155 }
156
157
158 /*
159 * Had to move this function outside of the Addressbook Class
160 * PHP 4.0.4 Seemed to be having problems with inline functions.
161 * Note: this can return now since we don't support 4.0.4 anymore.
162 */
163 function addressbook_cmp($a,$b) {
164
165 if($a['backend'] > $b['backend']) {
166 return 1;
167 } else if($a['backend'] < $b['backend']) {
168 return -1;
169 }
170
171 return (strtolower($a['name']) > strtolower($b['name'])) ? 1 : -1;
172
173 }
174
175 /**
176 * Make an input field
177 * @param string $label
178 * @param string $field
179 * @param string $name
180 * @param string $size
181 * @param array $values
182 * @param string $add
183 */
184 function addressbook_inp_field($label, $field, $name, $size, $values, $add='') {
185 global $color;
186 $value = ( isset($values[$field]) ? $values[$field] : '');
187
188 if (is_array($value)) {
189 $td_str = addSelect($name.'['.$field.']', $value);
190 } else {
191 $td_str = addInput($name.'['.$field.']', $value, $size);
192 }
193 $td_str .= $add ;
194
195 return html_tag( 'tr' ,
196 html_tag( 'td', $label . ':', 'right', $color[4]) .
197 html_tag( 'td', $td_str, 'left', $color[4])
198 )
199 . "\n";
200 }
201
202 /**
203 * Output form to add and modify address data
204 */
205 function address_form($name, $submittext, $values = array()) {
206 global $color, $squirrelmail_language;
207
208 if ($squirrelmail_language == 'ja_JP') {
209 echo html_tag( 'table',
210 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
211 ' <small>' . _("Must be unique") . '</small>') .
212 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
213 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
214 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
215 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
216 list_writable_backends($name) .
217 html_tag( 'tr',
218 html_tag( 'td',
219 addSubmit($submittext, $name.'[SUBMIT]'),
220 'center', $color[4], 'colspan="2"')
221 )
222 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
223 } else {
224 echo html_tag( 'table',
225 addressbook_inp_field(_("Nickname"), 'nickname', $name, 15, $values,
226 ' <small>' . _("Must be unique") . '</small>') .
227 addressbook_inp_field(_("E-mail address"), 'email', $name, 45, $values, '') .
228 addressbook_inp_field(_("First name"), 'firstname', $name, 45, $values, '') .
229 addressbook_inp_field(_("Last name"), 'lastname', $name, 45, $values, '') .
230 addressbook_inp_field(_("Additional info"), 'label', $name, 45, $values, '') .
231 list_writable_backends($name) .
232 html_tag( 'tr',
233 html_tag( 'td',
234 addSubmit($submittext, $name.'[SUBMIT]') ,
235 'center', $color[4], 'colspan="2"')
236 )
237 , 'center', '', 'border="0" cellpadding="1" width="90%"') ."\n";
238 }
239 }
240
241 function list_writable_backends($name) {
242 global $color, $abook;
243 if ( $name != 'addaddr' ) { return; }
244 if ( $abook->numbackends > 1 ) {
245 $ret = '<select name="backend">';
246 $backends = $abook->get_backend_list();
247 while (list($undef,$v) = each($backends)) {
248 if ($v->writeable) {
249 $ret .= '<option value="' . $v->bnum;
250 $ret .= '">' . $v->sname . "</option>\n";
251 }
252 }
253 $ret .= "</select>";
254 return html_tag( 'tr',
255 html_tag( 'td', _("Add to:"),'right', $color[4] ) .
256 html_tag( 'td', $ret, 'left', $color[4] )) . "\n";
257 } else {
258 return html_tag( 'tr',
259 html_tag( 'td',
260 addHidden('backend', '1'),
261 'center', $color[4], 'colspan="2"')) . "\n";
262 }
263 }
264
265 /**
266 * Sort array by the key "name"
267 */
268 function alistcmp($a,$b) {
269 $abook_sort_order=get_abook_sort();
270
271 switch ($abook_sort_order) {
272 case 0:
273 case 1:
274 $abook_sort='nickname';
275 break;
276 case 4:
277 case 5:
278 $abook_sort='email';
279 break;
280 case 6:
281 case 7:
282 $abook_sort='label';
283 break;
284 case 2:
285 case 3:
286 case 8:
287 default:
288 $abook_sort='name';
289 }
290
291 if ($a['backend'] > $b['backend']) {
292 return 1;
293 } else {
294 if ($a['backend'] < $b['backend']) {
295 return -1;
296 }
297 }
298
299 if( (($abook_sort_order+2) % 2) == 1) {
300 return (strtolower($a[$abook_sort]) < strtolower($b[$abook_sort])) ? 1 : -1;
301 } else {
302 return (strtolower($a[$abook_sort]) > strtolower($b[$abook_sort])) ? 1 : -1;
303 }
304 }
305
306 /**
307 * Address book sorting options
308 *
309 * returns address book sorting order
310 * @return integer book sorting options order
311 */
312 function get_abook_sort() {
313 global $data_dir, $username;
314
315 /* get sorting order */
316 if(sqgetGlobalVar('abook_sort_order', $temp, SQ_GET)) {
317 $abook_sort_order = (int) $temp;
318
319 if ($abook_sort_order < 0 or $abook_sort_order > 8)
320 $abook_sort_order=8;
321
322 setPref($data_dir, $username, 'abook_sort_order', $abook_sort_order);
323 } else {
324 /* get previous sorting options. default to unsorted */
325 $abook_sort_order = getPref($data_dir, $username, 'abook_sort_order', 8);
326 }
327
328 return $abook_sort_order;
329 }
330
331 /**
332 * This function shows the address book sort button.
333 *
334 * @param integer $abook_sort_order current sort value
335 * @param string $alt_tag alt tag value (string visible to text only browsers)
336 * @param integer $Down sort value when list is sorted ascending
337 * @param integer $Up sort value when list is sorted descending
338 * @return string html code with sorting images and urls
339 */
340 function show_abook_sort_button($abook_sort_order, $alt_tag, $Down, $Up ) {
341 global $form_url;
342
343 /* Figure out which image we want to use. */
344 if ($abook_sort_order != $Up && $abook_sort_order != $Down) {
345 $img = 'sort_none.png';
346 $which = $Up;
347 } elseif ($abook_sort_order == $Up) {
348 $img = 'up_pointer.png';
349 $which = $Down;
350 } else {
351 $img = 'down_pointer.png';
352 $which = 8;
353 }
354
355 /* Now that we have everything figured out, show the actual button. */
356 return ' <a href="' . $form_url .'?abook_sort_order=' . $which
357 . '"><img src="../images/' . $img
358 . '" border="0" width="12" height="10" alt="' . $alt_tag . '" title="'
359 . _("Click here to change the sorting of the address list") .'" /></a>';
360 }
361
362
363 /**
364 * This is the main address book class that connect all the
365 * backends and provide services to the functions above.
366 * @package squirrelmail
367 * @subpackage addressbook
368 */
369 class AddressBook {
370
371 var $backends = array();
372 var $numbackends = 0;
373 var $error = '';
374 var $localbackend = 0;
375 var $localbackendname = '';
376
377 // Constructor function.
378 function AddressBook() {
379 $this->localbackendname = _("Personal address book");
380 }
381
382 /*
383 * Return an array of backends of a given type,
384 * or all backends if no type is specified.
385 */
386 function get_backend_list($type = '') {
387 $ret = array();
388 for ($i = 1 ; $i <= $this->numbackends ; $i++) {
389 if (empty($type) || $type == $this->backends[$i]->btype) {
390 $ret[] = &$this->backends[$i];
391 }
392 }
393 return $ret;
394 }
395
396
397 /*
398 ========================== Public ========================
399
400 Add a new backend. $backend is the name of a backend
401 (without the abook_ prefix), and $param is an optional
402 mixed variable that is passed to the backend constructor.
403 See each of the backend classes for valid parameters.
404 */
405 function add_backend($backend, $param = '') {
406 $backend_name = 'abook_' . $backend;
407 eval('$newback = new ' . $backend_name . '($param);');
408 if(!empty($newback->error)) {
409 $this->error = $newback->error;
410 return false;
411 }
412
413 $this->numbackends++;
414
415 $newback->bnum = $this->numbackends;
416 $this->backends[$this->numbackends] = $newback;
417
418 /* Store ID of first local backend added */
419 if ($this->localbackend == 0 && $newback->btype == 'local') {
420 $this->localbackend = $this->numbackends;
421 $this->localbackendname = $newback->sname;
422 }
423
424 return $this->numbackends;
425 }
426
427
428 /*
429 * This function takes a $row array as returned by the addressbook
430 * search and returns an e-mail address with the full name or
431 * nickname optionally prepended.
432 */
433
434 function full_address($row) {
435 global $addrsrch_fullname, $data_dir, $username;
436 $prefix = getPref($data_dir, $username, 'addrsrch_fullname');
437 if (($prefix != "" || (isset($addrsrch_fullname) &&
438 $prefix == $addrsrch_fullname)) && $prefix != 'noprefix') {
439 $name = ($prefix == 'nickname' ? $row['nickname'] : $row['name']);
440 return $name . ' <' . trim($row['email']) . '>';
441 } else {
442 return trim($row['email']);
443 }
444 }
445
446 /*
447 Return a list of addresses matching expression in
448 all backends of a given type.
449 */
450 function search($expression, $bnum = -1) {
451 $ret = array();
452 $this->error = '';
453
454 /* Search all backends */
455 if ($bnum == -1) {
456 $sel = $this->get_backend_list('');
457 $failed = 0;
458 for ($i = 0 ; $i < sizeof($sel) ; $i++) {
459 $backend = &$sel[$i];
460 $backend->error = '';
461 $res = $backend->search($expression);
462 if (is_array($res)) {
463 $ret = array_merge($ret, $res);
464 } else {
465 $this->error .= "<br />\n" . $backend->error;
466 $failed++;
467 }
468 }
469
470 /* Only fail if all backends failed */
471 if( $failed >= sizeof( $sel ) ) {
472 $ret = FALSE;
473 }
474
475 } else {
476
477 /* Search only one backend */
478
479 $ret = $this->backends[$bnum]->search($expression);
480 if (!is_array($ret)) {
481 $this->error .= "<br />\n" . $this->backends[$bnum]->error;
482 $ret = FALSE;
483 }
484 }
485
486 return( $ret );
487 }
488
489
490 /* Return a sorted search */
491 function s_search($expression, $bnum = -1) {
492
493 $ret = $this->search($expression, $bnum);
494 if ( is_array( $ret ) ) {
495 usort($ret, 'addressbook_cmp');
496 }
497 return $ret;
498 }
499
500
501 /*
502 * Lookup an address by alias. Only possible in
503 * local backends.
504 */
505 function lookup($alias, $bnum = -1) {
506
507 $ret = array();
508
509 if ($bnum > -1) {
510 $res = $this->backends[$bnum]->lookup($alias);
511 if (is_array($res)) {
512 return $res;
513 } else {
514 $this->error = $backend->error;
515 return false;
516 }
517 }
518
519 $sel = $this->get_backend_list('local');
520 for ($i = 0 ; $i < sizeof($sel) ; $i++) {
521 $backend = &$sel[$i];
522 $backend->error = '';
523 $res = $backend->lookup($alias);
524 if (is_array($res)) {
525 if(!empty($res))
526 return $res;
527 } else {
528 $this->error = $backend->error;
529 return false;
530 }
531 }
532
533 return $ret;
534 }
535
536
537 /* Return all addresses */
538 function list_addr($bnum = -1) {
539 $ret = array();
540
541 if ($bnum == -1) {
542 $sel = $this->get_backend_list('local');
543 } else {
544 $sel = array(0 => &$this->backends[$bnum]);
545 }
546
547 for ($i = 0 ; $i < sizeof($sel) ; $i++) {
548 $backend = &$sel[$i];
549 $backend->error = '';
550 $res = $backend->list_addr();
551 if (is_array($res)) {
552 $ret = array_merge($ret, $res);
553 } else {
554 $this->error = $backend->error;
555 return false;
556 }
557 }
558
559 return $ret;
560 }
561
562 /*
563 * Create a new address from $userdata, in backend $bnum.
564 * Return the backend number that the/ address was added
565 * to, or false if it failed.
566 */
567 function add($userdata, $bnum) {
568
569 /* Validate data */
570 if (!is_array($userdata)) {
571 $this->error = _("Invalid input data");
572 return false;
573 }
574 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
575 $this->error = _("Name is missing");
576 return false;
577 }
578 if (empty($userdata['email'])) {
579 $this->error = _("E-mail address is missing");
580 return false;
581 }
582 if (empty($userdata['nickname'])) {
583 $userdata['nickname'] = $userdata['email'];
584 }
585
586 if (eregi('[ \\:\\|\\#\\"\\!]', $userdata['nickname'])) {
587 $this->error = _("Nickname contains illegal characters");
588 return false;
589 }
590
591 /* Check that specified backend accept new entries */
592 if (!$this->backends[$bnum]->writeable) {
593 $this->error = _("Addressbook is read-only");
594 return false;
595 }
596
597 /* Add address to backend */
598 $res = $this->backends[$bnum]->add($userdata);
599 if ($res) {
600 return $bnum;
601 } else {
602 $this->error = $this->backends[$bnum]->error;
603 return false;
604 }
605
606 return false; // Not reached
607 } /* end of add() */
608
609
610 /*
611 * Remove the user identified by $alias from backend $bnum
612 * If $alias is an array, all users in the array are removed.
613 */
614 function remove($alias, $bnum) {
615
616 /* Check input */
617 if (empty($alias)) {
618 return true;
619 }
620
621 /* Convert string to single element array */
622 if (!is_array($alias)) {
623 $alias = array(0 => $alias);
624 }
625
626 /* Check that specified backend is writable */
627 if (!$this->backends[$bnum]->writeable) {
628 $this->error = _("Addressbook is read-only");
629 return false;
630 }
631
632 /* Remove user from backend */
633 $res = $this->backends[$bnum]->remove($alias);
634 if ($res) {
635 return $bnum;
636 } else {
637 $this->error = $this->backends[$bnum]->error;
638 return false;
639 }
640
641 return FALSE; /* Not reached */
642 } /* end of remove() */
643
644
645 /*
646 * Remove the user identified by $alias from backend $bnum
647 * If $alias is an array, all users in the array are removed.
648 */
649 function modify($alias, $userdata, $bnum) {
650
651 /* Check input */
652 if (empty($alias) || !is_string($alias)) {
653 return true;
654 }
655
656 /* Validate data */
657 if(!is_array($userdata)) {
658 $this->error = _("Invalid input data");
659 return false;
660 }
661 if (empty($userdata['firstname']) && empty($userdata['lastname'])) {
662 $this->error = _("Name is missing");
663 return false;
664 }
665 if (empty($userdata['email'])) {
666 $this->error = _("E-mail address is missing");
667 return false;
668 }
669
670 if (eregi('[\\: \\|\\#"\\!]', $userdata['nickname'])) {
671 $this->error = _("Nickname contains illegal characters");
672 return false;
673 }
674
675 if (empty($userdata['nickname'])) {
676 $userdata['nickname'] = $userdata['email'];
677 }
678
679 /* Check that specified backend is writable */
680 if (!$this->backends[$bnum]->writeable) {
681 $this->error = _("Addressbook is read-only");;
682 return false;
683 }
684
685 /* Modify user in backend */
686 $res = $this->backends[$bnum]->modify($alias, $userdata);
687 if ($res) {
688 return $bnum;
689 } else {
690 $this->error = $this->backends[$bnum]->error;
691 return false;
692 }
693
694 return FALSE; /* Not reached */
695 } /* end of modify() */
696
697
698 } /* End of class Addressbook */
699
700 /**
701 * Generic backend that all other backends extend
702 * @package squirrelmail
703 * @subpackage addressbook
704 */
705 class addressbook_backend {
706
707 /* Variables that all backends must provide. */
708 var $btype = 'dummy';
709 var $bname = 'dummy';
710 var $sname = 'Dummy backend';
711
712 /*
713 * Variables common for all backends, but that
714 * should not be changed by the backends.
715 */
716 var $bnum = -1;
717 var $error = '';
718 var $writeable = false;
719
720 function set_error($string) {
721 $this->error = '[' . $this->sname . '] ' . $string;
722 return false;
723 }
724
725
726 /* ========================== Public ======================== */
727
728 function search($expression) {
729 $this->set_error('search not implemented');
730 return false;
731 }
732
733 function lookup($alias) {
734 $this->set_error('lookup not implemented');
735 return false;
736 }
737
738 function list_addr() {
739 $this->set_error('list_addr not implemented');
740 return false;
741 }
742
743 function add($userdata) {
744 $this->set_error('add not implemented');
745 return false;
746 }
747
748 function remove($alias) {
749 $this->set_error('delete not implemented');
750 return false;
751 }
752
753 function modify($alias, $newuserdata) {
754 $this->set_error('modify not implemented');
755 return false;
756 }
757
758 }
759
760 /*
761 PHP 5 requires that the class be made first, which seems rather
762 logical, and should have been the way it was generated the first time.
763 */
764
765 require_once(SM_PATH . 'functions/abook_local_file.php');
766 require_once(SM_PATH . 'functions/abook_ldap_server.php');
767
768 /* Use this if you wanna have a global address book */
769 if (isset($address_book_global_filename)) {
770 include_once(SM_PATH . 'functions/abook_global_file.php');
771 }
772
773 /* Only load database backend if database is configured */
774 if((isset($addrbook_dsn) && !empty($addrbook_dsn)) ||
775 (isset($addrbook_global_dsn) && !empty($addrbook_global_dsn)) ) {
776 include_once(SM_PATH . 'functions/abook_database.php');
777 }
778
779 /*
780 * hook allows adding different address book classes.
781 * class must follow address book class coding standards.
782 *
783 * see addressbook_backend class and functions/abook_*.php files.
784 */
785 do_hook('abook_add_class');
786
787 ?>