source: branches/new-search-20050223/cgi-bin/search.cgi@ 207

Last change on this file since 207 was 207, checked in by Kris Deugau, 20 years ago

/branches/new-search-20050223

All search criteria complete.

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