source: trunk/dns.cgi@ 62

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

/trunk

checkpoint
dns.cgi:

Fix lurking rebuglet on removing search filter
Add logging on domain active/inactive
Make sure to propagate error messages on domain add/delete as required
Logging of domain add/delete should now be complete
Record add/delete/update logging should be complete (not completely tested)
Explicitly set $startwith, $filter, and $searchsubs in listdomains()

DNSDB.pm:

Remove debugging cruft in DNSDB
Return the parent ID for a record in getRecLine
Normalize some SQL formatting

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