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

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

/branches/new-search-20050223

SQL for all except IP/netblock-based search filtering is complete.
Exclusion options are complete, although they will not behave
entirely predictably if "match any" is used.

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