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

Last change on this file since 716 was 670, checked in by Kris Deugau, 10 years ago

/trunk

Minimally update search tool for new database layout. Still needs a major rewrite.

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