misc fixes; added log function to login to help diagnose errors
[mirror/userdir-ldap-cgi.git] / search.cgi
1 #!/usr/bin/perl
2
3 # $Id: search.cgi,v 1.3 1999/12/11 07:03:45 tausq Exp $
4 # (c) 1999 Randolph Chung. Licensed under the GPL. <tausq@debian.org>
5
6 use lib '.';
7 use strict vars;
8 #use Apache::Registry;
9 use CGI;
10 use Util;
11 use URI::Escape;
12 use Net::LDAP qw(:all);
13
14 # Global settings...
15 my %config = &Util::ReadConfigFile;
16
17 my $query = new CGI;
18 my $id = $query->param('id');
19 my $authtoken = $query->param('authtoken');
20 my $password = &Util::CheckAuthToken($authtoken);
21 my $dosearch = $query->param('dosearch');
22 my $searchdn = $query->param('searchdn');
23 my $ldap = undef;
24
25 my $proto = ($ENV{HTTPS} ? "https" : "http");
26
27 sub DieHandler {
28   $ldap->unbind if (defined($ldap));
29 }
30
31 $SIG{__DIE__} = \&DieHandler;
32
33 if (!$dosearch) {
34   # No action yet, send back the search form...
35   print "Content-type: text/html\n\n";
36   open (F, "<$config{websearchhtml}") || &Util::HTMLError($!);
37   while (<F>) {
38     s/~id~/$id/g;
39     s/~authtoken~/$authtoken/g;    
40     print;
41   }
42   close F;
43 } else {
44   # Go ahead and construct the search terms
45   my %searchdata = (
46     cn             => { fuzzy => 'cnfuzzy', formname => 'cn' }, # First name
47     mn             => { fuzzy => 'mnfuzzy', formname => 'mn' }, # Middle name
48     sn             => { fuzzy => 'snfuzzy', formname => 'sn' }, # Last name
49     email          => { fuzzy => 'emailfuzzy', formname => 'email' }, # email
50     uid            => { fuzzy => 'uidfuzzy', formname => 'uid' }, # Login name
51     ircnick        => { fuzzy => 'ircfuzzy', formname => 'ircnick' }, # IRC nickname
52     keyfingerprint => { fuzzy => 'fpfuzzy', formname => 'fingerprint' }, # PGP/GPG fingerprint
53     c              => { formname => 'country'}, # Country
54   );
55
56   # Do a little preprocessing - strip the spaces out of the fingerprint
57   my $temp = $query->param('fingerprint');
58   $temp =~ s/ //g; $query->param('fingerprint', $temp);
59
60   # go through %searchdata and pull out all the search criteria the user
61   # specified...
62   my $filter = undef;
63   foreach (keys(%searchdata)) {
64     if ($query->param($searchdata{$_}{formname})) {    
65       if ($query->param($searchdata{$_}{fuzzy})) {
66         # fuzzy search
67         $filter .= "($_~=".$query->param($searchdata{$_}{formname}).")";
68       } else {
69         $filter .= "($_=".$query->param($searchdata{$_}{formname}).")";
70       }
71     }
72   }
73   
74   # Vacation is a special case
75   $filter .= "(onvacation=*)" if ($query->param('vacation'));
76
77   # AND all the search terms together
78   $filter = "(&$filter)";
79   
80   # Read in the result template...
81   my ($lineref, $dataspecref) = ParseResult($config{websearchresulthtml});
82
83   # Now, we are ready to connect to the LDAP server.
84   $ldap = Net::LDAP->new($config{ldaphost}) || &Util::HTMLError($!);
85   my $auth = 0;
86   my $mesg;
87
88   if ($id && $password) {
89     $mesg = $ldap->bind("uid=$id,$config{basedn}", password => $password);
90     $mesg->sync;
91     $auth = ($mesg->code == LDAP_SUCCESS);
92   }
93
94   if (!$auth) { # Not authenticated - either the above failed, or no password supplied
95     $ldap->bind;
96   }
97
98 #  &Util::HTMLPrint("Searching in $config{basedn} for $filter...\n");
99   
100   $mesg = $ldap->search(base   => ($searchdn ? $searchdn : $config{basedn}),
101                         filter => ($searchdn ? "(uid=*)" : $filter));
102   $mesg->code && &Util::HTMLError($mesg->error);
103
104   my %outsub; # this hash will contain all the substitution tokens in the output
105   $outsub{count} = $mesg->count; # Count number of requests, also ensures we're done with the search
106   $outsub{auth} = $authtoken;
107   $outsub{authtoken} = $authtoken; # alias
108   $outsub{id} = $id;
109   $outsub{searchresults} = undef;
110   
111   my $entries = $mesg->as_struct; # entries contain a hashref to all the search results
112   my ($dn, $attr, $data); 
113
114   # Format the output....
115   foreach $dn (sort {$entries->{$a}->{sn}->[0] <=> $entries->{$b}->{sn}->[0]} keys(%$entries)) {
116     $data = $entries->{$dn};
117
118     # These are local variables.. i have enough global vars as it is... <sigh>
119     my ($ufdn, $login, $name, $email, $fingerprint, $address, $latlong, $vacation, $created, $modified) = undef;
120     
121     $ufdn = $dn; # Net::LDAP does not have a dn2ufn function, but this is close enough :)
122     
123     # Assemble name, attach web page link if present.
124     $name = $data->{cn}->[0]." ".$data->{mn}->[0]." ".$data->{sn}->[0];
125     if (my $url = $data->{labeledurl}->[0]) {
126       $name = "<a href=\"$url\">$name</a>";
127     }
128     
129     # Add links to all email addresses
130     foreach (@{$data->{emailforward}}) {
131       $email .= "<br>" if ($email);
132       $email .= "<a href=\"mailto:$_\">$_</a>";
133     }
134
135     # Format PGP/GPG key fingerprints
136     my $fi;
137     foreach (@{$data->{keyfingerprint}}) {
138       $fingerprint .= "<br>" if ($fingerprint);
139       $fingerprint .= sprintf("%d:- <a href=\"fetchkey.cgi?fingerprint=%s\">%s</a>", ++$fi, $_, &Util::FormatFingerPrint($_));
140     }
141     
142     # Assemble addresses
143     $address = $data->{postaladdress}->[0] || "- unlisted -";
144     $address =~ s/\$/<br>/g;
145     $address .= "<br>".$data->{l}->[0]."<br>".&Util::LookupCountry($data->{c}->[0])."<br>".$data->{postalcode}->[0];
146
147     # Assemble latitude/longitude
148     $latlong  = $data->{latitude}->[0] || "none";
149     $latlong .= " / ";
150     $latlong .= $data->{longitude}->[0] || "none";    
151
152     # Modified/created time. TODO: maybe add is the name of the creator/modifier
153     $modified = &Util::FormatTimestamp($data->{modifytimestamp}->[0]);
154     $created =  &Util::FormatTimestamp($data->{createtimestamp}->[0]);
155
156     # Link in the debian login id 
157     $login = $data->{uid}->[0]."\@debian.org";
158     $login = "<a href=\"mailto:$login\">$login</a>";
159     
160     # See if the user has a vacation message
161     $vacation = $data->{onvacation}->[0];
162
163     # OK, now generate output... (i.e. put the output into the buffer )
164     $outsub{searchresults} .= '<table border=2 cellpadding=2 cellspacing=0 bgcolor="#DDDDDD" width="80%">';
165     $outsub{searchresults} .= '<tr><th bgcolor="#44CCCC" colspan=2><font size=+1>'."$name</font> ";
166     $outsub{searchresults} .= "($ufdn)</th></tr>\n";
167     
168     if ($vacation) {
169       $outsub{searchresults} .= "<tr><td colspan=2 align=center><b>$vacation</b></td></tr>\n";
170     }
171
172     $outsub{searchresults} .= FormatEntry($dataspecref->{uid}, $login);
173     $outsub{searchresults} .= FormatEntry($dataspecref->{ircnick}, $data->{ircnick}->[0]);
174     $outsub{searchresults} .= FormatEntry($dataspecref->{loginshell}, $data->{loginshell}->[0]);
175     $outsub{searchresults} .= FormatEntry($dataspecref->{fingerprint}, $fingerprint);
176     
177     if ($auth) {
178       # Some data should only be available to authorized users...
179       if ($id eq $data->{uid}->[0]) {
180         $outsub{searchresults} .= FormatEntry($dataspecref->{email}, $email);
181       }
182       $outsub{searchresults} .= FormatEntry($dataspecref->{address}, $address);
183       $outsub{searchresults} .= FormatEntry($dataspecref->{latlong}, $latlong);
184       $outsub{searchresults} .= FormatEntry($dataspecref->{phone}, $data->{telephonenumber}->[0] || "- unlisted -");
185       $outsub{searchresults} .= FormatEntry($dataspecref->{fax}, $data->{fascimiletelephonenumber}->[0] || "- unlisted -");
186     }
187     $outsub{searchresults} .= FormatEntry($dataspecref->{created}, $created);
188     $outsub{searchresults} .= FormatEntry($dataspecref->{modified}, $modified);
189     
190     $outsub{searchresults} .= "</table>";
191     
192     # If this is ourselves, present a link to do mods
193     if ($auth && ($id eq $data->{uid}->[0])) { #TODO: extract this string into a url for translation...
194       $outsub{searchresults} .= "<a href=\"$proto://$ENV{SERVER_NAME}/$config{webupdateurl}?id=$id&authtoken=$authtoken&editdn=".uri_escape($dn, "\x00-\x40\x7f-\xff")."\">Edit my settings</a>\n";
195     }
196     
197     $outsub{searchresults} .= "<br><br><br>\n";
198   }
199   
200   # Finally, we can write the output... yuck...
201   &Util::HTMLSendHeader;
202   foreach (@$lineref) {
203     if (/<\?ifauth(.+?)\?>/) {
204       $_ = ($auth ? $1 : "");
205     } elsif (/<\?ifnoauth(.+?)\?>/) {
206       $_ = ($auth ? "" : $1);
207     }
208     s/~(.+?)~/$outsub{$1}/g;
209     print;
210   }
211
212   $ldap->unbind;
213 }
214
215 sub ParseResult {
216   # Reads the output html file and find out how the output should be named
217   # -- this gives us a way to do translations more easily
218   # Returns the contents of the template (w/o the searchresult portion) and
219   # the output specification
220   my $fn = shift;
221   my $insec = 0;
222   my @lines;
223   my %hash;
224   
225   open (F, "<$fn") || &Util::HTMLError("$fn: $!");
226   while (<F>) {
227     if (!$insec) {
228       if (/<\?searchresults/i) {
229         $insec = 1;
230         push(@lines, "~searchresults~\n"); # Leave token so we know where to put the result
231       } else {
232         push(@lines, $_);
233       }
234     } else {
235       if (/searchresults\?>/i) {
236         $insec = 0;
237       } else {
238         if (!/^\s*#/) {
239           s/^ *\(//; 
240           s/\) *$//; # remove leading/trailing () and spaces
241           chomp;
242           my ($desc, $attr) = split(/, /, $_, 2);
243           $hash{$attr} = $desc;
244         }
245       }
246     }
247   }
248   close F;
249   return (\@lines, \%hash);
250 }
251
252 sub FormatEntry {
253   my ($key, $val) = @_;
254   
255   return "<tr><td align=right><b>$key:</b></td><td>&nbsp;$val</td></tr>\n";
256 }
257
258 exit 0;