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