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

Last change on this file since 801 was 801, checked in by Kris Deugau, 9 years ago

/trunk

Extend template-replacement from r793 to search.cgi and admin.cgi

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