source: branches/stable/cgi-bin/search.cgi@ 318

Last change on this file since 318 was 318, checked in by Kris Deugau, 18 years ago

/branches/stable

Extra code changes required for new billing system rollout. Note that references
to oldcustid can be removed later; this field is NOT required long-term.

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