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