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

Last change on this file since 234 was 234, checked in by Kris Deugau, 19 years ago

/trunk

Merge new search capability from /branches/new-search-20050223

r171-197 to trunk.

Changes to header.inc conflicted (minor, patched, expected)
Removals from main.cgi conflicted (not sure why)
search.cgi updated with ACL bits (for header)
Proper permissions set on search.cgi - really!

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