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

Last change on this file since 770 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
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: 2015-01-02 22:26:32 +0000 (Fri, 02 Jan 2015) $
8# SVN revision $Rev: 670 $
9# Last update by $Author: kdeugau $
10###
11# Copyright 2005-2010 - Kris Deugau
12
13use strict;
14use warnings;
15use CGI::Carp qw(fatalsToBrowser);
16use CGI::Simple;
17use HTML::Template;
18use DBI;
19use POSIX qw(ceil);
20use NetAddr::IP;
21
22# don't remove! required for GNU/FHS-ish install from tarball
23##uselib##
24
25use MyIPDB;
26
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
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
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;
67if ($ip_dbh) {
68 checkDBSanity($ip_dbh);
69 initIPDBGlobals($ip_dbh);
70}
71
72# Set up some globals
73$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";
74
75my $page;
76if (!defined($webvar{stype})) {
77 $webvar{stype} = "<NULL>"; #shuts up the warnings.
78 $page = HTML::Template->new(filename => "search/compsearch.tmpl");
79} else {
80 $page = HTML::Template->new(filename => "search/sresults.tmpl", global_vars => 1);
81 $page->param(webpath => $IPDB::webpath);
82}
83
84my $header = HTML::Template->new(filename => "header.tmpl");
85$header->param(version => $IPDB::VERSION);
86$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
87$header->param(webpath => $IPDB::webpath);
88print "Content-type: text/html\n\n", $header->output;
89
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
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') {
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+$//;
111 if ($webvar{input} =~ /^\d+$/) {
112 # All-digits, new custID
113 $searchfor = "cust";
114 } elsif ($webvar{input} =~ /^[\d\.]+(\/\d{1,3})?$/) {
115 # IP addresses should only have numbers, digits, and maybe a slash+netmask
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
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
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 {
141 # sum-buddy tryn'a game the system. Match "all"
142 $sqlconcat = "INTERSECT";
143 }
144
145# We actually construct a monster SQL statement for all criteria.
146# Iff something has been entered, it will be used as a filter.
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.
149
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
158 # First chunk of SQL. Filter on custid, description, and notes as necessary.
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}')";
163
164 # If we're not supposed to search for all types, search for the selected types.
165 $webvar{alltypes} = '' if !$webvar{alltypes};
166 $webvar{typeexclude} = '' if !$webvar{typeexclude};
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 .= "))";
174 }
175
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.
178 $webvar{allcities} = '' if !$webvar{allcities};
179 $webvar{cityexclude} = '' if !$webvar{cityexclude};
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 }
192 }
193 chop $sql;
194 $sql .= "))";
195 }
196
197 ## CIDR query options.
198 $webvar{cidr} =~ s/\s+//; # Hates the nasty spaceseseses we does.
199 if ($webvar{cidr} eq '') { # We has a blank CIDR. Ignore it.
200 } elsif ($webvar{cidr} =~ /\//) {
201 # 192.168.179/26 should show all /26 subnets in 192.168.179
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 ".
207 "$webvar{cidrexclude} cidr<<='$webvar{cidr}')";
208 } else {
209 # Partial match; beginning of subnet and maskbits are provided
210 # Show any blocks with the leading octet(s) and that masklength
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");
214 $sql .= " $sqlconcat (select $cols from searchme where $webvar{cidrexclude} ".
215 "($condition))";
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 {
227 # do nothing.
228 ##fixme we'll ignore this to clear out the references to legacy code.
229 } # done with CIDR query options.
230
231 # Find the offset for multipage results
232 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
233
234 # Find out how many rows the "core" query will return.
235 my $count = countRows($sql);
236
237 if ($count == 0) {
238 $page->param(errmsg => "No matches found. Try eliminating one of the criteria,".
239 " or making one or more criteria more general.");
240 } else {
241 # Add the limit/offset clauses
242 $sql .= " order by cidr";
243 $sql .= " limit $RESULTS_PER_PAGE offset $offset" if $RESULTS_PER_PAGE != 0;
244 # And tell the user.
245 print "<div class=heading>Searching...............</div>\n";
246 queryResults($sql, $webvar{page}, $count);
247 }
248
249} elsif ($webvar{stype} eq 'n') {
250 # Node search.
251
252 my $sql = "SELECT $cols FROM searchme".
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) {
262 $page->param(errmsg => "No customers currently listed as connected through this node.");
263##fixme: still get the results table header
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
273} else { # how script was called. General case is to show the search criteria page.
274
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;
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;
289 }
290 $page->param(typelist => \@typelist);
291
292# Generate table of cities
293 $sth = $ip_dbh->prepare("select id,city from cities order by city");
294 $sth->execute;
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;
305 }
306 $page->param(citylist => \@citylist);
307
308}
309
310print $page->output;
311
312# Shut down and clean up.
313finish($ip_dbh);
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
322# We shouldn't need to directly execute any code below here; it's all subroutines.
323exit 0;
324
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()
331sub viewBy {
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:
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"
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
352 $sql = "select $cols from searchme";
353 my $count = countRows($sql);
354 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
355 queryResults($sql, $webvar{page}, $count);
356
357 } elsif ($category eq 'cust') {
358
359##fixme: this and other quick-search areas; fix up page heading title similar to first grouping above
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. :/
364 $sql = "select $cols from searchme where custid ilike '%$query%' or description like '%$query%'";
365 my $count = countRows($sql);
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).
373 $sql = "select $cols from searchme where description ilike '%$query%'".
374 " or custid ilike '%$query%'";
375 my $count = countRows($sql);
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 =~ /\//) {
386 # 192.168.179/26 should show all /26 subnets in 192.168.179
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>
391 $sql = "select $cols from searchme where cidr='$query'";
392 queryResults($sql, $webvar{page}, 1);
393 } else {
394 #print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
395 # Partial match; beginning of subnet and maskbits are provided
396 $sql = "select $cols from searchme where text(cidr) like '$net%' and ".
397 "text(cidr) like '%$maskbits'";
398 my $count = countRows($sql);
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
404 #print "4-octet pattern found; finding netblock containing IP $query<br>\n";
405 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
406 my $sfor = new NetAddr::IP $query;
407 $sth = $ip_dbh->prepare("select $cols from searchme where text(cidr) like '$net%'");
408 $sth->execute;
409 while (my @data = $sth->fetchrow_array()) {
410 my $cidr = new NetAddr::IP $data[0];
411 if ($cidr->contains($sfor)) {
412 queryResults("select $cols from searchme where cidr='$cidr'", $webvar{page}, 1);
413 }
414 }
415 } elsif ($query =~ /^(\d{1,3}\.){1,3}\d{1,3}\.?$/) {
416 #print "Finding matches with leading octet(s) $query<br>\n";
417 $sql = "select $cols from searchme where text(cidr) like '$query%'";
418 my $count = countRows($sql);
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...
423 $page->param(errmsg => "Invalid query.");
424 }
425 } else {
426 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
427 $page->param(errmsg => "Invalid searchfor.");
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
456# queryResults()
457# Display search queries based on the passed SQL.
458# Takes SQL, page number (for multipage search results), and a total count.
459sub queryResults {
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
467 $page->param(searchtitle => "Showing all netblock and static-IP allocations");
468
469 my $count = 0;
470 my @sresults;
471 while (my ($block, $custid, $type, $city, $desc, $id, $parent, $avail) = $sth->fetchrow_array) {
472 my %row = (
473 rowclass => $count++ % 2,
474 issub => ($type =~ /^.r$/ ? 1 : 0),
475 ispool => ($type =~ /^.[pd]$/ ? 1 : 0),
476 basetype => ($type =~ /^.i/ ? 'i' : 'b'),
477 freeip => ($avail eq 'y'),
478 parent => $parent,
479 block => $block,
480 custid => $custid,
481 disptype => $disp_alloctypes{$type},
482 city => $city,
483 desc => $desc,
484 id => $id,
485 );
486 push @sresults, \%row;
487 }
488 $page->param(sresults => \@sresults);
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
496 $page->param(resfound => $rowCount);
497 $page->param(resstart => $offset+1);
498 $page->param(resstop => $upper);
499
500 # print the page thing..
501 if ($RESULTS_PER_PAGE > 0 && $rowCount > $RESULTS_PER_PAGE) {
502 $page->param(multipage => 1);
503 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
504 my @pagelist;
505 for (my $i = 1; $i <= $pages; $i++) {
506 my %row;
507 $row{pgnum} = $i;
508 if ($i == $pageNo) {
509 $row{thispage} = 1;
510 } else {
511 $row{stype} = $webvar{stype};
512 if ($webvar{stype} eq 'c') {
513 $row{extraopts} = "cidr=$webvar{cidr}&custid=$webvar{custid}&desc=$webvar{desc}&".
514 "notes=$webvar{notes}&which=$webvar{which}&alltypes=$webvar{alltypes}&".
515 "allcities=$webvar{allcities}&";
516 foreach my $key (keys %webvar) {
517 if ($key =~ /^(?:type|city)\[/ || $key =~ /exclude$/) {
518 $row{extraopts} .= "$key=$webvar{$key}&";
519 }
520 }
521 } else {
522 $row{extraopts} = "input=$webvar{input}&";
523 }
524 }
525 push @pagelist, \%row;
526 }
527 $page->param(pgnums => \@pagelist);
528 }
529
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
545# Return count of rows to be returned in a "real" query
546# with the passed SQL statement
547sub countRows {
548 # Note that the "as foo" is required
549 my $sth = $ip_dbh->prepare("select count(*) from ($_[0]) as foo");
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.