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

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

/branches/htmlform

Switch all scripts to use CGI::Simple for HTML form data munging
instead of legacy CommonWeb.pm sub. Remove parse_post() sub from
CommonWeb.pm. See #15.

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