Added support for the Jabber ID
[mirror/userdir-ldap-cgi.git] / search.cgi
1 #!/usr/bin/perl
2
3 # $Id: search.cgi,v 1.11 2004/11/18 19:17:00 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, $jabberjid, $email, $fingerprint,
121         $address, $latlong, $vacation, $created, $modified, $lastseen) = undef;
122     
123     $ufdn = $dn; # Net::LDAP does not have a dn2ufn function, but this is close enough :)
124     
125     # Assemble name, attach web page link if present.
126     $name = $data->{cn}->[0]." ".$data->{mn}->[0]." ".$data->{sn}->[0];
127     if (my $url = $data->{labeleduri}->[0]) {
128       $name = "<a href=\"$url\">$name</a>";
129     }
130     
131     # Add links to all email addresses
132     foreach (@{$data->{emailforward}}) {
133       $email .= "<br>" if ($email);
134       $email .= "<a href=\"mailto:$_\">$_</a>";
135     }
136
137     # ICQ 
138     if ($data->{icquin}->[0]) {
139       $icquin = sprintf("<a href=\"http://wwp.icq.com/%s\">%s</a>", $data->{icquin}->[0], $data->{icquin}->[0]);
140     }
141     
142     # Format PGP/GPG key fingerprints
143     my $fi;
144     foreach (@{$data->{keyfingerprint}}) {
145       $fingerprint .= "<br>" if ($fingerprint);
146       $fingerprint .= sprintf("%d:- <a href=\"fetchkey.cgi?fingerprint=%s\">%s</a>", ++$fi, $_, &Util::FormatFingerPrint($_));
147     }
148     
149     # Assemble addresses
150     $address = $data->{postaladdress}->[0] || "- unlisted -";
151     $address =~ s/\$/<br>/g;
152     $address .= "<br>".$data->{l}->[0]."<br>".&Util::LookupCountry($data->{c}->[0])."<br>".$data->{postalcode}->[0];
153
154     # Assemble latitude/longitude
155     $latlong  = $data->{latitude}->[0] || "none";
156     $latlong .= " / ";
157     $latlong .= $data->{longitude}->[0] || "none";    
158
159     # Modified/created time. TODO: maybe add is the name of the creator/modifier
160     $modified = &Util::FormatTimestamp($data->{modifytimestamp}->[0]);
161     $created =  &Util::FormatTimestamp($data->{createtimestamp}->[0]);
162
163     # Last seen information (Echelon)
164     $lastseen = &Util::FormatLastSeen($data->{"activity-pgp"}->[0],
165                                       $data->{"activity-from"}->[0]);
166
167     # Link in the debian login id 
168     $login = $data->{uid}->[0]."\@debian.org";
169     $login = "<a href=\"mailto:$login\">$login</a>";
170     
171     # See if the user has a vacation message, non-public
172     $vacation = $data->{onvacation}->[0] if ($authtoken && $id);
173
174     # OK, now generate output... (i.e. put the output into the buffer )
175     $outsub{searchresults} .= '<table border=2 cellpadding=2 cellspacing=0 bgcolor="#DDDDDD" width="80%">';
176     $outsub{searchresults} .= '<tr><th bgcolor="#44CCCC" colspan=2><font size=+1>'."$name</font> ";
177     $outsub{searchresults} .= "($ufdn)</th></tr>\n";
178     
179     if ($vacation) {
180       $outsub{searchresults} .= "<tr><td colspan=2 align=center><b>$vacation</b></td></tr>\n";
181     }
182
183     $outsub{searchresults} .= FormatEntry($dataspecref->{uid}, $login);
184     $outsub{searchresults} .= FormatEntry($dataspecref->{ircnick}, $data->{ircnick}->[0]);
185     $outsub{searchresults} .= FormatEntry($dataspecref->{jabberjid}, $data->{jabberjid}->[0]);
186     $outsub{searchresults} .= FormatEntry($dataspecref->{loginshell}, $data->{loginshell}->[0]);
187     $outsub{searchresults} .= FormatEntry($dataspecref->{fingerprint}, $fingerprint);
188     if ($icquin) {
189       $outsub{searchresults} .= FormatEntry($dataspecref->{icquin}, $icquin);
190     }
191     
192     if ($auth) {
193       # Some data should only be available to authorized users...
194       if ($id eq $data->{uid}->[0]) {
195         $outsub{searchresults} .= FormatEntry($dataspecref->{email}, $email);
196       }
197       $outsub{searchresults} .= FormatEntry($dataspecref->{address}, $address);
198       $outsub{searchresults} .= FormatEntry($dataspecref->{latlong}, $latlong);
199       $outsub{searchresults} .= FormatEntry($dataspecref->{phone}, $data->{telephonenumber}->[0] || "- unlisted -");
200       $outsub{searchresults} .= FormatEntry($dataspecref->{fax}, $data->{fascimiletelephonenumber}->[0] || "- unlisted -");
201       $outsub{searchresults} .= FormatEntry($dataspecref->{lastseen}, $lastseen);
202     }
203     $outsub{searchresults} .= FormatEntry($dataspecref->{created}, $created);
204     $outsub{searchresults} .= FormatEntry($dataspecref->{modified}, $modified);
205     
206     $outsub{searchresults} .= "</table>";
207     
208     # If this is ourselves, present a link to do mods
209     if ($auth && ($id eq $data->{uid}->[0])) { #TODO: extract this string into a url for translation...
210       $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";
211     }
212     
213     $outsub{searchresults} .= "<br><br><br>\n";
214   }
215   
216   # Finally, we can write the output... yuck...
217   &Util::HTMLSendHeader;
218   foreach (@$lineref) {
219     if (/<\?ifauth(.+?)\?>/) {
220       $_ = ($auth ? $1 : "");
221     } elsif (/<\?ifnoauth(.+?)\?>/) {
222       $_ = ($auth ? "" : $1);
223     }
224     s/~(.+?)~/$outsub{$1}/g;
225     print;
226   }
227
228   $ldap->unbind;
229 }
230
231 sub ParseResult {
232   # Reads the output html file and find out how the output should be named
233   # -- this gives us a way to do translations more easily
234   # Returns the contents of the template (w/o the searchresult portion) and
235   # the output specification
236   my $fn = shift;
237   my $insec = 0;
238   my @lines;
239   my %hash;
240   
241   open (F, "<$fn") || &Util::HTMLError("$fn: $!");
242   while (<F>) {
243     if (!$insec) {
244       if (/<\?searchresults/i) {
245         $insec = 1;
246         push(@lines, "~searchresults~\n"); # Leave token so we know where to put the result
247       } else {
248         push(@lines, $_);
249       }
250     } else {
251       if (/searchresults\?>/i) {
252         $insec = 0;
253       } else {
254         if (!/^\s*#/) {
255           s/^ *\(//; 
256           s/\) *$//; # remove leading/trailing () and spaces
257           chomp;
258           my ($desc, $attr) = split(/, /, $_, 2);
259           $hash{$attr} = $desc;
260         }
261       }
262     }
263   }
264   close F;
265   return (\@lines, \%hash);
266 }
267
268 sub FormatEntry {
269   my ($key, $val) = @_;
270   
271   return "<tr><td align=right><b>$key:</b></td><td>&nbsp;$val</td></tr>\n";
272 }
273
274 exit 0;