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