File: ldapextras.pl

package info (click to toggle)
websieve 0.62-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 276 kB
  • ctags: 92
  • sloc: perl: 3,532; makefile: 53
file content (1360 lines) | stat: -rwxr-xr-x 47,896 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
#!/usr/bin/perl
# ldapextras.pl
# version 0.11
# licensed under the LGPL - see http://www.gnu.org
# Jules Agee
# August 17 2001
# configuration options need to be defined in ldapextras.conf

use Net::LDAP;

sub ldapextras {

    $userisadmin = 1 if( $uid eq $manageruid );
    $op='printuser' if (param('Refresh') && $op ne 'ldapsearch' && $op ne 'printdir' && $op ne 'printgroup');
    for( $op ) {
        /ldapsearch/	and do { undef $gomodifyit; ldapsearch();  last; };
        /printuser/	and do { undef $gomodifyit; printuser();   last; };
        /printdir/	and do { undef $gomodifyit; printuser();   last; };
        /printgroup/	and do { undef $gomodifyit; printgroup();  last; };
        /createuser/	and do { undef $gomodifyit; createuser();  last; };
        /creategroup/	and do { undef $gomodifyit; creategroup(); last; };
        /changeuser/	and do { undef $gomodifyit; changeuser();  last; };
        /changegroup/	and do { undef $gomodifyit; changegroup(); last; };
        /deleteuser/	and do { undef $gomodifyit; deleteuser();  last; };
        /deletegroup/	and do { undef $gomodifyit; deletegroup(); last; };
    }    
    return;
}


# Parses form data from the printuser HTML form when the op parameter
# is set to createuser, and creates a new INBOX and Trash folder,
# then creates an LDAP entry
sub createuser {
    checkbuttons();

    if( !$userisadmin ) {
        autherr();
        return;
    }
    
    # make sure the admin filled out at least the minimum number of fields to
    # successfully create an account
    my %reqatts = ( 'sn'=>'Last Name',
                    'givenname'=>'First Name',
                    'pass1'=>'Password',
                    'pass2'=>'Password (again)',
                    'ldapuid'=>'Employee UID'
                  );
    while( my( $att, $desc ) = each %reqatts ) {
        if( param( $att ) eq '' ) {
            printerr("\"$desc\" is a required field. Try again.");
            printuser();
            return;
        }
    }
    
    if( param( 'pass1' ) ne param( 'pass2' )) {
        printerr("Password fields don't match. Try again.");
        printuser();
        return;
    }
    # get user mail home host and partition data
    my $partition="";
    my $mailhost;
    $partition=param($mailpartitionatt) if (defined param($mailpartitionatt)); 
    $mailhost=param($mailhostatt) if (defined param($mailhostatt));
    # check if imap account needs to be created for this host
    my $isimap = 1;
    $isimap = 0 if ((grep/$mailhost/i,@nonimapmailhosts) || !$mailhost);
    #get user mail host connection data to create imap account on
    $mailhost=&getserverdata($mailhost) if $mailhost;

    # Get the new users data from the submitted HTML form
    $ldapperson_ou=",".$ldapperson_ou if ($ldapperson_ou);
    my $ldapuid = param( 'ldapuid' );
    my $mail = $ldapuid . "\@" . $maildomain;
    my $cn = param( 'givenname' ) ." ". param( 'sn' ) ." (". $ldapuid .")";
    my $dn = "cn=" . $cn . $ldapperson_ou . ",".$LDAP_BASEDN;
    param( 'dn', $dn );

    
    # if we need to create an imap account
    if ($isimap) {
        #close previous imap connection since we'll be re-opening one later
        closeimap();
        # create their mailboxes
        $imap = openimap( $uid, $pass, $mailhost, $imapport, $useimapSSL );
        my $err = createmailfolder( "user." . $ldapuid,$partition );
        if( $err ) {
            printerr( "createuser: imaperr $err" );
            return;
        }
        $err = createmailfolder( "user." . $ldapuid . ".Trash",$partition );
        if( $err ) {
            printerr( "createuser: imaperr $err" );
            return;
        }
        #also set quota if a value is entered..
        if (param('maxquota')) {
  	    my $maxquota = param( 'maxquota' );
    	    my $err = setquota( "user.$ldapuid", $maxquota );
        }
        closeimap();
    }
    $ldap = ldapbind();
    return if $ldap < 0;

    # here we're using the default LDAP atts array to start making a 
    # complete set of attributes for one user
    my $ldapentry = Net::LDAP::Entry->new;

    $ldapentry->dn( $dn );
    $ldapentry->add( %ldappersondefatts );
    $ldapentry->add( 'cn'=> $cn,
                     'uid'=> $ldapuid,
                     'mail'=> $mail,
                     'sn' => param( 'sn' ),
                     'givenname'=> param( 'givenname' ),
                     $ldappassattr=>encrypt( param( 'pass1' ))
		      
                   );

    # All possible entries for the @ldappersonatts array are defined
    # in the ldapextras.conf file, with the odd elements naming an LDAP attrib.
    # Or, the even elements, depending how you look at it. The first, third
    # and fifth elements of the array, or array index values 0, 2, 4...
    # In the loop below, for every @ldappersonatts attribute that is
    # defined in an HTML param in the current environment, we want to add
    # the name of the attribute and the value of its corresponding HTML param
    # to the $ldapentry object so we can just call $ldapentry->update to create
    # the user's directory entry
    
    for( $i = 0; $i < $#ldappersonatts; $i += 2 ) { 
        my $key = $ldappersonatts[ $i ];
        my $value = param( $key );
	#can add customized default values to selected attributes
	$value=&postaddentry($key,$value) if defined &postaddentry;
        if( $value ) {
            $ldapentry->add( $key => $value );
        }
    }
    #  add the values for multi line attributes
    for( $i = 0; $i < $#multilineatts; $i += 2 ) {
    	my $num=param($multilineatts[$i]."0.num");
	my @attvals;
        for ($j = 0;$j<=$num; $j++) {
	    push (@attvals,param($multilineatts[$i].$j)) if param($multilineatts[$i].$j);
        }
	# function in custom.pl to create customized default entries for 
	# multiline attributes such as for creating default
	# aliases for each uid
	@attvals=&postaddmulti($multilineatts[$i],@attvals) if defined &postaddmulti;
	$ldapentry->add($multilineatts[$i]=>[@attvals]) if @attvals;
    }

    my $result = $ldapentry->update( $ldap );

    if( $result->code ) {
        printerr( "createuser: error creating LDAP entry:". $result->error);
    } else {
        print "User ", param( 'cn' ), 
              " directory entry created successfully.<BR>";
    }
    $ldap->unbind;
    &postcreate if (defined &postcreate);
    param( 'entrytype', 'user' );
    print hidden( 'entrytype' );
    printuser();
    return; 
}


# Parses form data from the printgroup HTML form when the op parameter
# is set to creategroup, and creates a new LDAP entry for that group
sub creategroup {
    checkbuttons();

    if( !$userisadmin ) {
        autherr();
        return();
    }

    my $cn = param( 'cn' );
    $ldapgroup_ou=",".$ldapgroup_ou if ($ldapgroup_ou);
    my $dn = "cn=" . $cn .  $ldapgroup_ou . ",".$LDAP_BASEDN;
    my $mail = $cn . "\@" . $maildomain;

    my $ldap = ldapbind();
    return if $ldap < 0;

    # @memberDNs is a list of the DNs of entries we are adding to this group

    my @memberDNs;
    my @memberarray = split( '\n', param( 'memberchanges' ));
    my $filter = "(|";

    # for performance reasons we don't want to perform a separate search
    # for every DN in the group, so we'll build a search filter that will
    # only capture these DNs.
    for( @memberarray ) {
        chop;
        $filter .= "(cn=$_)(uid=$_)";
    }
    $filter .= ")";
    $mesg = $ldap->search( base=>$LDAP_BASEDN,
                           filter=>$filter,
                           attrs=>[ "uid", "cn", "objectClass" ]
                         );

    printerr("creategroup:" . $mesg->error) if( $mesg->code );
    @entries = $mesg->entries;
    for( @entries ) {
        push( @memberDNs, $_->dn() );
    }
    # here we're using the default LDAP atts array to start making a 
    # complete set of attributes for one group
    my $ldapentry = Net::LDAP::Entry->new;
    $ldapentry->dn( $dn );
    $ldapentry->add( %ldapgroupdefatts );
    $ldapentry->add( 'cn'=> $cn,
                     'mail'=> $mail,
                     $ldapmemberatt=>\@memberDNs
                   );

    my $result = $ldapentry->update( $ldap );

    if( $result->code ) {
        printerr( "creategroup: error creating LDAP entry:". $result->error);
    } else {
        print "Group ", param( 'cn' )," created successfully in directory.<BR>";
    }
    $ldap->unbind;
    &postcreate if (defined &postcreate);
    param( 'dn', $dn );
    param( 'entrytype', 'group' );
    print hidden( 'entrytype' );
    printgroup();
    return; 
}


# Parses form data from the printuser HTML form when the ldapaction parameter
# is set to changeuser, and makes changes to the user's LDAP directory entry and
# their quotas if necessary
sub changeuser {
    checkbuttons();

    if( !$userisadmin ) {
        autherr();
        return;
    }
    my $pass1 = param( 'pass1' );
    my $pass2 = param( 'pass2' );

    if( $pass1 ne $pass2 ) {
        printerr("Password fields don't match. Try again.");
        printuser();
        return;
    }

    my $ldapuid = param( 'ldapuid' );
    #get user mail host
    $mailhost= param($mailhostatt) if (defined param($mailhostatt));
    # check if imap account data needs to be retrieved for this host
    my $isimap = 1; 
    $isimap = 0 if ((grep/$mailhost/i,@nonimapmailhosts) || !$mailhost);
    $mailhost=&getserverdata($mailhost) if $mailhost; 
   
   # set new maxquota value
    my $maxquota = param( 'maxquota' );
    #close previous imap connection since we'll be re-opening one later
    if ($isimap) {
         closeimap();
    
         $imap = openimap( $uid, $pass, $mailhost, $imapport, $useimapSSL );
         my $err = setquota( "user.$ldapuid", $maxquota );
         closeimap();
    }
    my $ldap = ldapbind();
   my $dn = param( 'dn' );

    # get the existing entry for this user from the directory
    $ldapentry = ldapget( $ldap, $dn );

    # and update it with the new data
    for( $i = 0; $i < $#ldappersonatts; $i += 2 ) {
        #if value blank, put space to create a blank record but still allow
	#replication to occur error free
        param($ldappersonatts[$i]," ") if !param($ldappersonatts[$i]); 
        $ldapentry->replace( $ldappersonatts[ $i ]=>
                             param( $ldappersonatts[ $i ] )); 
    }
    #  update all values for multiple appearances of the same selected attribute
    for( $i = 0; $i < $#multilineatts; $i += 2 ) {
    	my $num=param($multilineatts[$i]."0.num");
	my @attvals;
        for ($j = 0;$j<=$num; $j++) {
	    push (@attvals,param($multilineatts[$i].$j)) if param($multilineatts[$i].$j);
        }
	@attvals=(" ") if !@attvals;
	$ldapentry->replace($multilineatts[$i]=>[@attvals]);
    }

    # change password if necessary
    if( $pass1 && $pass1 ne "" ) {
        $ldapentry->replace( $ldappassattr=>encrypt($pass1));
    }

    # and dump it all back onto the server
    my $result = $ldapentry->update( $ldap );
    if( $result->code ) {
        printerr( "changeuser: error changing LDAP entry:". $result->error);
    } else {
        print "User ", param( 'cn' )," updated successfully.<BR>";
    }

    $ldap->unbind;
    &postchange if (defined &postchange);
    undef $ldap;
    print hidden( 'entrytype', 'user' );
    printuser();
    return;
}


# Parses form data from the printgroup HTML form when the op parameter
# is set to changegroup, and makes changes to that group's directory entry
sub changegroup {
    checkbuttons();

    if( !$userisadmin ) {
        autherr();
        return;
    }

    my $dn = param( 'dn' );

    my $ldap = ldapbind();
    return if $ldap < 0;

    # @memberDNs is a list of the DNs of entries in this group

    my @memberDNs;
    my @memberarray = split( '\n', param( 'memberchanges' ));
    my $filter = "(|";

    # for performance reasons we don't want to perform a separate search
    # for every DN in the group, so we'll build a search filter that will
    # capture all the DNs in one search.
    for( @memberarray ) {
        chop;
        $filter .= "(cn=$_)(uid=$_)";
    }
    $filter .= ")";

    $mesg = $ldap->search( base=>$LDAP_BASEDN,
                           filter=>$filter,
                           attrs=>[ "uid", "cn", "objectClass" ]
                         );

    printerr("changegroup:" . $mesg->error) if( $mesg->code );
    @entries = $mesg->entries;
    for( @entries ) {
        push( @memberDNs, $_->dn() );
    }

    # get the existing entry for this group from the directory
    $ldapentry = ldapget( $ldap, $dn );

    # and update it with the new list of members
    $ldapentry->replace( $ldapmemberatt=>\@memberDNs );
    my $result = $ldapentry->update( $ldap );

    if( $result->code ) {
        printerr( "changegroup: error changing LDAP entry:". $result->error);
    } else {
        print "Group ", param( 'cn' )," updated successfully.<BR>";
    }
    $ldap->unbind;
    &postchange if (defined &postchange);
    param( 'dn', $dn );
    param( 'entrytype', 'group' );
    print hidden( 'entrytype' );
    printgroup();
    return; 
}


# Parses form data from the confirmdelete HTML form and deletes that user's
# LDAP entry and IMAP mailboxes. Also deletes references to that user from
# all mail groups.
sub deleteuser {

    if( !$userisadmin ) {
        autherr();
        return;
    }
    #get user mail host and connection data
    $mailhost= param($mailhostatt);
    # check if imap account needs to be deleted for this host
    my $isimap = 1; 
    $isimap = 0 if ((grep/$mailhost/i,@nonimapmailhosts) || !$mailhost);
    $mailhost=&getserverdata($mailhost) if $mailhost; 
    
    if ($isimap) { 
        #close previous imap connection since we'll be re-opening one later
        closeimap();
        $imap = openimap( $uid, $pass, $mailhost, $imapport, $useimapSSL );
        my $err = setacl( "user." . param( 'ldapuid' ), 
                      $uid, 
                      "lrswipcda" 
                    );
        $err .= deletemailbox( "user." . param( 'ldapuid' ));
        if( $err ) {
            printerr( "deleteuser: imapdelerr $err" );
            if( $err =~ m/Mailbox does not exist/ ) {
                print "<BR>LDAP entry only will be deleted<BR>";
            } else {
                return;
            }
        } else {
            print "IMAP account for " . param( 'ldapuid' ) . " deleted.<BR>";
        }
        closeimap();
     }
    $ldap = ldapbind();
    return if( $ldap < 0 );

    $err = "";
    my $dn = param( 'dn' );
    my $mesg = $ldap->delete( ldapclean( $dn ));
    $err .= $mesg->error if ( $mesg->code );

    # get a list of all groups this person was a member of
    my @groups;
    $mesg = $ldap->search( base=>$LDAP_BASEDN,
                              filter=>"( $ldapmemberatt=" .ldapclean($dn). ")",
                              attrs=>[ 'dn' ]
                            );
    $err .= $mesg->error if( $mesg->code );
    
    if( $err ) {
        printerr( "Deleting LDAP entry: $err" );
        return;
    }
    $err = "";
    
    my @results = $mesg->entries;
    foreach $result ( @results ) {
        push( @groups, $result->dn() );
    }

    my $whattodelete = { $ldapmemberatt, $dn };
  
    # And delete the user from each group he/she was listed in
    for( @groups ) {
        my $mesg = $ldap->modify( $_, delete=>$whattodelete );
        $err .= $mesg->error if( $mesg->code );
    }

    if( $err ) {
        printerr( "Deleting LDAP entries: $err" );
    } else {
        print "User ", param( 'cn' ), " deleted successfully.<BR>";
    }

    $ldap->unbind;
    &postdelete if (defined &postdelete);
    param( 'op', 'ldapsearch' );
    param( 'dn', '' );
    ldapsearch();
    return;
}


# Parses form data from the confirmdelete HTML form and deletes that group's
# entry from the directory

sub deletegroup {
    checkbuttons();

    if( !$userisadmin ) {
        autherr();
        return;
    }

    $ldap = ldapbind();
    return if( $ldap < 0 );

    my $err = "";
    my $dn = param( 'dn' );
    my $mesg = $ldap->delete( ldapclean( $dn ));
    $err = $mesg->error if ( $mesg->code );

    if( $err ) {
        printerr( "Deleting LDAP entries: $err" );
    } else {
        print "Group ", param( 'cn' ), " deleted successfully.<BR>";
    }

    $ldap->unbind;
    &postdelete if (defined &postdelete);
    param( 'op', 'ldapsearch' );
    param( 'dn', '' );
    ldapsearch();
    return;
}


# Prints a form asking the user to confirm the deletion of a user or group
# when the op attribute is set to confirmdelete. Possible op attribute values 
# generated from this form are deleteuser, deletegroup

sub confirmdelete {
    my $dn = param( 'dn' );
    my $cn = param( 'cn' );
    my $mailhost=param($mailhostatt);
    my $entrytype = param( 'entrytype' );

    if( !$userisadmin ) {
        autherr();
        return;
    }
    if(( $entrytype ne "user" )&&( $entrytype ne "group" )) {
        printerr( "Unknown entry type - can't delete entry $cn." );
        return;
    }
    $op = "delete" . $entrytype;
    param( 'op', $op );
    print hidden( 'dn' );
    print hidden( 'cn' );
    print hidden( 'ldapuid' );
    print hidden($mailhostatt);
    print "<CENTER><BR><H4> Confirm: Really delete $entrytype $cn from server $mailhost?</H4><BR>";
    print "<BR><CENTER>",submit("Confirm Delete"),"</CENTER>";
    print "<BR> If so, press the Confirm Delete button.\n";
    print "<BR> If not, press the back button in your browser.\n</CENTER>";
    return;
    exit;
}


# Prints an HTML form that lets an admin edit user data or create new users.
# If the user running this script doesn't have admin privs, it prints the data
# in a read-only format instead of as an editable form.
# Possible op attributes generated from this form are createuser and changeuser

sub printuser {
    my ( $getgroupinfo ) = @_;
    checkbuttons();
    ldapsearch();
    param( 'entrytype', 'user' );
    my $ldap = ldapbind();
    my $op = param( 'op' );
    my $isimap = 1;
    my $ldapdata;
    my $passvalue;
    my $entrytype = 'user';
    my $dn = param( 'dn' );
    #set default mailhost attribute to this server host name if it does'nt exist
    param($mailhostatt,$imapserver) if !param($mailhostatt);

    if ( $dn ) {
        # get user info from LDAP and ( if $userisadmin ) IMAP servers

        $ldapdata = ldapget( $ldap, $dn );
	return if !$ldapdata;
        # First we want to clear out all the HTML parameters in case $ldapdata
        # returns null values and fails to overwrite existing param values
        param( 'cn', '' );
        param( 'ldapuid', '' );
        param( 'mail', '' );
        param( 'sn', '' );
        param( 'givenname', '' );
        param( 'maxquota', '' );
   	param($mailhostatt,'');

	#get user mail host and connection data
	my $partition=scalar( $ldapdata->get_value($mailpartitionatt));
        my $mailhost=scalar( $ldapdata->get_value($mailhostatt));
        # check if imap data needs to be read for this host
    	$isimap = 0 if ((grep/$mailhost/i,@nonimapmailhosts) || !$mailhost);
	$mailhost=&getserverdata($mailhost) if $mailhost;

        if( $userisadmin) {
            $op = "changeuser";
	    if ($isimap) {
	        #close previous imap connection since we'll be re-opening one later
    	        closeimap();
                $imap = openimap($uid, $pass, $mailhost, $imapport, $useimapSSL);
                my @imapquota = 
                    getquota( "user." . scalar( $ldapdata->get_value( 'uid' )));
                param( 'usedquota',  $imapquota[1] );
                param( 'maxquota',  $imapquota[2] );
                closeimap();
	    }
        }

        param( 'cn',        scalar( $ldapdata->get_value( 'cn' )));
        param( 'ldapuid',   scalar( $ldapdata->get_value( 'uid' )));
        param( 'mail',      scalar( $ldapdata->get_value( 'mail' )));
        param( 'sn',        scalar( $ldapdata->get_value( 'sn' )));
        param( 'givenname', scalar( $ldapdata->get_value( 'givenname' )));

        # loop through the rest of the attributes
        for( $i = 0; $i < $#ldappersonatts; $i += 2 ) { 
            param( $ldappersonatts[ $i ], '' );
            param( $ldappersonatts[ $i ], 
                   scalar( $ldapdata->get_value( $ldappersonatts[ $i ] )));
        }
	# get all the values for the indicated multiple appearances of the same attribute
        for( $i = 0; $i < $#multilineatts; $i +=2  ) { 
            my @attvals = $ldapdata->get_value($multilineatts[$i] );
	    for ($j = 0;$j<=$#attvals; $j++) {
	        param( $multilineatts[ $i ].$j, '' );
                param( $multilineatts[ $i ].$j,$attvals[ $j ]);
	    }
	    param($multilineatts[$i]."0.num",$j);
        }



    } else {
        $op = "createuser" if( $userisadmin );
    }
    # print the HTML - different for users than admins
    print "<TABLE WIDTH=90%><TR><TD>";
    if( param( 'photo' )) {
        print "<IMG ALIGN=RIGHT SRC=", param( 'photo' ), " TITLE=\"Photo of ",
              param( 'cn' ), "\" >";
    }
    print "<CENTER>";
    if( $userisadmin ) {
        # print the screen that lets one make changes to user information 
        print "<TABLE WIDTH=60%><TR><TD>Employee UID:</TD><TD>";

        if( $op eq "changeuser" ) {  #user is admin and op is changeuser

            print param( 'ldapuid' ), "</TD></TR>\n<TR><TD>E-mail Address:<BR>";
            print "</TD><TD>", param( 'mail' ),"<BR>";
            print "</TD></TR>\n<TR><TD>Name:</TD><TD>",
                  param( 'givenname' ), " ", param( 'sn' );

            print hidden( 'entrytype' );
            print hidden( 'ldapuid' );
            print hidden( 'dn' );
            print hidden( 'mail' );
            print hidden( 'cn' );

            # Note that we don't allow the admin to change the user's uid.
            # With a Cyrus server using LDAP that would be a complex,
            # configuration-dependant process that would involve changing the
            # the RDN on the LDAP server, and on the Cyrus server we would have
            # to create a new user, then copy all the mailboxes from the user's
            # old account to their new one, and delete the old ones. With all
            # the possible different system configurations that seems risky
            # and very difficult to implement robustly. We'll just force
            # the admin to create a new user account and have the user copy
            # their messages from the old account to the new one.

        } else {      # user is admin and op is createuser
            # if not "changeuser" then $op must equal "createuser", so we will
            # need to allow the admin to enter the new user's uid and passwd

            print textfield( -name=>'ldapuid',
                             -maxlength=>40,
                             -size=>40
                           );
            print "</TD></TR>\n<TR><TD>First Name:</TD><TD>",
                  textfield(-name=>'givenname', 
                            -value=>param( 'givenname' ) || "",
                            -maxlength=>75,
                            -size=>40
                           );
            print "</TD></TR>\n<TR><TD>Last Name:</TD><TD>",
                  textfield(-name=>'sn',
                            -value=>param( 'sn' ) || "",
                            -maxlength=>75,
                            -size=>40
                           );

            if( $suggestpass ) {
                # suggest a random password when creating new users
                $passvalue = scalar( `$suggestpass` );
                chop( $passvalue );
            }
        }        # below here printed for any op value if user is admin
        if( $passvalue ) {  # if configured to suggest a default password
            # Note that if $suggestpasswd is undefined in the ldapextras.conf
            # file, $passvalue will always be undefined, too
            print "</TD></TR><TR><TD COLSPAN=2>A random alphabetic",
                  " password has been entered for your convenience.";
            print "</TD></TR><TR><TD>Password:</TD><TD>",
                   textfield( -name=>pass1,
                              -value=>$passvalue || "",
                              -override=>1,
                              -size=>40,
                              -maxlength=>15
                            );
            print "</TD></TR><TR><TD>Password (again):</TD><TD>",
                   textfield( -name=>pass2,
                              -value=>$passvalue || "",
                              -override=>1,
                              -size=>40,
                              -maxlength=>15
                            );
        } else {         #print blank password fields
            print "</TD></TR><TR><TD>Password:</TD><TD>",
                   password_field( -name=>pass1,
                                   -value=>"",
                                   -override=>1,
                                   -size=>40,
                                   -maxlength=>15
                                 );
            print "</TD></TR><TR><TD>Password (again):</TD><TD>",
                   password_field( -name=>pass2,
                                   -value=>"",
                                   -override=>1,
                                   -size=>40,
                                   -maxlength=>15
                                 );
        }
        # still in the userisadmin block
        #Loop through the rest of the attributes
        for( $i = 0; $i < $#ldappersonatts; $i += 2 ) { 
            print "</TD></TR>\n<TR><TD>", 
                  $ldappersonatts[ $i + 1 ], ":</TD><TD>";
	    if (!$allowchghost && ($op ne 'createuser') && ($ldappersonatts[$i] eq $mailhostatt || $ldappersonatts[$i] eq $mailpartitionatt)) {
	        # if attribute is the mailhost or mailpartition then
		# only display it since it can't be changed after a user account
		# is created
	    	print param($ldappersonatts[$i]);
		print hidden($ldappersonatts[$i]);
	    }
            elsif ( exists $ldapselectatts{$ldappersonatts[$i]}) {
		# if attribute exists in %ldapselectatts then display it
	    	# as a popup menu instead of a textfield entry
	    	print popup_menu($ldappersonatts[$i],[@{$ldapselectatts{$ldappersonatts[$i]}}],param($ldappersonatts[$i]));
	    }
                
	    elsif (exists $ldaptextareaatts{$ldappersonatts[$i]}) {	
	        #if the attribute is in %ldaptextareatts display it with the number
	        #of lines contained in the hash value for that attribute
		print textarea(-name=>$ldappersonatts[ $i ],
                               -value=>param( $ldappersonatts[ $i ] )||(""),
                               -rows=>$ldaptextareaatts{$ldappersonatts[$i]},
                               -columns=>38
                              );
	    }
            elsif( $ldappersonatts[ $i ] !~ /street/i ) {
	      # placed this attribute value in %ldaptextarea

                # for any attributes except the street address:
                print textfield(-name=>$ldappersonatts[ $i ],
                                -value=>param( $ldappersonatts[ $i ])||(""),
                                -maxlength=>75,
                                -size=>40
                               );

	     } else {  

                # print a textarea instead of textbox for street addresses
                print textarea(-name=>$ldappersonatts[ $i ],
                               -value=>param( $ldappersonatts[ $i ] )||(""),
                               -rows=>4,
                               -columns=>38
                              );
            
            }
        }
	### display the values of multiattributes plus one blank line for a new entry 
        for( $i = 0; $i < $#multilineatts; $i +=2  ) { 
	    my $num=param($multilineatts[$i]."0.num");
	    for ($j = 0;$j<=$num; $j++) {
                print "</TD></TR>\n<TR><TD>", 
                  $multilineatts[ $i + 1 ], ":</TD><TD>";
                print textfield(-name=>$multilineatts[ $i ].$j,
                                -value=>param($multilineatts[$i].$j)||(""),
                                -maxlength=>75,
                                -size=>40
                               );

	    }
	    param($multilineatts[$i]."0.num",$j);
	    print hidden($multilineatts[$i]."0.num");
        }

	# used to add custom form fields
        &postprint if (defined &postprint);
        if( ($op eq 'changeuser' || $op eq 'createuser')) {
            print "</TD></TR>\n<TR><TD>Disk Quota Limit (KB):</TD><TD>",
                  textfield(-name=>'maxquota',
                            -maxlength=>20,
                            -size=>40
                           ) if ($isimap);
	     print "</TD></TR>\n<TR><TD COLSPAN=2><CENTER>",submit('Create User'),
	         "</CENTER>" if $op eq 'createuser';
	     if ($op eq 'changeuser') {
                 print  "</TD></TR>\n<TR><TD>Disk Quota Used (KB):</TD><TD>", 
                  param('usedquota'), "</TD></TR>\n<TR><TD COLSPAN=2>";
                    print "<HR><CENTER>", submit( 'Save Changes' ),
                   submit( 'Get Group Info' ), submit( 'Delete This User' ), 
                   "</CENTER>";
	   }
        }
	print "</TD></TR></TABLE>\n";

    } else {    # if user is not the admin
        # print the screen ordinary mortals will see
        print hidden( 'dn' );
        print hidden( 'mail' );
        print hidden( 'cn' );
        print hidden( 'sn' );
        print hidden( 'givenname' );
	print hidden($mailhostatt);

        print "<TABLE WIDTH=60%><TR><TD>Employee:</TD><TD>", param( 'cn' ), 
            "</TD></TR>\n";
        print "<TR><TD>E-mail Address:</TD><TD>", param( 'mail' ), 
            "</TD></TR>\n";

        # loop through the rest of the attributes
        for( $i = 0; $i < $#ldappersonatts; $i += 2 ) { 
            next if exists $donotdisplay{ $ldappersonatts[ $i ] };
            print hidden( $ldappersonatts[ $i ] );
            if( param( $ldappersonatts[ $i ] )) {
                print "<TR><TD>", $ldappersonatts[ $i + 1 ], "</TD><TD>",
                      param( $ldappersonatts[ $i ] ), "</TD></TR>";
            }
        }

        print "<TR><TD COLSPAN=2><BR></TD></TR><TR><TD>",
              "Click here to see which e-mail groups<BR>",
              "will forward mail to this person. </TD><TD>";
        print submit( 'Get Group Info' );
        print "</TD></TR><TR><TD COLSPAN=2><BR></TD></TR></TABLE>\n";
    }     # Below here will apply whether or not $userisadmin


    getallgroups( $ldap, $dn, param( 'cn' )) if( $getgroupinfo ); 
    print "</TD></TR></TABLE>\n";
    $ldap->unbind;
    undef $ldap;
    param( 'op', $op );
    return;
}


# Prints an HTML form that lets an admin edit the members of a group.
# If the user running this script doesn't have admin privs, it prints the data
# read-only instead of as an HTML form, and members of the group are listed
# as links to display info about that member.
# Possible op attributes from this form are creategroup and changegroup 

sub printgroup {
    my $buttonpush = checkbuttons();
    return if( $buttonpush );

    # print the ldapsearch textbox
    ldapsearch();

    my $dn = param( 'dn' );
    my $ldap = ldapbind();

    if ( $dn ) {
        # get group info from LDAP server

        my $ldapdata = ldapget( $ldap, $dn );
	return if !$ldapdata;
        # clear out old param values in case $get_value returns null and fails
        # to overwrite the HTML parameter will a null value
        param( 'cn', '' );
        param( 'members', '' );

        param( 'cn', scalar( $ldapdata->get_value( 'cn' ))) if $ldapdata;

        my @members;
        my $entrytype;
        my $filter = "(|";
        my @memberarray = $ldapdata->get_value( $ldapmemberatt ) ;

        # for performance reasons we don't want to perform a seperate search
        # for every DN in the group, so we'll build a search filter that will
        # only capture these DNs.
        for( @memberarray ) {
            $_ =~ m/([^,]*),.*/;
            my $cn = ldapclean( $1 );
            $filter .= "($cn)";
        }
        $filter .= ")";

        $mesg = $ldap->search( base=>$LDAP_BASEDN,
                               filter=>$filter,
                               attrs=>[ "uid", "cn", "objectClass" ]
                             );
        printerr( "printgroup:" . $mesg->error ) if( $mesg->code );

        my @entries = $mesg->entries;
        my $count = 0;
        foreach $memberentry ( @entries ) {
            getentrytype( $memberentry );
            my $displayname;
            my $entrytype = $memberentry->get_value( 'entrytype' );
            my $cn = $memberentry->get_value( 'cn' );
            if( $entrytype eq 'group' ) {
                $displayname = $cn
            } else {
                $displayname = $memberentry->get_value( 'uid' );
            }
            my $dn = $memberentry->dn();
            
            # the data to be stored in the 'members' HTML param  will be a tab-
            # delimited string.
            # @members is an array of anonymous arrays. The first element of
            # these subarrays will be the line as written to the members HTML
            # param. The second and third elements will be the cn and entrytype
            # respectively, lowercased to use in sorting the @members array
            $members[ $count ] = [ $entrytype . "\t" . $displayname . "\t" .
                                          $cn . "\t" . $dn . "\n" ,
                              lc( $cn ),
                              $entrytype 
                             ];
            $count++;
        }

        # Sort @members first by entrytype, then alphabetically
        @members = sort {
            $b->[2] cmp $a->[2]
                    ||
            $a->[1] cmp $b->[1] 
        } @members; 

        # write the sorted results to the members HTML param
        my $output = "";
        for( @members ) {
           $output .= $_->[0];
        } 
        param( "members", $output );

        $op = 'changegroup' if( $userisadmin );
    } else {
        $op = 'creategroup' if( $userisadmin );
    } 

    my @members = split( /\n/, param( 'members' ));

    # print the HTML
    print "<CENTER>";

    if( $userisadmin ) {
        if( $op eq 'changegroup' ) {
            print "<H3>Members of Group ",param('cn'),":</H3><BR>";
            my $displaystring;
            print hidden( 'members' );
            print hidden( 'dn' );
            print hidden( 'cn' );
            for( @members ) {
                my ( $entrytype, $displayname, $cn, $dn ) = split( '\t' );
                $displaystring .= $displayname . "\n";    
            }
            param( 'memberchanges', '' );
            param( 'memberchanges', $displaystring );
            param( 'entrytype', 'group' );
            print hidden( 'entrytype' );
            print "<CENTER>";
            print textarea(-name=>'memberchanges',
                           -rows=>15,
                           -columns=>20
                          );
            print "<BR>", submit( 'Save Changes' ),
                          submit( 'Delete This Group' );
        } elsif( $op eq 'creategroup' ) {
            param( 'cn', '' );
            param( 'members', '' );
            print "Group Name:&nbsp;&nbsp;";
            print textfield( -name=>'cn',
                             -size=>10,
                             -maxlength=>40
                           );
            print "<BR><BR>" , textarea(-name=>'memberchanges',
                                        -rows=>30,
                                        -columns=>20
                                       );
	     print "<BR>",submit('Create Group');


        }
    } else {                     # print the page as everyday users will see it

        print "<H3>Members of Group ",param('cn'),":</H3><BR>";

        param( 'members', '' );
        param( 'mail', '' );
        print "<TABLE WIDTH=80%><TR>";

        my $count = -1;
        my $realop = $op;


        for ( @members ) {
            my ( $entrytype, $displayname, $cn, $dn ) = split( '\t' );

            param( 'op', "print" . $entrytype );
            param( 'dn', $dn );
            print "<TD WIDTH=33%><A HREF=", url( -query_string=>1 ), ">", $cn, 
                  "</A></TD>";
            print "</TR>\n<TR>" if(( ++$count % 3 ) == 2 );
        }    
        print "</TR></TABLE>\n";
        $op = $realop;
    }

    $ldap->unbind;
    undef $ldap;

    param( 'op', $op );
    return;
}


# Accepts a search string in an HTML param, searches the directory for entries
# that match the string, and prints an HTML page with a list of the matching
# entries. Matching entries are printed as HTML links to display info about
# those entries.
# Possible op attributes from this form are printgroup, printuser and ldapsearch

sub ldapsearch {
    # If the user entered a string to search for, search and get the results
    my $searchstring = param( 'searchstring' );
    param( 'searchstring', '' );
    my @results;
    my $realop = param( 'op' );
    if( $searchstring && $realop !~ /change/i) { 
        # make sure searchstring doesn't contain funny chars such as ';' that
        # might cause unpredictable behavior 
        $searchstring =~ s/[^\w\(\)\-]//;
        ldapclean( $searchstring );
        param( 'Search', '' );
        my $ldap = ldapbind();

        my $mesg = $ldap->search( base=>$LDAP_BASEDN,
                                  filter=>"(cn=\*$searchstring\*)",
                                  attrs=>[ "cn", "objectclass", "uid" ]
                                );
        printerr("ldapsearch error:" . $mesg->error) if( $mesg->code );
        @results = $mesg->entries(["cn"]);

        # Figure out whether each entry is a user or group 
        # and put that data into the entry perl object as attribute 'entrytype'
        # note that this data is not written to the LDAP server
        foreach $result ( @results ) {
            getentrytype( $result );
        }

        @results = sortldapentries( @results );

        $ldap->unbind;
        undef $ldap;

    }

    # print the HTML
    print "<CENTER><TABLE border=1 WIDTH=90%><TR $cb><TD $tb><CENTER>",
          "Search the Directory for:</TD></CENTER><TD $tb><CENTER>";
    print textfield( -name=>'searchstring',
                     -default=>$searchstring,
                     -size=>40,
                     -maxlength=>40
                   );
    print "</CENTER></TD><TD $tb><CENTER>", submit( 'Search' );
    print "</CENTER></TD></TR></TABLE>";
    if( $searchstring && @results ) {
        print "<BR><CENTER>You can get more information about any entry ",
              "listed below by clicking on it.<HR>";
    }
    print "<TABLE WIDTH=100% ALIGN=RIGHT><TR>";
    # print a table of all the LDAP entries that matched the searchstring
    my $count = -1;

    # prevent putting too much data in link query_string
    param( 'members', '' );
    param( 'mail', '' );

    foreach $result ( @results ) {
        my $dn = $result->dn;
        my ( $cn ) = $result->get_value( 'cn' );
        my ( $ldapuid ) = $result->get_value( 'uid' );
        $op = "print" . $result->get_value( 'entrytype' );

        # clear out previous values of params in case one of the get_value
        # calls returned null
        param( 'op', '' );
        param( 'dn', '' );
        param( 'cn', '' );
        param( 'ldapuid', '' );
        param( 'op', $op );
        param( 'dn', $dn );
        param( 'cn', $cn );
        param( 'ldapuid', $ldapuid );
        print "<TD WIDTH=33%><A HREF=", url( -query_string=>1 ), ">", $cn, 
              "</A></TD>";
        print "</TR>\n<TR>" if(( ++$count % 3 ) == 2 );
    }    
    if( !@results && $realop eq "ldapsearch" ) {
        print "<TD><CENTER><BR>",
              "Hint: Enter someone's first or last name, or the first few ",
              "letters of<BR>their e-mail address, or part of the name of an ",
              "e-mail group.</TD></CENTER>";
    }
    print "</TR></TABLE><BR><HR>\n";
    $op = $realop;
    param( 'op', $op );
    return;
}


# Accepts the entry's DN, a printable name, and a reference to a Net::LDAP object
# that has already been been successfully binded to (bound?). Uses the
# grouprecurse function to search the LDAP group structure to determine all
# groups that refer to that uid or cn, either directly or indirectly through
# references from groups that are members of other groups. 

sub getallgroups {
    my( $ldap, $dn, $name ) = @_;
    my @indirectgroups;
    my @directgroups;

    # first, we'll search for groups that the DN is directly a member of
    # so we can differentiate those from indirect ones when printing the HTML
    my $mesg = $ldap->search( base=>$LDAP_BASEDN,
                              filter=>"( $ldapmemberatt=" .ldapclean($dn). ")",
                              attrs=>[ 'dn' ]
                            );
    my $err .= $mesg->error if( $mesg->code );
    my @results = $mesg->entries;
    foreach $result ( @results ) {
        push( @directgroups, $result->dn() );
    }

    # then, we'll use the grouprecurse sub to get a list of all other groups
    # that contain groups that the DN is a member of to make sure we get 'em all
    for( @directgroups ) {
        my $arrayref = \@indirectgroups;
        my $count = 0;
        $err .= grouprecurse( $ldap, $arrayref, $_, $count );
        return $err if( $err );
    }

    # and print the HTML
    print "<TABLE WIDTH=60%><TR><TD>$name is a member of the following groups:",
          "</TD></TR><TR><TD><CENTER>\n";

    # prevent putting extra data in link querystring
    param( 'mail', '' );
    param( 'members', '' );

    for( @directgroups ) {
        my ( $cn ) = ldapgetatt( $ldap, $_, "cn" );
        param( 'op', "printgroup" );
        param( 'dn', $_ );
        print "<A HREF=", url(-query=>1), ">", $cn, "</A><BR>\n";
    }
    print "<BR></TD></TR><TR><TD>This user will also receive mail ",
          "sent to these groups:</TD></TR><TR><TD><CENTER>\n";
    for( @indirectgroups ) {
        my ( $cn ) = ldapgetatt( $ldap, $_, "cn" );
        param( 'op', "printgroup" );
        param( 'dn', $_ );
        print "<A HREF=", url(-query=>1), ">", $cn, "</A><BR>\n";
    }
    print "</TD></TR></TABLE>";
    return;
}

# recursive function called by getallgroups above. Accepts a reference to a
# Net::LDAP object that has already been binded successfully, a reference to the
# array that will be storing all the results, the name of the cn to search
# the groups in the directory for, and a counter variable to detect circular
# references.

sub grouprecurse {
    my( $ldap, $array, $dn, $count ) = @_;
    $count++;
    return "Error! Circular references in groups?\n" if( $count > 20 );
    my $mesg = $ldap->search( base=>$LDAP_BASEDN,
                              filter=>"( $ldapmemberatt=".ldapclean($dn).")",
                              attrs=>[ "dn" ]
                            );
    my $err .= $mesg->error if( $mesg->code );
    my @results = $mesg->entries;
    foreach $result ( @results ) {
        push( @$array, $result->dn );
        $err .= grouprecurse( $ldap, $array, $result->dn, $count );
    }
    return $err;
}


# Quick shortcut for typing $ldap->search(blah blah blah) if you only want
# the contents of one attribute from one dn. Returns an array containing
# the value(s) of that attribute for the dn in question.
sub ldapgetatt {
    my @results;
    my( $ldap, $dn, $attribute ) = @_;
    my $user = ldapget( $ldap, $dn );
    @results = $user->get_value( $attribute );
    return @results;
}

# Gets an entry from the LDAP server given the dn and a bound Net::LDAP object
sub ldapget {
    my( $ldap, $dn ) = @_;
    my $mesg = $ldap->search( base=>$dn,
                              filter=>"(objectclass=*)",
                            );
    if( $mesg->code ) {
        printerr( "ldapget: $dn <BR>" . $mesg->error );
    }
    my @entries = $mesg->entries;
    return $entries[0];
}


# Accepts a string containing error text and prints an error screen

sub printerr {
    my( $err ) = @_;
    print "<H3> Error: </H3><B> $err </B>";
    return;
}

# what to do in the even of an authentication err

sub autherr {
    printerr( "<BR>Think you're sneaky, huh? :)<BR>\nYou don't have access." );
    return;
}


# We need to escape certain characters to prevent Net::LDAP from interpreting
# some characters in DN's from screwing up LDAP searches when the DN is part
# of the searchfilter - this adds backslashes in front of parenthesis, asterisks
# or backslasheatts that appear as literal characters in the DN. 

sub ldapclean {
    my ( $dn ) = @_;
    $dn =~ s/([\(\)\\\*])/\\$1/g;
    return $dn;
}

# for a given Net::LDAP::Entry object, determine whether it's a user or group
# and add an attribute to that object called entrytype 
sub getentrytype {
    my ( $ldapentry ) = @_;
    my @objectclasses = $ldapentry->get_value( "objectClass" );
    for( @objectclasses ) {
        if( /person/i ) {
            $ldapentry->add('entrytype'=>'user');
            last;
        } elsif( /group/i ) {
            $ldapentry->add('entrytype'=>'group');
            last;
        }
    } 
}

# for a given array of Net::LDAP::Entry objects, sort the objects by
# entrytype (see getentrytype function above) and then alphabetically by cn
sub sortldapentries {
    my @results = @_;
    # sort the entries alphabetically and by entrytype
    @results = sort {
        lc( $b->get_value( 'entrytype' )) cmp lc( $a->get_value( 'entrytype' ))
        ||
        lc( $a->get_value( 'cn' ))        cmp lc( $b->get_value( 'cn' ))
    } @results;
        
    return @results;
}

# Bind to the LDAP directory as the current user, return the $ldap object
sub ldapbind {
    # first, bind anonymously to get the DN of the current user 
    my $ldap = Net::LDAP->new( $LDAP_SERVER ) || do {
        printerr( "ldapbind: Couldn't connect to LDAP server: $@" );
        return -1;
    };
    my $mesg = $ldap->bind;
    if ( $mesg->code ) {
        printerr( "ldapbind: couldn't bind anonymously: $@" );
        return -1;
    }
    $mesg = $ldap->search( base=>$LDAP_BASEDN,
                           filter=>"(uid=$uid)"
                         );

    my @entries = $mesg->entries;
    my $user = $entries[0]; 
    my $dn = $user->dn;
    $ldap->unbind;
    undef $ldap;
    $ldap = Net::LDAP->new( $LDAP_SERVER ) || do {
        printerr( "ldapbind: Couldn't connect to LDAP server: $@" );
        return -1;
    };
    $mesg = $ldap->bind( dn=>$dn, password=>$pass );
    if ( $mesg->code ) {
        printerr( "ldapbind: couldn't bind with dn $dn: $@" );
        return -1;
    }
    return $ldap;
}

# check for button pushes and run the appropriate function if
# they have been pushed
sub checkbuttons {

    if( param( 'Search' )) {
        param( 'Search', '' );
        param( 'op', 'ldapsearch' );
        ldapsearch();
        print hidden( 'op' );
        print end_form;
        print end_html;
        exit;
    }

    if( param( 'Delete This Group' )) {
        param( 'Delete This Group', '' );
        param( 'op', 'confirmdelete' );
        confirmdelete();
        print hidden( 'op' );
        print end_form;
        print end_html;
        exit;
    }

    if( param( 'Delete This User' )) {
        param( 'Delete This User', '' );
        param( 'op', 'confirmdelete' );
        confirmdelete();
        print hidden( 'op' );
        print end_form;
        print end_html;
        exit;
    }

    if( param( 'Get Group Info' )) {
        param( 'Get Group Info', "");
        printuser( "getgroupinfo" );
        print hidden( 'op' );
        print end_form;
        print end_html;
        exit;
    }
    return;
}

1; # make require happy