source: branches/htmlform/cgi-bin/search.cgi@ 471

Last change on this file since 471 was 468, checked in by Kris Deugau, 14 years ago

/branches/htmlform

Merge trunk bugfixes and updates

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 17.9 KB
RevLine 
[197]1#!/usr/bin/perl
2# ipdb/cgi-bin/search.cgi
3# Started splitting search functions (quick and otherwise) from
4# main IPDB interface 03/11/2005
5###
6# SVN revision info
7# $Date: 2010-08-12 16:00:28 +0000 (Thu, 12 Aug 2010) $
8# SVN revision $Rev: 468 $
9# Last update by $Author: kdeugau $
10###
[417]11# Copyright 2005-2010 - Kris Deugau
[197]12
13use strict;
14use warnings;
15use CGI::Carp qw(fatalsToBrowser);
[447]16use CGI::Simple;
[449]17use HTML::Template;
[197]18use DBI;
19use CommonWeb qw(:ALL);
20use POSIX qw(ceil);
21use NetAddr::IP;
22
[417]23# don't remove! required for GNU/FHS-ish install from tarball
24##uselib##
[197]25
[417]26use MyIPDB;
27
[439]28# Don't formally need a username or syslog here. syslog left active for debugging.
29use Sys::Syslog;
30openlog "IPDBsearch","pid","$IPDB::syslog_facility";
31
32# ... but we do *use* the username on ACLs now.
33# Collect the username from HTTP auth. If undefined, we're in
34# a test environment, or called without a username.
35my $authuser;
36if (!defined($ENV{'REMOTE_USER'})) {
37 $authuser = '__temptest';
38} else {
39 $authuser = $ENV{'REMOTE_USER'};
40}
41
[197]42# Why not a global DB handle? (And a global statement handle, as well...)
43# Use the connectDB function, otherwise we end up confusing ourselves
44my $ip_dbh;
45my $sth;
46my $errstr;
47($ip_dbh,$errstr) = connectDB_My;
48if (!$ip_dbh) {
49 printAndExit("Failed to connect to database: $errstr\n");
50}
51checkDBSanity($ip_dbh);
52initIPDBGlobals($ip_dbh);
53
54# Global variables
[351]55my $RESULTS_PER_PAGE = 25;
[449]56##fixme - need to autofill this somehow
57$ENV{HTML_TEMPLATE_ROOT} = '/home/kdeugau/dev/ipdb/trunk/templates';
[197]58
[447]59# Set up the CGI object...
60my $q = new CGI::Simple;
61# ... and get query-string params as well as POST params if necessary
62$q->parse_query_string;
63
64# Convenience; saves changing all references to %webvar
65##fixme: tweak for handling <select multiple='y' size=3> (list with multiple selection)
66my %webvar = $q->Vars;
67
[370]68if (defined($webvar{rpp})) {
69 ($RESULTS_PER_PAGE) = ($webvar{rpp} =~ /(\d+)/);
70}
71
[197]72if (!defined($webvar{stype})) {
73 $webvar{stype} = "<NULL>"; #shuts up the warnings.
74}
75
[451]76my $header = HTML::Template->new(filename => "header.tmpl");
77$header->param(version => $IPDB::VERSION);
78$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
79print "Content-type: text/html\n\n", $header->output;
[197]80
81if ($webvar{stype} eq 'q') {
82 # Quick search.
83
84 if (!$webvar{input}) {
85 # No search term. Display everything.
86 viewBy('all', '');
87 } else {
88 # Search term entered. Display matches.
89 # We should really sanitize $webvar{input}, no?
90 my $searchfor;
91 # Chew up leading and trailing whitespace
92 $webvar{input} =~ s/^\s+//;
93 $webvar{input} =~ s/\s+$//;
[285]94 if ($webvar{input} =~ /^\d+$/) {
95 # All-digits, new custID
96 $searchfor = "cust";
97 } elsif ($webvar{input} =~ /^[\d\.]+(\/\d{1,3})?$/) {
[201]98 # IP addresses should only have numbers, digits, and maybe a slash+netmask
[197]99 $searchfor = "ipblock";
100 } else {
101 # Anything else.
102 $searchfor = "desc";
103 }
104 viewBy($searchfor, $webvar{input});
105 }
106
107} elsif ($webvar{stype} eq 'c') {
108 # Complex search.
109
[201]110 # Several major cases, and a whole raft of individual cases.
111 # -> Show all types means we do not need to limit records retrieved by type
112 # -> Show all cities means we do not need to limit records retrieved by city
113 # Individual cases are for the CIDR/IP, CustID, Description, Notes, and individual type
114 # requests.
115
[207]116 my $sqlconcat;
117 if ($webvar{which} eq 'all') {
118 # Must match *all* specified criteria. ## use INTERSECT or EXCEPT
119 $sqlconcat = "INTERSECT";
120 } elsif ($webvar{which} eq 'any') {
121 # Match on any specified criteria ## use UNION
122 $sqlconcat = "UNION";
123 } else {
124 # We can't get here. PTHBTT!
125 printAndExit "PTHBTT!! Your search has been rejected due to Microsoft excuse #4432: ".
126 "Not enough mana";
127 }
[197]128
[202]129# We actually construct a monster SQL statement for all criteria.
130# Iff something has been entered, it will be used as a filter.
[208]131# Iff something has NOT been entered, we still include it but in
132# such a way that it does not actually filter anything out.
[201]133
[207]134 # Columns actually returned. Slightly better than hardcoding it
135 # in each (sub)select
136 my $cols = "cidr,custid,type,city,description";
[201]137
[207]138 # First chunk of SQL. Filter on custid, description, and notes as necessary.
[351]139 my $sql = "(select $cols from searchme where".
140 " $webvar{custexclude} (custid ilike '%$webvar{custid}%'".
[201]141 " $sqlconcat (select $cols from searchme where $webvar{descexclude} description ilike '%$webvar{desc}%')".
142 " $sqlconcat (select $cols from searchme where $webvar{notesexclude} notes ilike '%$webvar{notes}%')";
143
[207]144 # If we're not supposed to search for all types, search for the selected types.
145 if ($webvar{alltypes} ne 'on') {
146 $sql .= " $sqlconcat (select $cols from searchme where $webvar{typeexclude} type in (";
147 foreach my $key (keys %webvar) {
148 $sql .= "'$1'," if $key =~ /type\[(..)\]/;
149 }
150 chop $sql;
151 $sql .= "))";
[201]152 }
153
[207]154 # If we're not supposed to search for all cities, search for the selected cities.
155 # This could be vastly improved with proper foreign keys in the database.
156 if ($webvar{allcities} ne 'on') {
157 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cityexclude} city in (";
158 $sth = $ip_dbh->prepare("select city from cities where id=?");
159 foreach my $key (keys %webvar) {
160 if ($key =~ /city\[(\d+)\]/) {
161 $sth->execute($1);
162 my $city;
163 $sth->bind_columns(\$city);
164 $sth->fetch;
165 $city =~ s/'/''/;
166 $sql .= "'$city',";
167 }
[201]168 }
[207]169 chop $sql;
170 $sql .= "))";
[201]171 }
172
[207]173 ## CIDR query options.
174 $webvar{cidr} =~ s/\s+//; # Hates the nasty spaceseseses we does.
[351]175 if ($webvar{cidr} eq '') { # We has a blank CIDR. Ignore it.
[285]176 } elsif ($webvar{cidr} =~ /\//) {
[427]177 # 192.168.179/26 should show all /26 subnets in 192.168.179
[207]178 my ($net,$maskbits) = split /\//, $webvar{cidr};
179 if ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
180 # /0->/9 are silly to worry about right now. I don't think
181 # we'll be getting a class A anytime soon. <g>
182 $sql .= " $sqlconcat (select $cols from searchme where ".
[351]183 "$webvar{cidrexclude} cidr<<='$webvar{cidr}')";
[207]184 } else {
185 # Partial match; beginning of subnet and maskbits are provided
186 # Show any blocks with the leading octet(s) and that masklength
[351]187 # Need some more magic for bare /nn searches:
188 my $condition = ($net eq '' ?
189 "masklen(cidr)=$maskbits" : "text(cidr) like '$net%' and masklen(cidr)=$maskbits");
[207]190 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
[351]191 "($condition))";
[207]192 }
193 } elsif ($webvar{cidr} =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
194 # Specific IP address match. Will show either a single netblock,
195 # or a static pool plus an IP.
196 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
197 "cidr >>= '$webvar{cidr}')";
198 } elsif ($webvar{cidr} =~ /^\d{1,3}(\.(\d{1,3}(\.(\d{1,3}\.?)?)?)?)?$/) {
199 # Leading octets in CIDR
200 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
201 "text(cidr) like '$webvar{cidr}%')";
202 } else {
203 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
204 printAndExit("Invalid netblock query.");
205 } # done with CIDR query options.
[201]206
[207]207 # Find the offset for multipage results
208 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
[201]209
[207]210 # Find out how many rows the "core" query will return.
211 my $count = countRows($sql);
[201]212
[207]213 if ($count == 0) {
214 printError "No matches found. Try eliminating one of the criteria,".
215 " or making one or more criteria more general.";
216 } else {
217 # Add the limit/offset clauses
[370]218 $sql .= " order by cidr";
219 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
[207]220 # And tell the user.
221 print "<div class=heading>Searching...............</div>\n";
222 queryResults($sql, $webvar{page}, $count);
223 }
[201]224
[397]225} elsif ($webvar{stype} eq 'n') {
226 # Node search.
227
228 my $sql = "SELECT cidr,custid,type,city,description FROM searchme".
229 " WHERE cidr IN (SELECT block FROM noderef WHERE node_id=$webvar{node})";
230
231 # Find the offset for multipage results
232 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
233
234 # Find out how many rows the "core" query will return.
235 my $count = countRows($sql);
236
237 if ($count == 0) {
238 printError "No customers currently listed as connected through this node.";
239 } else {
240 # Add the limit/offset clauses
241 $sql .= " order by cidr";
242 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
243 # And tell the user.
244 print "<div class=heading>Searching...............</div>\n";
245 queryResults($sql, $webvar{page}, $count);
246 }
247
[207]248} else { # how script was called. General case is to show the search criteria page.
[201]249
[197]250 # Display search page. We have to do this here, because otherwise
251 # we can't retrieve data from the database for the types and cities. >:(
252 my $html;
253 open HTML,"<../compsearch.html";
254 $html = join('',<HTML>);
255 close HTML;
256
257# Generate table of types
258 my $typetable = "<table class=regular cellspacing=0>\n<tr>";
259 $sth = $ip_dbh->prepare("select type,dispname from alloctypes where listorder <500 ".
260 "order by listorder");
261 $sth->execute;
262 my $i=0;
263 while (my @data = $sth->fetchrow_array) {
264 $typetable .= "<td><input type=checkbox name=type[$data[0]]>$data[1]</td>";
265 $i++;
266 $typetable .= "</tr>\n<tr>"
267 if ($i % 4 == 0);
268 }
269 if ($i %4 == 0) {
270 $typetable =~ s/<tr>$//;
271 } else {
272 $typetable .= "</tr>\n";
273 }
274 $typetable .= "</table>\n";
275
276# Generate table of cities
277 my $citytable = "<table class=regular cellspacing=0>\n<tr>";
278 $sth = $ip_dbh->prepare("select id,city from cities order by city");
279 $sth->execute;
280 my $i=0;
281 while (my @data = $sth->fetchrow_array) {
282 $citytable .= "<td><input type=checkbox name=city[$data[0]]>$data[1]</td>";
283 $i++;
284 $citytable .= "</tr>\n<tr>"
285 if ($i % 5 == 0);
286 }
287 if ($i %5 == 0) {
288 $citytable =~ s/<tr>$//;
289 } else {
290 $citytable .= "</tr>\n";
291 }
292 $citytable .= "</table>\n";
293
294 $html =~ s/\$\$TYPELIST\$\$/$typetable/;
295 $html =~ s/\$\$CITYLIST\$\$/$citytable/;
296
297 print $html;
298}
299
300# Shut down and clean up.
301finish($ip_dbh);
[449]302
303# We print the footer here, so we don't have to do it elsewhere.
304my $footer = HTML::Template->new(filename => "footer.tmpl");
305# include the admin tools link in the output?
306$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
307
308print $footer->output;
309
[197]310# We shouldn't need to directly execute any code below here; it's all subroutines.
311exit 0;
312
[207]313
314# viewBy()
315# The quick search
316# Takes a category descriptor and a query string
317# Creates appropriate SQL to run the search and display the results
318# with queryResults()
[197]319sub viewBy($$) {
320 my ($category,$query) = @_;
321
322 # Local variables
323 my $sql;
324
325 # Calculate start point for LIMIT clause
326 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
327
328# Possible cases:
[207]329# 1) Partial IP/subnet. Treated as "octet-prefix".
330# 2a) CIDR subnet. Exact match.
331# 2b) CIDR netmask. YMMV but it should be octet-prefix-with-netmask
332# (ie, all matches with the octet prefix *AND* that netmask)
333# 3) Customer ID. "Match-any-segment"
334# 4) Description. "Match-any-segment"
[197]335# 5) Invalid data which might be interpretable as an IP or something, but
336# which probably shouldn't be for reasons of sanity.
337
[371]338 my $cols = "cidr,custid,type,city,description";
339
[197]340 if ($category eq 'all') {
341
342 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
[371]343 $sql = "select $cols from searchme";
[202]344 my $count = countRows($sql);
[197]345 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
346 queryResults($sql, $webvar{page}, $count);
347
348 } elsif ($category eq 'cust') {
349
350 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
351
352 # Query for a customer ID. Note that we can't restrict to "numeric-only"
353 # as we have non-numeric custIDs in the legacy data. :/
[468]354 $sql = "select $cols from searchme where custid ilike '%$query%' or description like '%$query%'";
[202]355 my $count = countRows($sql);
[197]356 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
357 queryResults($sql, $webvar{page}, $count);
358
359 } elsif ($category eq 'desc') {
360
361 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
362 # Query based on description (includes "name" from old DB).
[371]363 $sql = "select $cols from searchme where description ilike '%$query%'".
[285]364 " or custid ilike '%$query%'";
[202]365 my $count = countRows($sql);
[197]366 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
367 queryResults($sql, $webvar{page}, $count);
368
369 } elsif ($category =~ /ipblock/) {
370
371 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
372 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
373
374 $query =~ s/\s+//g;
375 if ($query =~ /\//) {
[427]376 # 192.168.179/26 should show all /26 subnets in 192.168.179
[197]377 my ($net,$maskbits) = split /\//, $query;
378 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
379 # /0->/9 are silly to worry about right now. I don't think
380 # we'll be getting a class A anytime soon. <g>
[371]381 $sql = "select $cols from searchme where cidr='$query'";
[197]382 queryResults($sql, $webvar{page}, 1);
383 } else {
[289]384 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
[197]385 # Partial match; beginning of subnet and maskbits are provided
[371]386 $sql = "select $cols from searchme where text(cidr) like '$net%' and ".
[197]387 "text(cidr) like '%$maskbits'";
[202]388 my $count = countRows($sql);
[197]389 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
390 queryResults($sql, $webvar{page}, $count);
391 }
392 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
393 # Specific IP address match
[289]394 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
[197]395 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
396 my $sfor = new NetAddr::IP $query;
[371]397 $sth = $ip_dbh->prepare("select $cols from searchme where text(cidr) like '$net%'");
[197]398 $sth->execute;
399 while (my @data = $sth->fetchrow_array()) {
400 my $cidr = new NetAddr::IP $data[0];
401 if ($cidr->contains($sfor)) {
[371]402 queryResults("select $cols from searchme where cidr='$cidr'", $webvar{page}, 1);
[197]403 }
404 }
[202]405 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
[289]406 #print "Finding matches with leading octet(s) $query<br>\n";
[371]407 $sql = "select $cols from searchme where text(cidr) like '$query%'";
[202]408 my $count = countRows($sql);
[197]409 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
410 queryResults($sql, $webvar{page}, $count);
411 } else {
412 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
413 printError("Invalid query.");
414 }
415 } else {
416 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
417 printError("Invalid searchfor.");
418 }
419} # viewBy
420
421
422# args are: a reference to an array with the row to be printed and the
423# class(stylesheet) to use for formatting.
424# if ommitting the class - call the sub as &printRow(\@array)
425sub printRow {
426 my ($rowRef,$class) = @_;
427
428 if (!$class) {
429 print "<tr>\n";
430 } else {
431 print "<tr class=\"$class\">\n";
432 }
433
434ELEMENT: foreach my $element (@$rowRef) {
435 if (!defined($element)) {
436 print "<td></td>\n";
437 next ELEMENT;
438 }
439 $element =~ s|\n|</br>|g;
440 print "<td>$element</td>\n";
441 }
442 print "</tr>";
443} # printRow
444
445
[207]446# queryResults()
447# Display search queries based on the passed SQL.
448# Takes SQL, page number (for multipage search results), and a total count.
[197]449sub queryResults($$$) {
450 my ($sql, $pageNo, $rowCount) = @_;
451 my $offset = 0;
452 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
453
454 my $sth = $ip_dbh->prepare($sql);
455 $sth->execute();
456
457 startTable('Allocation','CustID','Type','City','Description/Name');
458 my $count = 0;
459
460 while (my @data = $sth->fetchrow_array) {
[202]461
[197]462 # cidr,custid,type,city,description,notes
[202]463 # Another bit of HairyPerl(TM) to prefix subblocks with "Sub"
464 my @row = (($data[2] =~ /^.r$/ ? 'Sub ' : '').
465 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
[197]466 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
467 # Allow listing of pool if desired/required.
468 if ($data[2] =~ /^.[pd]$/) {
469 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
470 "&pool=$data[0]\">List IPs</a>";
471 }
472 printRow(\@row, 'color1', 1) if ($count%2==0);
473 printRow(\@row, 'color2', 1) if ($count%2!=0);
474 $count++;
475 }
476
477 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
478 # In this context it's probably a good idea.
479 $sth->finish();
480
481 my $upper = $offset+$count;
[202]482 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: ".($offset+1)." - $upper</i></td></tr>\n";
[197]483 print "</table></center>\n";
484
485 # print the page thing..
[370]486 if ($RESULTS_PER_PAGE > 0 && $rowCount > $RESULTS_PER_PAGE) {
[197]487 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
488 print qq(<div class="center"> Page: );
489 for (my $i = 1; $i <= $pages; $i++) {
490 if ($i == $pageNo) {
491 print "<b>$i&nbsp;</b>\n";
492 } else {
[202]493 print qq(<a href="/ip/cgi-bin/search.cgi?page=$i&stype=$webvar{stype}&);
494 if ($webvar{stype} eq 'c') {
495 print "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
496 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
497 "allcities=$webvar{allcities}&";
498 foreach my $key (keys %webvar) {
[351]499 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
[202]500 print "$key=$webvar{$key}&";
501 }
502 }
503 } else {
504 print "input=$webvar{input}&";
505 }
506 print qq(">$i</a>&nbsp;\n);
[197]507 }
508 }
509 print "</div>";
510 }
511} # queryResults
512
513
514# Prints table headings. Accepts any number of arguments;
515# each argument is a table heading.
516sub startTable {
517 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
518
519 foreach(@_) {
520 print qq(<td class="heading">$_</td>);
521 }
522 print "</tr>\n";
523} # startTable
524
525
[202]526# Return count of rows to be returned in a "real" query
527# with the passed SQL statement
[197]528sub countRows($) {
[202]529 # Note that the "as foo" is required
530 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
[197]531 $sth->execute();
532 my @a = $sth->fetchrow_array();
533 $sth->finish();
534 return $a[0];
535}
Note: See TracBrowser for help on using the repository browser.