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

Last change on this file since 392 was 389, checked in by Kris Deugau, 15 years ago

/branches/stable

Commit lurking fix/extension to search descriptions for CustIDs

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 16.1 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: 2010-02-18 20:03:12 +0000 (Thu, 18 Feb 2010) $
8# SVN revision $Rev: 389 $
9# Last update by $Author: kdeugau $
10###
11# Copyright 2005,2006 Kris Deugau
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{rpp})) {
44 ($RESULTS_PER_PAGE) = ($webvar{rpp} =~ /(\d+)/);
45}
46
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+$//;
66 if ($webvar{input} =~ /^\d+$/) {
67 # All-digits, new custID
68 $searchfor = "cust";
69 } elsif ($webvar{input} =~ /^[\d\.]+(\/\d{1,3})?$/) {
70 # IP addresses should only have numbers, digits, and maybe a slash+netmask
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
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
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 }
100
101# We actually construct a monster SQL statement for all criteria.
102# Iff something has been entered, it will be used as a filter.
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.
105
106 # Columns actually returned. Slightly better than hardcoding it
107 # in each (sub)select
108 my $cols = "cidr,custid,type,city,description";
109
110 # First chunk of SQL. Filter on custid, description, and notes as necessary.
111 my $sql = "(select $cols from searchme where".
112 " $webvar{custexclude} (custid ilike '%$webvar{custid}%'".
113 " OR $webvar{custexclude} oldcustid ilike '%$webvar{custid}%'))".
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
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 .= "))";
125 }
126
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 }
141 }
142 chop $sql;
143 $sql .= "))";
144 }
145
146 ## CIDR query options.
147 $webvar{cidr} =~ s/\s+//; # Hates the nasty spaceseseses we does.
148 if ($webvar{cidr} eq '') { # We has a blank CIDR. Ignore it.
149 } elsif ($webvar{cidr} =~ /\//) {
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 ".
156 "$webvar{cidrexclude} cidr<<='$webvar{cidr}')";
157 } else {
158 # Partial match; beginning of subnet and maskbits are provided
159 # Show any blocks with the leading octet(s) and that masklength
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");
163 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
164 "($condition))";
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.
179
180 # Find the offset for multipage results
181 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
182
183 # Find out how many rows the "core" query will return.
184 my $count = countRows($sql);
185
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
191 $sql .= " order by cidr";
192 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
193 # And tell the user.
194 print "<div class=heading>Searching...............</div>\n";
195 queryResults($sql, $webvar{page}, $count);
196 }
197
198} else { # how script was called. General case is to show the search criteria page.
199
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
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()
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:
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"
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 my $cols = "cidr,custid,type,city,description";
282
283 if ($category eq 'all') {
284
285 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
286 $sql = "select $cols from searchme";
287 my $count = countRows($sql);
288 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
289 queryResults($sql, $webvar{page}, $count);
290
291 } elsif ($category eq 'cust') {
292
293 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
294
295 # Query for a customer ID. Note that we can't restrict to "numeric-only"
296 # as we have non-numeric custIDs in the legacy data. :/
297 $sql = "select $cols from searchme where custid ilike '%$query%' or oldcustid ilike '%$query%' or description like '%$query%'";
298 my $count = countRows($sql);
299 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
300 queryResults($sql, $webvar{page}, $count);
301
302 } elsif ($category eq 'desc') {
303
304 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
305 # Query based on description (includes "name" from old DB).
306 $sql = "select $cols from searchme where description ilike '%$query%'".
307 " or custid ilike '%$query%'";
308 my $count = countRows($sql);
309 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
310 queryResults($sql, $webvar{page}, $count);
311
312 } elsif ($category =~ /ipblock/) {
313
314 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
315 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
316
317 $query =~ s/\s+//g;
318 if ($query =~ /\//) {
319 # 209.91.179/26 should show all /26 subnets in 209.91.179
320 my ($net,$maskbits) = split /\//, $query;
321 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
322 # /0->/9 are silly to worry about right now. I don't think
323 # we'll be getting a class A anytime soon. <g>
324 $sql = "select $cols from searchme where cidr='$query'";
325 queryResults($sql, $webvar{page}, 1);
326 } else {
327 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
328 # Partial match; beginning of subnet and maskbits are provided
329 $sql = "select $cols from searchme where text(cidr) like '$net%' and ".
330 "text(cidr) like '%$maskbits'";
331 my $count = countRows($sql);
332 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
333 queryResults($sql, $webvar{page}, $count);
334 }
335 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
336 # Specific IP address match
337 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
338 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
339 my $sfor = new NetAddr::IP $query;
340 $sth = $ip_dbh->prepare("select $cols from searchme where text(cidr) like '$net%'");
341 $sth->execute;
342 while (my @data = $sth->fetchrow_array()) {
343 my $cidr = new NetAddr::IP $data[0];
344 if ($cidr->contains($sfor)) {
345 queryResults("select $cols from searchme where cidr='$cidr'", $webvar{page}, 1);
346 }
347 }
348 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
349 #print "Finding matches with leading octet(s) $query<br>\n";
350 $sql = "select $cols from searchme where text(cidr) like '$query%'";
351 my $count = countRows($sql);
352 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
353 queryResults($sql, $webvar{page}, $count);
354 } else {
355 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
356 printError("Invalid query.");
357 }
358 } else {
359 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
360 printError("Invalid searchfor.");
361 }
362} # viewBy
363
364
365# args are: a reference to an array with the row to be printed and the
366# class(stylesheet) to use for formatting.
367# if ommitting the class - call the sub as &printRow(\@array)
368sub printRow {
369 my ($rowRef,$class) = @_;
370
371 if (!$class) {
372 print "<tr>\n";
373 } else {
374 print "<tr class=\"$class\">\n";
375 }
376
377ELEMENT: foreach my $element (@$rowRef) {
378 if (!defined($element)) {
379 print "<td></td>\n";
380 next ELEMENT;
381 }
382 $element =~ s|\n|</br>|g;
383 print "<td>$element</td>\n";
384 }
385 print "</tr>";
386} # printRow
387
388
389# queryResults()
390# Display search queries based on the passed SQL.
391# Takes SQL, page number (for multipage search results), and a total count.
392sub queryResults($$$) {
393 my ($sql, $pageNo, $rowCount) = @_;
394 my $offset = 0;
395 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
396
397 my $sth = $ip_dbh->prepare($sql);
398 $sth->execute();
399
400 startTable('Allocation','CustID','Type','City','Description/Name');
401 my $count = 0;
402
403 while (my @data = $sth->fetchrow_array) {
404
405 # cidr,custid,type,city,description,notes
406 # Another bit of HairyPerl(TM) to prefix subblocks with "Sub"
407 my @row = (($data[2] =~ /^.r$/ ? 'Sub ' : '').
408 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
409 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
410 # Allow listing of pool if desired/required.
411 if ($data[2] =~ /^.[pd]$/) {
412 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
413 "&pool=$data[0]\">List IPs</a>";
414 }
415 printRow(\@row, 'color1', 1) if ($count%2==0);
416 printRow(\@row, 'color2', 1) if ($count%2!=0);
417 $count++;
418 }
419
420 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
421 # In this context it's probably a good idea.
422 $sth->finish();
423
424 my $upper = $offset+$count;
425 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: ".($offset+1)." - $upper</i></td></tr>\n";
426 print "</table></center>\n";
427
428 # print the page thing..
429 if ($RESULTS_PER_PAGE > 0 && $rowCount > $RESULTS_PER_PAGE) {
430 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
431 print qq(<div class="center"> Page: );
432 for (my $i = 1; $i <= $pages; $i++) {
433 if ($i == $pageNo) {
434 print "<b>$i&nbsp;</b>\n";
435 } else {
436 print qq(<a href="/ip/cgi-bin/search.cgi?page=$i&stype=$webvar{stype}&);
437 if ($webvar{stype} eq 'c') {
438 print "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
439 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
440 "allcities=$webvar{allcities}&";
441 foreach my $key (keys %webvar) {
442 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
443 print "$key=$webvar{$key}&";
444 }
445 }
446 } else {
447 print "input=$webvar{input}&";
448 }
449 print qq(">$i</a>&nbsp;\n);
450 }
451 }
452 print "</div>";
453 }
454} # queryResults
455
456
457# Prints table headings. Accepts any number of arguments;
458# each argument is a table heading.
459sub startTable {
460 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
461
462 foreach(@_) {
463 print qq(<td class="heading">$_</td>);
464 }
465 print "</tr>\n";
466} # startTable
467
468
469# Return count of rows to be returned in a "real" query
470# with the passed SQL statement
471sub countRows($) {
472 # Note that the "as foo" is required
473 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
474 $sth->execute();
475 my @a = $sth->fetchrow_array();
476 $sth->finish();
477 return $a[0];
478}
Note: See TracBrowser for help on using the repository browser.