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