source: trunk/cgi-bin/search.cgi@ 370

Last change on this file since 370 was 370, checked in by Kris Deugau, 17 years ago

/trunk

Merge bugfixes and enhancements from /branches/stable r351 through r359

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