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