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

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

/branches/new-search-20050223

Checkpoint commit:

  • Search functionality copied to separate file/module
  • Initial layout for complex search added in new HTML fragment
  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 11.3 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-15 18:48:12 +0000 (Tue, 15 Mar 2005) $
8# SVN revision $Rev: 197 $
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 = 50;
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 # need to munge up data for $webvar{searchfor}, rather than breaking things here.
60 my $searchfor;
61 # Chew up leading and trailing whitespace
62 $webvar{input} =~ s/^\s+//;
63 $webvar{input} =~ s/\s+$//;
64 if ($webvar{input} =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{1,3}$/) {
65 # "Perfect" IP subnet match
66 $searchfor = "ipblock";
67 } elsif ($webvar{input} =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
68 # "Perfect" IP address match (shows containing block)
69 $searchfor = "ipblock";
70 } elsif ($webvar{input} =~ /^(\d{1,3}\.){2}\d{1,3}(\.\d{1,3}?)?/) {
71 # Partial IP match
72 $searchfor = "ipblock";
73 } elsif ($webvar{input} =~ /^\d+$/) {
74 # All-digits, new custID
75 $searchfor = "cust";
76 } else {
77 # Anything else.
78 $searchfor = "desc";
79 }
80 viewBy($searchfor, $webvar{input});
81 }
82
83} elsif ($webvar{stype} eq 'c') {
84 # Complex search.
85 print "Complex Search...............\n";
86
87print "<pre>\n";
88foreach my $key (keys %webvar) {
89 print "key: $key value: $webvar{$key}\n";
90}
91print "</pre>\n";
92
93} else {
94 # Display search page. We have to do this here, because otherwise
95 # we can't retrieve data from the database for the types and cities. >:(
96 my $html;
97 open HTML,"<../compsearch.html";
98 $html = join('',<HTML>);
99 close HTML;
100
101# Generate table of types
102 my $typetable = "<table class=regular cellspacing=0>\n<tr>";
103 $sth = $ip_dbh->prepare("select type,dispname from alloctypes where listorder <500 ".
104 "order by listorder");
105 $sth->execute;
106 my $i=0;
107 while (my @data = $sth->fetchrow_array) {
108 $typetable .= "<td><input type=checkbox name=type[$data[0]]>$data[1]</td>";
109 $i++;
110 $typetable .= "</tr>\n<tr>"
111 if ($i % 4 == 0);
112 }
113 if ($i %4 == 0) {
114 $typetable =~ s/<tr>$//;
115 } else {
116 $typetable .= "</tr>\n";
117 }
118 $typetable .= "</table>\n";
119
120# Generate table of cities
121 my $citytable = "<table class=regular cellspacing=0>\n<tr>";
122 $sth = $ip_dbh->prepare("select id,city from cities order by city");
123 $sth->execute;
124 my $i=0;
125 while (my @data = $sth->fetchrow_array) {
126 $citytable .= "<td><input type=checkbox name=city[$data[0]]>$data[1]</td>";
127 $i++;
128 $citytable .= "</tr>\n<tr>"
129 if ($i % 5 == 0);
130 }
131 if ($i %5 == 0) {
132 $citytable =~ s/<tr>$//;
133 } else {
134 $citytable .= "</tr>\n";
135 }
136 $citytable .= "</table>\n";
137
138
139 $html =~ s/\$\$TYPELIST\$\$/$typetable/;
140 $html =~ s/\$\$CITYLIST\$\$/$citytable/;
141
142 print $html;
143}
144
145# # This is unpossible!
146# print "This is UnPossible! You can't get here!\n";
147
148# Shut down and clean up.
149finish($ip_dbh);
150printFooter;
151# We shouldn't need to directly execute any code below here; it's all subroutines.
152exit 0;
153
154sub viewBy($$) {
155 my ($category,$query) = @_;
156
157 # Local variables
158 my $sql;
159
160#print "<pre>\n";
161
162#print "start querysub: query '$query'\n";
163# this may happen with more than one subcategory. Unlikely, but possible.
164
165 # Calculate start point for LIMIT clause
166 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
167
168# Possible cases:
169# 1) Partial IP/subnet. Treated as "first-three-octets-match" in old IPDB,
170# I should be able to handle it similarly here.
171# 2a) CIDR subnet. Treated more or less as such in old IPDB.
172# 2b) CIDR netmask. Not sure how it's treated.
173# 3) Customer ID. Not handled in old IPDB
174# 4) Description.
175# 5) Invalid data which might be interpretable as an IP or something, but
176# which probably shouldn't be for reasons of sanity.
177
178 if ($category eq 'all') {
179
180 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
181 $sql = "select * from searchme";
182 my $count = countRows("select count(*) from ($sql) foo");
183 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
184 queryResults($sql, $webvar{page}, $count);
185
186 } elsif ($category eq 'cust') {
187
188 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
189
190 # Query for a customer ID. Note that we can't restrict to "numeric-only"
191 # as we have non-numeric custIDs in the legacy data. :/
192 $sql = "select * from searchme where custid ilike '%$query%'";
193 my $count = countRows("select count(*) from ($sql) foo");
194 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
195 queryResults($sql, $webvar{page}, $count);
196
197 } elsif ($category eq 'desc') {
198
199 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
200 # Query based on description (includes "name" from old DB).
201 $sql = "select * from searchme where description ilike '%$query%'";
202 my $count = countRows("select count(*) from ($sql) foo");
203 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
204 queryResults($sql, $webvar{page}, $count);
205
206 } elsif ($category =~ /ipblock/) {
207
208 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
209 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
210
211 $query =~ s/\s+//g;
212 if ($query =~ /\//) {
213 # 209.91.179/26 should show all /26 subnets in 209.91.179
214 my ($net,$maskbits) = split /\//, $query;
215 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
216 # /0->/9 are silly to worry about right now. I don't think
217 # we'll be getting a class A anytime soon. <g>
218 $sql = "select * from searchme where cidr='$query'";
219 queryResults($sql, $webvar{page}, 1);
220 } else {
221 print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
222 # Partial match; beginning of subnet and maskbits are provided
223 $sql = "select * from searchme where text(cidr) like '$net%' and ".
224 "text(cidr) like '%$maskbits'";
225 my $count = countRows("select count(*) from ($sql) foo");
226 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
227 queryResults($sql, $webvar{page}, $count);
228 }
229 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
230 # Specific IP address match
231 print "4-octet pattern found; finding netblock containing IP $query<br>\n";
232 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
233 my $sfor = new NetAddr::IP $query;
234 $sth = $ip_dbh->prepare("select * from searchme where text(cidr) like '$net%'");
235 $sth->execute;
236 while (my @data = $sth->fetchrow_array()) {
237 my $cidr = new NetAddr::IP $data[0];
238 if ($cidr->contains($sfor)) {
239 queryResults("select * from searchme where cidr='$cidr'", $webvar{page}, 1);
240 }
241 }
242 } elsif ($query =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.?$/) {
243 print "Finding matches where the first three octets are $query<br>\n";
244 $sql = "select * from searchme where text(cidr) like '$query%'";
245 my $count = countRows("select count(*) from ($sql) foo");
246 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
247 queryResults($sql, $webvar{page}, $count);
248 } else {
249 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
250 printError("Invalid query.");
251 }
252 } else {
253 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
254 printError("Invalid searchfor.");
255 }
256} # viewBy
257
258
259# args are: a reference to an array with the row to be printed and the
260# class(stylesheet) to use for formatting.
261# if ommitting the class - call the sub as &printRow(\@array)
262sub printRow {
263 my ($rowRef,$class) = @_;
264
265 if (!$class) {
266 print "<tr>\n";
267 } else {
268 print "<tr class=\"$class\">\n";
269 }
270
271ELEMENT: foreach my $element (@$rowRef) {
272 if (!defined($element)) {
273 print "<td></td>\n";
274 next ELEMENT;
275 }
276 $element =~ s|\n|</br>|g;
277 print "<td>$element</td>\n";
278 }
279 print "</tr>";
280} # printRow
281
282
283# Display certain types of search query. Note that this can't be
284# cleanly reused much of anywhere else as the data isn't neatly tabulated.
285# This is tied to the search sub tightly enough I may just gut it and provide
286# more appropriate tables directly as needed.
287sub queryResults($$$) {
288 my ($sql, $pageNo, $rowCount) = @_;
289 my $offset = 0;
290 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
291
292 my $sth = $ip_dbh->prepare($sql);
293 $sth->execute();
294
295 startTable('Allocation','CustID','Type','City','Description/Name');
296 my $count = 0;
297
298 while (my @data = $sth->fetchrow_array) {
299 # cidr,custid,type,city,description,notes
300 # Fix up types from pools (which are single-char)
301 # Fixing the database would be... painful. :(
302##fixme LEGACY CODE
303 if ($data[2] =~ /^[cdsmw]$/) {
304 $data[2] .= 'i';
305 }
306 my @row = (qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
307 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
308 # Allow listing of pool if desired/required.
309 if ($data[2] =~ /^.[pd]$/) {
310 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
311 "&pool=$data[0]\">List IPs</a>";
312 }
313 printRow(\@row, 'color1', 1) if ($count%2==0);
314 printRow(\@row, 'color2', 1) if ($count%2!=0);
315 $count++;
316 }
317
318 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
319 # In this context it's probably a good idea.
320 $sth->finish();
321
322 my $upper = $offset+$count;
323 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: $offset - $upper</i></td></tr>\n";
324 print "</table></center>\n";
325
326 # print the page thing..
327 if ($rowCount > $RESULTS_PER_PAGE) {
328 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
329 print qq(<div class="center"> Page: );
330 for (my $i = 1; $i <= $pages; $i++) {
331 if ($i == $pageNo) {
332 print "<b>$i&nbsp;</b>\n";
333 } else {
334 print qq(<a href="/ip/cgi-bin/main.cgi?page=$i&input=$webvar{input}&action=search&searchfor=$webvar{searchfor}">$i</a>&nbsp;\n);
335 }
336 }
337 print "</div>";
338 }
339} # queryResults
340
341
342# Prints table headings. Accepts any number of arguments;
343# each argument is a table heading.
344sub startTable {
345 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
346
347 foreach(@_) {
348 print qq(<td class="heading">$_</td>);
349 }
350 print "</tr>\n";
351} # startTable
352
353
354# Return first element of passed SQL query
355sub countRows($) {
356 my $sth = $ip_dbh->prepare($_[0]);
357 $sth->execute();
358 my @a = $sth->fetchrow_array();
359 $sth->finish();
360 return $a[0];
361}
362
Note: See TracBrowser for help on using the repository browser.