source: trunk/dns.cgi@ 60

Last change on this file since 60 was 60, checked in by Kris Deugau, 15 years ago

/trunk

Littleish cosmetic tweaks to log display
Tweaks to calls into log display page so that it shows the right data
Stub in section to show log for a user (not sure how useful this will

be...) - NB, this is not linked from anywhere and not present at all
in Vega's implementation

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 44.8 KB
Line 
1#!/usr/bin/perl -w -T
2# dns/cgi-bin/dns.cgi
3###
4# SVN revision info
5# $Date: 2010-01-15 19:52:28 +0000 (Fri, 15 Jan 2010) $
6# SVN revision $Rev: 60 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2008,2009 - Kris Deugau <kdeugau@deepnet.cx>
10
11use strict;
12use warnings;
13
14use CGI::Carp qw (fatalsToBrowser);
15use CGI::Simple;
16use HTML::Template;
17use CGI::Session;
18use Crypt::PasswdMD5;
19use Net::DNS;
20use DBI;
21
22use lib '.';
23# custom modules
24use DNSDB qw(:ALL);
25
26my @debugbits; # temp, to be spit out near the end of processing
27my $debugenv = 0;
28
29# Let's do these templates right...
30my $templatedir = "templates";
31my $sessiondir = "session";
32
33# Set up the CGI object...
34my $q = new CGI::Simple;
35# ... and get query-string params as well as POST params if necessary
36$q->parse_query_string;
37
38# This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about...
39my %webvar = $q->Vars;
40
41# persistent stuff needed on most/all pages
42my $sid = ($webvar{sid} ? $webvar{sid} : undef);
43my $session = new CGI::Session("driver:File", $sid, {Directory => $sessiondir});
44#$sid = $session->id() if !$sid;
45if (!$sid) {
46 # init stuff. can probably axe this down to just above if'n'when user manipulation happens
47 $sid = $session->id();
48# need to know the "upper" group the user can deal with; may as well
49# stick this in the session rather than calling out to the DB every time.
50 $session->param('logingroup',1);
51 $session->param('curgroup',1); # yes, we *do* need to track this too. er, probably.
52 $session->param('domlistsortby','domain');
53 $session->param('domlistorder','ASC');
54 $session->param('useradminsortby','user');
55 $session->param('useradminorder','ASC');
56 $session->param('grpmansortby','group');
57 $session->param('grpmanorder','ASC');
58 $session->param('reclistsortby','name');
59 $session->param('reclistorder','ASC');
60# $session->param('filter','login');
61# $session->param('startwith','login');
62# $session->param('searchsubs','login');
63}
64
65my $logingroup = ($session->param('logingroup') ? $session->param('logingroup') : 1);
66my $curgroup = ($session->param('curgroup') ? $session->param('curgroup') : $logingroup);
67my $group = ($webvar{group} ? $webvar{group} : 1);
68
69# per-page startwith, filter, searchsubs
70$session->param($webvar{page}.'startwith', $webvar{startwith}) if $webvar{startwith};
71$session->param($webvar{page}.'filter', $webvar{filter}) if $webvar{filter};
72$webvar{searchsubs} =~ s/^n ?// if $webvar{searchsubs};
73$session->param($webvar{page}.'searchsubs', $webvar{searchsubs}) if defined($webvar{searchsubs});
74
75my $startwith = $session->param($webvar{page}.'startwith');
76my $filter = $session->param($webvar{page}.'filter');
77my $searchsubs = $session->param($webvar{page}.'searchsubs');
78
79push @debugbits, "foo<br>\n" if defined($webvar{searchsubs});
80
81# nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet
82
83my $header = HTML::Template->new(filename => "$templatedir/header.tmpl");
84my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl");
85
86# default
87#my $perpage = 15;
88my $perpage = 3;
89my $offset = ($webvar{offset} ? $webvar{offset} : 0);
90
91# NB: these must match the field name and SQL ascend/descend syntax respectively
92my $sortby = "domain";
93my $sortorder = "ASC";
94
95my ($dbh,$msg) = connectDB("dnsdb","dnsdb","secret","dbhost");
96#my $dbh = DBI->connect("DBI:mysql:database=vegadns","vegadns","secret",
97# { AutoCommit => 0 }) or die $DBI::errstr;
98
99##fixme. PLEASE! <G>
100print $msg if !$dbh;
101
102# fiddle hardcoded "defaults" as per system/user (?) prefs
103initGlobals($dbh);
104
105# handle login redirect
106if ($webvar{action}) {
107 if ($webvar{action} eq 'login') {
108 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
109 $sth->execute($webvar{username});
110 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
111 $webvar{loginfailed} = 1 if !defined($uid);
112
113 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
114 $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1);
115 } else {
116 $webvar{loginfailed} = 1 if $pass ne $webvar{password};
117 }
118
119 # set session bits
120 $session->param('logingroup',$gid);
121 $session->param('curgroup',$gid);
122 $session->param('username',$webvar{username});
123
124 changepage(page => "domlist") if !defined($webvar{loginfailed});
125 } elsif ($webvar{action} eq 'logout') {
126 # delete the session
127 $session->delete();
128 $session->flush();
129
130 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}";
131 $newurl =~ s|/[^/]+$|/|;
132 print "Status: 302\nLocation: $newurl\n\n";
133 exit;
134
135 } elsif ($webvar{action} eq 'chgroup') {
136 # fiddle session-stored group data
137 # magic incantation to... uhhh...
138 $session->param('curgroup', $webvar{group});
139 $curgroup = ($webvar{group} ? $webvar{group} : $session->param('curgroup'));
140 }
141} # handle global webvar{action}s
142
143
144## Default page is a login page
145#my $page; # to be initialized as an HTML::Template entity sooner or later
146
147
148# decide which page to spit out...
149$webvar{page} = 'login' if !$webvar{page};
150#if (!$webvar{page}) {
151# $page = HTML::Template->new(filename => "$templatedir/login.tmpl");
152#} else {
153#}
154
155my $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl");
156
157$page->param(sid => $sid);
158
159if ($webvar{page} eq 'login') {
160
161 $page->param(loginfailed => 1) if $webvar{loginfailed};
162##fixme: set up session init to actually *check* for session timeout
163 $page->param(timeout => 1) if $webvar{sesstimeout};
164
165} elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') {
166
167# hmm. seeing problems in some possibly-not-so-corner cases.
168# this currently only handles "domain on", "domain off"
169 if (defined($webvar{action})) {
170 domStatus($dbh,$webvar{id},$webvar{action});
171 }
172
173 $page->param(curpage => $webvar{page});
174
175 listdomains();
176
177} elsif ($webvar{page} eq 'newdomain') {
178
179 # hmm. nothing to do here?
180 # - group list is filled by the same bit that fills the group list in the menu
181
182} elsif ($webvar{page} eq 'adddomain') {
183
184 my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0));
185
186 if ($code eq 'OK') {
187 logaction($msg, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}");
188 changepage(page => "reclist", id => $msg);
189 } else {
190 changepage(page => "newdomain", add_failed => 1, domain => $webvar{domain}, errmsg => $msg);
191 }
192
193} elsif ($webvar{page} eq 'deldom') {
194
195 $page->param(id => $webvar{id});
196 # first pass = confirm y/n (sorta)
197 if (!defined($webvar{del})) {
198 $page->param(del_getconf => 1);
199 $page->param(domain => domainName($dbh,$webvar{id}));
200# print some neato things?
201
202# } else {
203# #whether actually deleting or cancelling we redirect to the domain list, default format
204
205 } elsif ($webvar{del} eq 'ok') {
206 my $pargroup = parentID($webvar{id}, 'dom', 'group');
207 my ($code,$msg) = delDomain($dbh, $webvar{id});
208 if ($code ne 'OK') {
209# need to find failure mode
210 $page->param(del_failed => 1);
211 $page->param(errmsg => $msg);
212 listdomains($curgroup);
213 } else {
214##fixme: need domain to put in log message
215 logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $webvar{domain}");
216 changepage(page => "domlist");
217 }
218 } else {
219 # cancelled. whee!
220 changepage(page => "domlist");
221 }
222
223} elsif ($webvar{page} eq 'reclist') {
224
225 # Handle record list for both default records (per-group) and live domain records
226
227 $page->param(defrec => $webvar{defrec});
228 $page->param(id => $webvar{id});
229 $page->param(curpage => $webvar{page});
230
231# select count(*) from (default_)?records where (group|domain)_id=?
232 my $sth = $dbh->prepare("SELECT count(*) FROM ".
233 ($webvar{defrec} eq 'y' ? 'default_' : '')."records ".
234 "WHERE ".($webvar{defrec} eq 'y' ? 'group' : 'domain')."_id=? ".
235 "AND NOT type=$reverse_typemap{SOA}");
236 $sth->execute($webvar{id});
237 my ($count) = ($sth->fetchrow_array);
238
239# fill the page-count and first-previous-next-last-all details
240 fill_pgcount($count,"records",domainName($dbh,$webvar{id}));
241 fill_fpnla($count); # should put some params on this sub...
242
243 $page->param(defrec => $webvar{defrec});
244 if ($webvar{defrec} eq 'y') {
245##fixme: hardcoded group
246 showdomain('y',$curgroup);
247 } else {
248 showdomain('n',$webvar{id});
249 $page->param(logdom => 1);
250 }
251
252} elsif ($webvar{page} eq 'record') {
253
254$debugenv = 1;
255
256 if ($webvar{recact} eq 'new') {
257
258 $page->param(todo => "Add record to");
259 $page->param(recact => "add");
260 $page->param(parentid => $webvar{parentid});
261 $page->param(defrec => $webvar{defrec});
262
263 fill_recdata();
264
265 } elsif ($webvar{recact} eq 'add') {
266
267 my @recargs = ($dbh,$webvar{defrec},$webvar{parentid},$webvar{name},$webvar{type},$webvar{address},$webvar{ttl});
268 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) {
269 push @recargs, $webvar{distance};
270 if ($webvar{type} == $reverse_typemap{SRV}) {
271 push @recargs, $webvar{weight};
272 push @recargs, $webvar{port};
273 }
274 }
275
276 my ($code,$msg) = addRec(@recargs);
277
278 if ($code eq 'OK') {
279 if ($webvar{defrec} eq 'y') {
280 logaction(0, $session->param("username"), $webvar{parentid},
281 "Added default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
282 } else {
283 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'),
284 "Added record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
285 }
286 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
287 } else {
288 $page->param(failed => 1);
289 $page->param(errmsg => $msg);
290 $page->param(wastrying => "adding");
291 $page->param(todo => "Add record to");
292 $page->param(recact => "add");
293 $page->param(parentid => $webvar{parentid});
294 $page->param(defrec => $webvar{defrec});
295 $page->param(id => $webvar{id});
296 fill_recdata(); # populate the form... er, mostly.
297 if ($webvar{defrec} eq 'y') {
298 logaction(0, $session->param("username"), $webvar{parentid},
299 "Failed adding default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
300 } else {
301 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'),
302 "Failed adding record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
303 }
304 }
305
306 } elsif ($webvar{recact} eq 'edit') {
307
308 $page->param(todo => "Update record");
309 $page->param(recact => "update");
310 $page->param(parentid => $webvar{parentid});
311 $page->param(id => $webvar{id});
312 $page->param(defrec => $webvar{defrec});
313##fixme: SQL does not belong!
314 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM ".
315 ($webvar{defrec} eq 'y' ? 'default_' : '')."records WHERE record_id=?");
316 $sth->execute($webvar{id});
317 my ($host,$type,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array;
318 $page->param(name => $host);
319 $page->param(address => $val);
320 $page->param(distance => $distance);
321 $page->param(weight => $weight);
322 $page->param(port => $port);
323 $page->param(ttl => $ttl);
324 fill_rectypes($type);
325
326 } elsif ($webvar{recact} eq 'update') {
327
328 my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{id},
329 $webvar{name},$webvar{type},$webvar{address},$webvar{ttl},
330 $webvar{distance},$webvar{weight},$webvar{port});
331
332 if ($code eq 'OK') {
333##fixme: need more magic to get proper group - if domain was fiddled
334# from search-subgroups listing, may not be "current" group
335
336# SELECT d.group_id FROM domains d INNER JOIN records r ON d.domain_id=r.domain_id WHERE r.record_id=?
337# $sth->execute($webvar{id});
338##log
339 if ($webvar{defrec} eq 'y') {
340 logaction(0, $session->param("username"), $webvar{parentid},
341 "Updated default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
342 } else {
343 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{id}, 'rec', 'group'),
344 "Updated record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
345 }
346 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
347 } else {
348 $page->param(failed => 1);
349 $page->param(errmsg => $msg);
350 $page->param(wastrying => "updating");
351 $page->param(todo => "Update record");
352 $page->param(recact => "update");
353 $page->param(parentid => $webvar{parentid});
354 $page->param(defrec => $webvar{defrec});
355 $page->param(id => $webvar{id});
356 fill_recdata();
357 if ($webvar{defrec} eq 'y') {
358 logaction(0, $session->param("username"), $webvar{parentid},
359 "Failed updating default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
360 } else {
361 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'),
362 "Failed updating record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
363 }
364 }
365 }
366
367 if ($webvar{defrec} eq 'y') {
368 $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid}));
369 } else {
370 $page->param(parentid => $webvar{parentid});
371# $page->param(id => $webvar{id});
372 $page->param(dohere => domainName($dbh,$webvar{parentid}));
373 }
374
375} elsif ($webvar{page} eq 'delrec') {
376
377 $page->param(id => $webvar{id});
378 $page->param(defrec => $webvar{defrec});
379 $page->param(parentid => $webvar{parentid});
380 # first pass = confirm y/n (sorta)
381 if (!defined($webvar{del})) {
382 $page->param(del_getconf => 1);
383 my %rec = getRecLine($dbh,$webvar{defrec},$webvar{id});
384 $page->param(host => $rec{host});
385 $page->param(ftype => $typemap{$rec{type}});
386 $page->param(recval => $rec{val});
387 } elsif ($webvar{del} eq 'ok') {
388# get groupid of deleted record before we try to delete it
389 my $pargrp = parentID($webvar{id}, 'rec', 'group', $webvar{defrec});
390 my ($code,$msg) = delRec($dbh,$webvar{defrec},$webvar{id});
391 if ($code ne 'OK') {
392## need to find failure mode
393 #logaction(
394 $page->param(del_failed => 1);
395 $page->param(errmsg => $msg);
396 showdomain($webvar{defrec}, $webvar{parentid});
397 } else {
398##log
399 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
400 }
401 } else {
402 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
403 }
404
405} elsif ($webvar{page} eq 'editsoa') {
406
407 fillsoa($webvar{defrec},$webvar{id});
408
409} elsif ($webvar{page} eq 'updatesoa') {
410
411 my $sth;
412 my $sql = '';
413 # no domain ID, so we're editing the default SOA for a group (we don't care which one here)
414 # plus a bit of magic to update the appropriate table
415 $sql = "update ".($webvar{defrec} eq 'y' ? "default_records" : "records").
416 " set host='$webvar{prins}:$webvar{contact}',".
417 " val='$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}',".
418 " ttl=$webvar{ttl} where record_id=$webvar{recid}";
419 $sth = $dbh->prepare($sql);
420 $sth->execute;
421
422 if ($sth->err) {
423 $page->param(update_failed => 1);
424 $page->param(msg => $DBI::errstr);
425 fillsoa($webvar{defrec},$webvar{id});
426 } else {
427
428##fixme! need to set group ID properly here
429# SELECT group_id FROM domains WHERE domain_id=?
430# $sth->execute($webvar{id});
431##log
432 logaction(0, $session->param("username"), $webvar{group},
433 "Updated SOA (ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},".
434 " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl}");
435 changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec});
436# $page->param(update_failed => 0);
437# showdomain('y',1);
438 }
439
440} elsif ($webvar{page} eq 'grpman') {
441
442 listgroups();
443 $page->param(curpage => $webvar{page});
444
445} elsif ($webvar{page} eq 'newgrp') {
446
447 # do.. uhh.. stuff.. if we have no webvar{action}
448 if ($webvar{action} && $webvar{action} eq 'add') {
449 # not gonna provide the 4th param: template-or-clone flag, just yet
450 my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup});
451 if ($code eq 'OK') {
452 logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}");
453 changepage(page => "grpman");
454 }
455 $page->param(add_failed => 1);
456 $page->param(errmsg => $msg);
457 $page->param(newgroup => $webvar{newgroup});
458 fill_grouplist('pargroup',$webvar{pargroup});
459 } else {
460# $page->param
461 fill_grouplist('pargroup',$curgroup);
462
463 }
464
465} elsif ($webvar{page} eq 'delgrp') {
466
467 $page->param(id => $webvar{id});
468 # first pass = confirm y/n (sorta)
469 if (!defined($webvar{del})) {
470 $page->param(del_getconf => 1);
471# $page->param(groupname => groupName($dbh,$webvar{id}));
472# print some neato things?
473
474# } else {
475# #whether actually deleting or cancelling we redirect to the group list, default format
476
477 } elsif ($webvar{del} eq 'ok') {
478 my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it...
479 my ($code,$msg) = delGroup($dbh, $webvar{id});
480 if ($code ne 'OK') {
481# need to find failure mode
482 $page->param(del_failed => 1);
483 $page->param(errmsg => $msg);
484 $page->param(curpage => $webvar{page});
485 listgroups();
486 } else {
487##fixme: need to clean up log when deleting a major container
488 logaction(0, $session->param("username"), $webvar{curgroup}, "Deleted group $deleteme");
489 # success. go back to the domain list, do not pass "GO"
490 changepage(page => "grpman");
491 }
492 } else {
493 # cancelled. whee!
494 changepage(page => "grpman");
495 }
496 $page->param(delgroupname => groupName($dbh, $webvar{id}));
497
498} elsif ($webvar{page} eq 'useradmin') {
499
500 if (defined($webvar{action})) {
501 userStatus($dbh,$webvar{id},$webvar{action});
502 }
503
504 $page->param(curpage => $webvar{page});
505
506 list_users();
507
508} elsif ($webvar{page} eq 'newuser') {
509
510 # foo?
511 fill_actypelist();
512
513} elsif ($webvar{page} eq 'adduser') {
514
515 my ($code,$msg);
516
517 if ($webvar{pass1} ne $webvar{pass2}) {
518 $code = 'FAIL';
519 $msg = "Passwords don't match";
520 } else {
521 ($code,$msg) = addUser($dbh,$webvar{uname}, $webvar{group}, $webvar{pass1},
522 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
523 $webvar{fname}, $webvar{lname}, $webvar{phone});
524 }
525
526# hokay, a bit of magic to decide which page we hit.
527 if ($code eq 'OK') {
528##log
529 logaction(0, $session->param("username"), $webvar{group},
530 "Added user $webvar{uname} ($webvar{fname} $webvar{lname})");
531 changepage(page => "useradmin");
532 } else {
533# oddity - apparently, xhtml 1.0 strict swallows username as an HTML::Template var. O_o
534 $page->param(add_failed => 1);
535 $page->param(uname => $webvar{uname});
536 $page->param(fname => $webvar{fname});
537 $page->param(lname => $webvar{lname});
538 $page->param(pass1 => $webvar{pass1});
539 $page->param(pass2 => $webvar{pass2});
540 $page->param(errmsg => $msg);
541 fill_actypelist();
542 }
543
544# $page->param(add_failed => 1);
545
546} elsif ($webvar{page} eq 'deluser') {
547
548 $page->param(id => $webvar{id});
549 # first pass = confirm y/n (sorta)
550 if (!defined($webvar{del})) {
551 $page->param(del_getconf => 1);
552 $page->param(user => userFullName($dbh,$webvar{id}));
553 } elsif ($webvar{del} eq 'ok') {
554##fixme: find group id user is in (for logging) *before* we delete the user
555 my ($code,$msg) = delUser($dbh, $webvar{id});
556 if ($code ne 'OK') {
557# need to find failure mode
558 $page->param(del_failed => 1);
559 $page->param(errmsg => $msg);
560 list_users($curgroup);
561 } else {
562 # success. go back to the domain list, do not pass "GO"
563##log
564 logaction(0, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}");
565 changepage(page => "useradmin");
566 }
567 } else {
568 # cancelled. whee!
569 changepage(page => "useradmin");
570 }
571
572} elsif ($webvar{page} eq 'dnsq') {
573
574 $page->param(qfor => $webvar{qfor}) if $webvar{qfor};
575 fill_rectypes($webvar{type} ? $webvar{type} : '', 1);
576 $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse};
577 $page->param(resolver => $webvar{resolver}) if $webvar{resolver};
578
579 if ($webvar{qfor}) {
580 my $resolv = Net::DNS::Resolver->new;
581 $resolv->tcp_timeout(5); # make me adjustable!
582 $resolv->udp_timeout(5); # make me adjustable!
583 $resolv->recurse(0) if $webvar{nrecurse};
584 $resolv->nameservers($webvar{resolver}) if $webvar{resolver};
585 my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}});
586 if ($query) {
587
588 $page->param(showresults => 1);
589
590 my @answer;
591 foreach my $rr ($query->answer) {
592# next unless $rr->type eq "A" or $rr->type eq 'NS';
593 my %row;
594 my ($host,$ttl,$class,$type,$data) =
595 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s);
596 $row{host} = $host;
597 $row{ftype} = $type;
598 $row{rdata} = ($type eq 'SOA' ? "<pre>$data</pre>" : $data);
599 push @answer, \%row;
600 }
601 $page->param(answer => \@answer);
602
603 my @additional;
604 foreach my $rr ($query->additional) {
605# next unless $rr->type eq "A" or $rr->type eq 'NS';
606 my %row;
607 my ($host,$ttl,$class,$type,$data) =
608 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
609 $row{host} = $host;
610 $row{ftype} = $type;
611 $row{rdata} = $data;
612 push @additional, \%row;
613 }
614 $page->param(additional => \@additional);
615
616 my @authority;
617 foreach my $rr ($query->authority) {
618# next unless $rr->type eq "A" or $rr->type eq 'NS';
619 my %row;
620 my ($host,$ttl,$class,$type,$data) =
621 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
622 $row{host} = $host;
623 $row{ftype} = $type;
624 $row{rdata} = $data;
625 push @authority, \%row;
626 }
627 $page->param(authority => \@authority);
628
629 $page->param(usedresolver => $resolv->answerfrom);
630 $page->param(frtype => $typemap{$webvar{type}});
631
632 } else {
633 $page->param(errmsg => $resolv->errorstring);
634 }
635 }
636 ## done DNS query
637
638} elsif ($webvar{page} eq 'axfr') {
639
640 # don't need this while we've got the dropdown in the menu. hmm.
641 #fill_grouplist;
642
643 $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom};
644 $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa};
645 $page->param(rwns => $webvar{rwns}) if $webvar{rwns};
646 $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww.
647 $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms};
648
649##fixme: check group too?
650 if ($webvar{doit} eq 'y' && !$webvar{ifrom}) {
651 $page->param(errmsg => "Need to set host to import from");
652 } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) {
653 $page->param(errmsg => "Need domains to import");
654 } else {
655 my @domlist = split /\s+/, $webvar{importdoms};
656 my @results;
657my $rnum = 0;
658 foreach my $domain (@domlist) {
659 my %row;
660 my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group},
661 $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns});
662 $row{domok} = $msg if $code eq 'OK';
663 if ($code eq 'WARN') {
664 $msg =~ s|\n|<br />|g;
665 $row{domwarn} = $msg;
666 }
667 if ($code eq 'FAIL') {
668 $msg =~ s|\n|<br />|g;
669 $row{domerr} = $msg;
670 }
671 # do stuff! DNSDB::importAXFR($webvar{ifrom}, $webvar{rwsoa}, $webvar{rwns}, $domain, <flags>)
672 $row{domain} = $domain;
673# $row{row} = $rnum++;
674 push @results, \%row;
675 }
676 $page->param(axfrresults => \@results);
677 }
678
679} elsif ($webvar{page} eq 'whoisq') {
680
681 if ($webvar{qfor}) {
682 use Net::Whois::Raw;
683 use Text::Wrap;
684
685# caching useful?
686#$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/";
687#$Net::Whois::Raw::CACHE_TIME = 60;
688
689 my ($dominfo, $whois_server) = whois($webvar{qfor});
690##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data
691
692 # le sigh. idjits spit out data without linefeeds...
693 $Text::Wrap::columns = 88;
694
695# &%$@%@# high-bit crap. We should probably find a way to properly recode these instead of one-by-one.
696# Mainly an XHTML validation thing.
697 $dominfo =~ s/\xa9/\&copy;/g;
698 $dominfo =~ s/\xae/\&reg;/g;
699
700 $page->param(qfor => $webvar{qfor});
701 $page->param(dominfo => wrap('','',$dominfo));
702 $page->param(whois_server => $whois_server);
703 } else {
704 $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway};
705 }
706
707} elsif ($webvar{page} eq 'log') {
708
709##fixme put in some real log-munching stuff
710##fixme need to add bits to *create* log entries...
711 my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE ";
712 my $id = $curgroup; # we do this because the group log may be called from (almost) any page,
713 # but the others are much more limited. this is probably non-optimal.
714 if ($werbvar{ltype} && $webvar{ltype} eq 'user') {
715 $sql .= "user_id=?";
716 $id = $webvar{id};
717 $page->param(logfor => 'user '.userFullName($dbh,$id));
718 } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') {
719 $sql .= "domain_id=?";
720 $id = $webvar{id};
721 $page->param(logfor => 'domain '.domainName($dbh,$id));
722 } else {
723 # Default to listing curgroup log
724 $sql .= "group_id=?";
725 $page->param(logfor => 'group '.groupName($dbh,$id));
726 }
727 my $sth = $dbh->prepare($sql);
728 $sth->execute($id);
729 my @logbits;
730 while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) {
731 my %row;
732 $row{userfname} = $name;
733 $row{userid} = $uid;
734 $row{useremail} = $email;
735 $row{logentry} = $entry;
736 ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/);
737 push @logbits, \%row;
738 }
739 $page->param(logentries => \@logbits);
740
741} # end $webvar{page} dance
742
743
744# start output here so we can redirect pages.
745print "Content-type: text/html\n\n", $header->output;
746
747##common bits
748if ($webvar{page} ne 'login') {
749 $page->param(username => $session->param("username"));
750
751 $page->param(group => $curgroup);
752 $page->param(groupname => groupName($dbh,$curgroup));
753 $page->param(logingrp => groupName($dbh,$logingroup));
754
755 # group tree. should go elsewhere, probably
756 my $tmpgrplist = fill_grptree($logingroup,$curgroup);
757 $page->param(grptree => $tmpgrplist);
758
759 $page->param(inlogingrp => $curgroup == $logingroup);
760
761 # stuff for menu group change. nb: this is icky.
762 fill_grouplist("grouplist");
763
764## set up "URL to self"
765# @#$%@%@#% XHTML - & in a URL must be escaped. >:(
766 my $tmp_ruri = $ENV{REQUEST_URI};
767 $tmp_ruri =~ s/\&([a-z])/\&amp\;$1/g;
768
769# le sigh. and we need to strip any previous action
770 $tmp_ruri =~ s/\&amp;action=[^&]+//g;
771
772# and search filter options. these get stored in the session, but discarded
773# as soon as you switch to a different page.
774##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits
775 no warnings qw(uninitialized);
776 $tmp_ruri =~ s/\&amp;startwith=[a-z09-]*(\&)?/$1/g;
777 $tmp_ruri =~ s/\&amp;searchsubs=[a-z09-]*(\&)?/$1/g;
778 $tmp_ruri =~ s/\&amp;filter=[a-z09-]*(\&)?/$1/g;
779 use warnings qw(uninitialized);
780
781# fill in the URL-to-self
782 $page->param(whereami => $tmp_ruri);
783}
784
785foreach (@debugbits) { print; }
786
787# spit it out
788print $page->output;
789
790if ($debugenv) {
791 print "<div id=\"debug\">webvar keys: <pre>\n";
792 foreach my $key (keys %webvar) {
793 print "key: $key\tval: $webvar{$key}\n";
794 }
795 print "</pre>\nsession:\n<pre>\n";
796 my $sesdata = $session->dataref();
797 foreach my $key (keys %$sesdata) {
798 print "key: $key\tval: ".$sesdata->{$key}."\n";
799 }
800 print "</pre>\nENV:\n<pre>\n";
801 foreach my $key (keys %ENV) {
802 print "key: $key\tval: $ENV{$key}\n";
803 }
804 print "</pre></div>\n";
805}
806
807print $footer->output;
808
809# as per the docs, Just In Case
810$session->flush();
811
812exit 0;
813
814
815sub fill_grptree {
816 my $root = shift;
817 my $cur = shift;
818
819 my @childlist;
820
821 my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl');
822 getChildren($dbh,$root,\@childlist,'immediate');
823 return if $#childlist == -1;
824 my @grouplist;
825 foreach (@childlist) {
826 my %row;
827 $row{grpname} = groupName($dbh,$_);
828 $row{grpname} = "<b>$row{grpname}</b>" if $_ == $cur;
829 $row{subs} = fill_grptree($_,$cur);
830 push @grouplist, \%row;
831 }
832 $grptree->param(treelvl => \@grouplist);
833 return $grptree->output;
834}
835
836sub changepage {
837 my %params = @_; # think this works the way I want...
838
839 # handle user check
840 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid";
841 foreach (keys %params) {
842 $newurl .= "&$_=$params{$_}";
843 }
844
845 # Just In Case
846 $session->flush();
847
848 print "Status: 302\nLocation: $newurl\n\n";
849 exit;
850} # end changepage
851
852sub fillsoa {
853 my $def = shift;
854 my $id = shift;
855 my $domname = ($def eq 'y' ? '' : "DOMAIN");
856
857 $page->param(defrec => $def);
858
859# i had a good reason to do this when I wrote it...
860# $page->param(domain => $domname);
861# $page->param(group => $DNSDB::group);
862 $page->param(isgrp => 1) if $def eq 'y';
863 $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) );
864
865# defaults
866 $page->param(defcontact => $DNSDB::def{contact});
867 $page->param(defns => $DNSDB::def{prins});
868 $page->param(defsoattl => $DNSDB::def{soattl});
869 $page->param(defrefresh => $DNSDB::def{refresh});
870 $page->param(defretry => $DNSDB::def{retry});
871 $page->param(defexpire => $DNSDB::def{expire});
872 $page->param(defminttl => $DNSDB::def{minttl});
873
874 # there are probably better ways to do this. TMTOWTDI.
875 my %soa = getSOA($dbh,$def,$id);
876
877 $page->param(id => $id);
878 $page->param(recid => $soa{recid});
879 $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins}));
880 $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact}));
881 $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh}));
882 $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry}));
883 $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire}));
884 $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl}));
885 $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl}));
886}
887
888sub showdomain {
889 my $def = shift;
890 my $id = shift;
891
892 # get the SOA first
893 my %soa = getSOA($dbh,$def,$id);
894
895 $page->param(recid => $soa{recid});
896 $page->param(contact => $soa{contact});
897 $page->param(prins => $soa{prins});
898 $page->param(refresh => $soa{refresh});
899 $page->param(retry => $soa{retry});
900 $page->param(expire => $soa{expire});
901 $page->param(minttl => $soa{minttl});
902 $page->param(ttl => $soa{ttl});
903
904# my @foo2 = getDomRecs($dbh,'def',1);
905 my $foo2 = getDomRecs($dbh,$def,$id,$perpage,$webvar{offset});
906
907 my $row = 0;
908 foreach my $rec (@$foo2) {
909 $rec->{type} = $typemap{$rec->{type}};
910 $rec->{row} = $row % 2;
911 $rec->{defrec} = $webvar{defrec};
912 $rec->{sid} = $webvar{sid};
913 $rec->{id} = $id;
914 $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV');
915 $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV');
916 $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV');
917 $row++;
918 }
919 $page->param(reclist => $foo2);
920}
921
922# fill in record type list on add/update/edit record template
923sub fill_rectypes {
924 my $type = shift || $reverse_typemap{A};
925 my $soaflag = shift || 0;
926
927 my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder");
928 $sth->execute;
929 my @typelist;
930 while (my ($rval,$rname) = $sth->fetchrow_array()) {
931 my %row = ( recval => $rval, recname => $rname );
932 $row{tselect} = 1 if $rval == $type;
933 push @typelist, \%row;
934 }
935 if ($soaflag) {
936 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
937 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
938 push @typelist, \%row;
939 }
940 $page->param(typelist => \@typelist);
941} # fill_rectypes
942
943sub fill_recdata {
944 fill_rectypes($webvar{type});
945
946 $page->param(name => $webvar{name});
947 $page->param(address => $webvar{address});
948 $page->param(distance => $webvar{distance})
949 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV});
950 $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV};
951 $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV};
952 $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $DNSDB::def{minttl}));
953}
954
955sub fill_actypelist {
956 my @actypes;
957
958 my %row1 = (actypeval => 'u', actypename => 'user');
959 $row1{typesel} = 1 if $webvar{accttype} eq 'u';
960 push @actypes, \%row1;
961
962 my %row2 = (actypeval => 'S', actypename => 'superuser');
963 $row2{typesel} = 1 if $webvar{accttype} eq 'S';
964 push @actypes, \%row2;
965
966 $page->param(actypelist => \@actypes);
967}
968
969sub fill_fpnla {
970 my $count = shift;
971##fixme
972 if ($offset eq 'all') {
973# uhm....
974 } else {
975 # all these bits only have sensible behaviour if offset is numeric. err, probably.
976 if ($count > $perpage) {
977 # if there are more results than the default, always show the "all" link
978 $page->param(navall => 1);
979
980 if ($offset > 0) {
981 $page->param(navfirst => 1);
982 $page->param(navprev => 1);
983 $page->param(prevoffs => $offset-1);
984 }
985
986 # show "next" and "last" links if we're not on the last page of results
987 if ( (($offset+1) * $perpage - $count) < 0 ) {
988 $page->param(navnext => 1);
989 $page->param(nextoffs => $offset+1);
990 $page->param(navlast => 1);
991 $page->param(lastoffs => int (($count-1)/$perpage));
992 }
993 }
994 }
995} # end fill_fpnla()
996
997sub fill_pgcount {
998 my $pgcount = shift;
999 my $pgtype = shift;
1000 my $parent = shift;
1001
1002 $page->param(ntot => $pgcount);
1003 $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1));
1004 $page->param(npglast => ($offset eq 'all' ? $pgcount :
1005 ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) )
1006 ));
1007 $page->param(pgtype => $pgtype);
1008 $page->param(parent => $parent);
1009} # end fill_pgcount()
1010
1011sub listdomains {
1012
1013##fixme: $logingroup or $curgroup?
1014 my @childgroups;
1015 #getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1016 my $childlist = join(',',@childgroups);
1017
1018 my $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1019 ($startwith ? " AND domain ~* '^[$startwith]'" : '').
1020 ($filter ? " AND domain ~* '$filter'" : '');
1021 my $sth = $dbh->prepare($sql);
1022 $sth->execute;
1023 my ($count) = $sth->fetchrow_array;
1024
1025# fill page count and first-previous-next-last-all bits
1026##fixme - hardcoded group bit
1027 fill_pgcount($count,"domains",groupName($dbh,$curgroup));
1028 fill_fpnla($count);
1029
1030# sort/order
1031 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1032 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1033
1034 $sortby = $session->param($webvar{page}.'sortby');
1035 $sortorder = $session->param($webvar{page}.'order');
1036
1037# set up the headers
1038 my @cols = ('domain', 'status', 'group');
1039 my %colheads = (domain => 'Domain', status => 'Status', group => 'Group');
1040 fill_colheads($sortby, $sortorder, \@cols, \%colheads);
1041
1042# $page->param(sortorder => $sortorder);
1043 # hack! hack! pthbttt. have to rethink the status column storage,
1044 # or inactive comes "before" active. *sigh*
1045 $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status';
1046
1047# waffle, waffle - keep state on these as well as sortby, sortorder?
1048 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1049
1050 $page->param(filter => $filter) if $filter;
1051 $page->param(searchsubs => $searchsubs) if $searchsubs;
1052
1053##fixme
1054##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
1055##fixme
1056
1057 $page->param(group => $curgroup);
1058 my @domlist;
1059 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1060 " INNER JOIN groups ON domains.group_id=groups.group_id".
1061 " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1062##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1063 ($startwith ? " AND domain ~* '^[$startwith]'" : '').
1064 ($filter ? " AND domain ~* '$filter'" : '').
1065 " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $sortby).
1066 " $sortorder ".($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1067 $sth = $dbh->prepare($sql);
1068 $sth->execute;
1069 my $rownum = 0;
1070 while (my @data = $sth->fetchrow_array) {
1071 my %row;
1072 $row{domainid} = $data[0];
1073 $row{domain} = $data[1];
1074 $row{status} = ($data[2] ? 'Active' : 'Inactive');
1075 $row{group} = $data[3];
1076 $row{bg} = ($rownum++)%2;
1077# $row{mkactive} = ($data[2] eq 'inactive' ? 1 : 0);
1078 $row{mkactive} = !$data[2];
1079 $row{sid} = $sid;
1080 $row{offset} = $offset;
1081##fixme: need to clean up status indicator/usage/inversion
1082 push @domlist, \%row;
1083 }
1084 $page->param(domtable => \@domlist);
1085} # end listdomains()
1086
1087sub listgroups {
1088
1089 my @childgroups;
1090 getChildren($dbh, $logingroup, \@childgroups, 'all') if $searchsubs;
1091 my $childlist = join(',',@childgroups);
1092
1093 my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
1094 ($startwith ? " AND group_name ~* '^[$startwith]'" : '').
1095 ($filter ? " AND group_name ~* '$filter'" : '');
1096 my $sth = $dbh->prepare($sql);
1097
1098 $sth->execute;
1099 my ($count) = ($sth->fetchrow_array);
1100# fill page count and first-previous-next-last-all bits
1101##fixme - hardcoded group bit
1102 fill_pgcount($count,"groups",'');
1103 fill_fpnla($count);
1104
1105# $sortby = 'group';
1106# sort/order
1107 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1108 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1109
1110 $sortby = $session->param($webvar{page}.'sortby');
1111 $sortorder = $session->param($webvar{page}.'order');
1112
1113# set up the headers
1114 my @cols = ('group','parent','nusers','ndomains');
1115 my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains');
1116 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1117
1118# waffle, waffle - keep state on these as well as sortby, sortorder?
1119 $page->param("start$webvar{startwith}" => 1) if $webvar{startwith} && $webvar{startwith} =~ /^[a-z]$/;
1120
1121 $page->param(filter => $filter) if $filter;
1122 $page->param(searchsubs => $searchsubs) if $searchsubs;
1123
1124# munge sortby for columns in database
1125 $sortby = 'g.group_name' if $sortby eq 'group';
1126 $sortby = 'g2.group_name' if $sortby eq 'parent';
1127
1128 my @grouplist;
1129 $sth = $dbh->prepare("SELECT g.group_id, g.group_name, g2.group_name, ".
1130 "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ".
1131 "FROM groups g ".
1132 "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ".
1133 "LEFT OUTER JOIN users u ON u.group_id=g.group_id ".
1134 "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ".
1135 "WHERE g.parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').") ".
1136##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1137 ($startwith ? " AND g.group_name ~* '^[$startwith]'" : '').
1138 ($filter ? " AND g.group_name ~* '$filter'" : '').
1139 " GROUP BY g.group_id, g.group_name, g2.group_name ".
1140 " ORDER BY $sortby $sortorder ".
1141 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage));
1142 $sth->execute;
1143
1144 my $rownum = 0;
1145 while (my @data = $sth->fetchrow_array) {
1146 my %row;
1147 $row{groupid} = $data[0];
1148 $row{groupname} = $data[1];
1149 $row{pgroup} = $data[2];
1150 $row{nusers} = $data[3];
1151 $row{ndomains} = $data[4];
1152 $row{bg} = ($rownum++)%2;
1153 $row{sid} = $sid;
1154 push @grouplist, \%row;
1155 }
1156 $page->param(grouptable => \@grouplist);
1157} # end listgroups()
1158
1159sub fill_grouplist {
1160 my $template_var = shift;
1161 my $cur = shift || $curgroup;
1162
1163 my @childgroups;
1164 getChildren($dbh, $logingroup, \@childgroups, 'all');
1165 my $childlist = join(',',@childgroups);
1166
1167 # weesa gonna discard parent_group_id for now
1168 my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ".
1169 "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
1170 "ORDER BY group_id");
1171 $sth->execute;
1172 my @grouplist;
1173 while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) {
1174 my %row;
1175 $row{groupname} = $groupname;
1176 $row{groupval} = $groupid;
1177##fixme: need magic
1178# $row{defgroup} = '';
1179 $row{groupactive} = 1 if $groupid == $cur;
1180 push @grouplist, \%row;
1181 }
1182
1183 $page->param("$template_var" => \@grouplist);
1184
1185} # end fill_grouplist()
1186
1187sub list_users {
1188
1189 my @childgroups;
1190 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1191 my $childlist = join(',',@childgroups);
1192
1193 my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1194 ($startwith ? " AND username ~* '^[$startwith]'" : '').
1195 ($filter ? " AND username ~* '$filter'" : '');
1196 my $sth = $dbh->prepare($sql);
1197 $sth->execute;
1198 my ($count) = ($sth->fetchrow_array);
1199
1200# fill page count and first-previous-next-last-all bits
1201##fixme - hardcoded group bit
1202 fill_pgcount($count,"users",'');
1203 fill_fpnla($count);
1204
1205# $sortby = 'user';
1206# sort/order
1207 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1208 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1209
1210 $sortby = $session->param($webvar{page}.'sortby');
1211 $sortorder = $session->param($webvar{page}.'order');
1212
1213# set up the headers
1214 my @cols = ('user','fname','type','group','status');
1215 my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status');
1216 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1217
1218# waffle, waffle - keep state on these as well as sortby, sortorder?
1219 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^[a-z]$/;
1220
1221 $page->param(filter => $filter) if $filter;
1222 $page->param(searchsubs => $searchsubs) if $searchsubs;
1223
1224# munge sortby for columns in database
1225 $sortby = 'u.username' if $sortby eq 'user';
1226 $sortby = 'u.type' if $sortby eq 'type';
1227 $sortby = 'g.group_name' if $sortby eq 'group';
1228 $sortby = 'u.status' if $sortby eq 'status';
1229
1230 my @userlist;
1231 $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
1232 "FROM users u ".
1233 "INNER JOIN groups g ON u.group_id=g.group_id ".
1234 "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1235##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1236 ($startwith ? " AND u.username ~* '^[$startwith]'" : '').
1237 ($filter ? " AND u.username ~* '$filter'" : '').
1238 " ORDER BY $sortby $sortorder ".
1239 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1240
1241 $sth = $dbh->prepare($sql);
1242 $sth->execute;
1243
1244 my $rownum = 0;
1245 while (my @data = $sth->fetchrow_array) {
1246 no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name
1247 my %row;
1248 $row{userid} = $data[0];
1249 $row{username} = $data[1];
1250 $row{userfull} = $data[2];
1251 $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user");
1252 $row{usergroup} = $data[4];
1253 $row{active} = $data[5];
1254 $row{bg} = ($rownum++)%2;
1255 $row{sid} = $sid;
1256 push @userlist, \%row;
1257 }
1258 $page->param(usertable => \@userlist);
1259} # end list_users()
1260
1261# Generate all of the glop necessary to add or not the appropriate marker/flag for
1262# the sort order and column in domain, user, group, and record lists
1263# Takes an array ref and hash ref
1264sub fill_colheads {
1265 my $sortby = shift;
1266 my $sortorder = shift;
1267 my $cols = shift;
1268 my $colnames = shift;
1269
1270 my @headings;
1271
1272 foreach my $col (@$cols) {
1273 my %coldata;
1274 $coldata{firstcol} = 1 if $col eq $cols->[0];
1275 $coldata{sid} = $sid;
1276 $coldata{page} = $webvar{page};
1277 $coldata{offset} = $webvar{offset} if $webvar{offset};
1278 $coldata{sortby} = $col;
1279 $coldata{colname} = $colnames->{$col};
1280 if ($col eq $sortby) {
1281 $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC');
1282 $coldata{sortorder} = $sortorder;
1283 } else {
1284 $coldata{order} = 'ASC';
1285 }
1286 push @headings, \%coldata;
1287 }
1288
1289 $page->param(colheads => \@headings);
1290
1291} # end fill_colheads()
1292
1293sub logaction {
1294 my $domid = shift;
1295 my $username = shift;
1296 my $groupid = shift;
1297 my $entry = shift;
1298
1299##fixme: ooohhh, nasty. what if we get a failure *here*? PTHBTT!
1300 my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?");
1301 $sth->execute($username);
1302 my ($user_id, $fullname) = $sth->fetchrow_array;
1303
1304 $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) ".
1305 "VALUES (?,?,?,?,?,?)");
1306 $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry);
1307} # end logaction()
1308
1309##fixme: generalize to return appropriate id on all cases (ie, use $partype)
1310sub parentID {
1311 my $id = shift;
1312 my $idtype = shift;
1313 my $partype = shift;
1314 my $defrec = shift || '';
1315
1316 my $sql = '';
1317
1318 if ($idtype eq 'dom') {
1319 return $id if $defrec eq 'y'; # "domain" + default records, we're really looking at a group.
1320 $sql = "SELECT group_id FROM domains WHERE domain_id=?";
1321 } elsif ($idtype eq 'rec') {
1322 if ($defrec eq 'y') {
1323 $sql = "SELECT group_id FROM default_records WHERE record_id=?";
1324 } else {
1325 return
1326 $sql = "SELECT d.group_id FROM domains d".
1327 " INNER JOIN records r ON d.domain_id=r.domain_id".
1328 " WHERE r.record_id=?";
1329 }
1330 } elsif ($idtype eq 'group') {
1331 $sql = "SELECT parent_group_id FROM groups WHERE group_id=?";
1332 } elsif ($idtype eq 'user') {
1333 $sql = "SELECT group_id FROM users WHERE user_id=?";
1334 } else {
1335 return "FOO", "BAR"; # can't get here.... we think.
1336 }
1337 my $sth = $dbh->prepare($sql);
1338 $sth->execute($id);
1339 my ($retid) = $sth->fetchrow_array;
1340 return $retid if $retid;
1341 # ahh! fall of the edge of the world if things went sideways
1342 ##fixme: really need to do a little more error handling, I think
1343} # end parentID()
Note: See TracBrowser for help on using the repository browser.