source: trunk/dns.cgi@ 139

Last change on this file since 139 was 139, checked in by Kris Deugau, 13 years ago

/trunk

Reduce the abuse of "actions" as a form input name; make the
domain and user list status changes use their own custom input
names to reduce the mixups when checking "global" actions

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 68.7 KB
Line 
1#!/usr/bin/perl -w -T
2# dns/cgi-bin/dns.cgi
3###
4# SVN revision info
5# $Date: 2011-10-07 20:01:55 +0000 (Fri, 07 Oct 2011) $
6# SVN revision $Rev: 139 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2008-2011 - 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 Digest::MD5 qw(md5_hex);
20use Net::DNS;
21use DBI;
22use Data::Dumper;
23
24#sub is_tainted {
25# # from perldoc perlsec
26# return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 };
27#}
28#use Cwd 'abs_path';
29#use File::Basename;
30#use lib dirname( abs_path $0 );
31#die "argh! tainted!" if is_tainted($0);
32#die "argh! \@INC got tainted!" if is_tainted(@INC);
33
34# custom modules
35use lib '.';
36use DNSDB qw(:ALL);
37
38my @debugbits; # temp, to be spit out near the end of processing
39my $debugenv = 1;
40
41# Let's do these templates right...
42my $templatedir = "templates";
43my $sessiondir = "session";
44
45# Set up the CGI object...
46my $q = new CGI::Simple;
47# ... and get query-string params as well as POST params if necessary
48$q->parse_query_string;
49
50# This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about...
51my %webvar = $q->Vars;
52
53# persistent stuff needed on most/all pages
54my $sid = ($webvar{sid} ? $webvar{sid} : undef);
55my $session = new CGI::Session("driver:File", $sid, {Directory => $sessiondir})
56 or die CGI::Session->errstr();
57#$sid = $session->id() if !$sid;
58if (!$sid) {
59 # init stuff. can probably axe this down to just above if'n'when user manipulation happens
60 $sid = $session->id();
61# need to know the "upper" group the user can deal with; may as well
62# stick this in the session rather than calling out to the DB every time.
63 $session->param('logingroup',1);
64 $session->param('curgroup',1); # yes, we *do* need to track this too. er, probably.
65 $session->param('domlistsortby','domain');
66 $session->param('domlistorder','ASC');
67 $session->param('useradminsortby','user');
68 $session->param('useradminorder','ASC');
69 $session->param('grpmansortby','group');
70 $session->param('grpmanorder','ASC');
71 $session->param('reclistsortby','host');
72 $session->param('reclistorder','ASC');
73# $session->param('filter','login');
74# $session->param('startwith','login');
75# $session->param('searchsubs','login');
76}
77
78# Just In Case. Stale sessions should not be resurrectable.
79if ($sid ne $session->id()) {
80 changepage(page=> "login", sessexpired => 1);
81}
82
83my $logingroup = ($session->param('logingroup') ? $session->param('logingroup') : 1);
84my $curgroup = ($session->param('curgroup') ? $session->param('curgroup') : $logingroup);
85my $group = ($webvar{group} ? $webvar{group} : 1);
86
87# per-page startwith, filter, searchsubs
88$session->param($webvar{page}.'startwith', $webvar{startwith}) if defined($webvar{startwith});
89$session->param($webvar{page}.'filter', $webvar{filter}) if defined($webvar{filter});
90$webvar{searchsubs} =~ s/^n ?// if $webvar{searchsubs};
91$session->param($webvar{page}.'searchsubs', $webvar{searchsubs}) if defined($webvar{searchsubs});
92
93# decide which page to spit out...
94# also set $webvar{page} before we try to use it.
95$webvar{page} = 'login' if !$webvar{page};
96
97my $startwith = $session->param($webvar{page}.'startwith');
98my $filter = $session->param($webvar{page}.'filter');
99my $searchsubs = $session->param($webvar{page}.'searchsubs');
100
101# nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet
102
103my $header = HTML::Template->new(filename => "$templatedir/header.tmpl");
104my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl");
105
106## set up "URL to self"
107# @#$%@%@#% XHTML - & in a URL must be escaped. >:(
108my $uri_self = $ENV{REQUEST_URI};
109$uri_self =~ s/\&([a-z])/\&amp\;$1/g;
110
111# le sigh. and we need to strip any previous action
112$uri_self =~ s/\&amp;action=[^&]+//g;
113
114# and search filter options. these get stored in the session, but discarded
115# as soon as you switch to a different page.
116##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits
117no warnings qw(uninitialized);
118$uri_self =~ s/\&amp;startwith=[a-z09-]*(\&)?/$1/g;
119$uri_self =~ s/\&amp;searchsubs=[a-z09-]*(\&)?/$1/g;
120$uri_self =~ s/\&amp;filter=[a-z09-]*(\&)?/$1/g;
121use warnings qw(uninitialized);
122
123# default
124#my $perpage = 15;
125my $perpage = 5;
126my $offset = ($webvar{offset} ? $webvar{offset} : 0);
127
128# NB: these must match the field name and SQL ascend/descend syntax respectively
129my $sortby = "domain";
130my $sortorder = "ASC";
131
132# now load some local system defaults (mainly DB connect info)
133# note this is not *absolutely* fatal, since there's a default dbname/user/pass in DNSDB.pm
134# we'll catch a bad DB connect string a little further down.
135if (!loadConfig()) {
136 warn "Using default configuration; unable to load custom settings: $DNSDB::errstr";
137}
138
139##fixme: quit throwing the database handle around, and put all the SQL and direct DB fiddling into DNSDB.pm
140# dbname, user, pass, host (optional)
141my ($dbh,$msg) = connectDB($config{dbname}, $config{dbuser}, $config{dbpass}, $config{dbhost});
142
143if (!$dbh) {
144 print "Content-type: text/html\n\n";
145 print $header->output;
146 my $errpage = HTML::Template->new(filename => "$templatedir/dberr.tmpl");
147 $errpage->param(errmsg => $msg);
148 print $errpage->output;
149 print $footer->output;
150 exit;
151}
152
153# Load config pieces from the database. Ideally all but the DB user/pass/etc should be loaded here.
154initGlobals($dbh);
155
156# handle login redirect
157if ($webvar{action}) {
158 if ($webvar{action} eq 'login') {
159 # Snag ACL/permissions here too
160 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
161 $sth->execute($webvar{username});
162 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
163 $webvar{loginfailed} = 1 if !defined($uid);
164
165 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
166 # native passwords (crypt-md5)
167 $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1);
168 } elsif ($pass =~ /^[0-9a-f]{32}$/) {
169 # VegaDNS import (hex-coded MD5)
170 $webvar{loginfailed} = 1 if $pass ne md5_hex($webvar{password});
171 } else {
172 # plaintext (convenient now and then)
173 $webvar{loginfailed} = 1 if $pass ne $webvar{password};
174 }
175
176 # set session bits
177 $session->param('logingroup',$gid);
178 $session->param('curgroup',$gid);
179 $session->param('uid',$uid);
180 $session->param('username',$webvar{username});
181
182 changepage(page => "domlist") if !defined($webvar{loginfailed});
183 } elsif ($webvar{action} eq 'logout') {
184 # delete the session
185 $session->delete();
186 $session->flush();
187
188 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}";
189 $newurl =~ s|/[^/]+$|/|;
190 print "Status: 302\nLocation: $newurl\n\n";
191 exit;
192
193 } elsif ($webvar{action} eq 'chgroup') {
194 # fiddle session-stored group data
195 # magic incantation to... uhhh...
196
197 # ... and the "change group" bits...
198 $uri_self =~ s/\&amp;group=[^&]*//g;
199
200 $session->param('curgroup', $webvar{group});
201 $curgroup = ($webvar{group} ? $webvar{group} : $session->param('curgroup'));
202 }
203} # handle global webvar{action}s
204
205initPermissions($dbh,$session->param('uid'));
206
207## Default page is a login page
208#my $page; # to be initialized as an HTML::Template entity sooner or later
209
210
211#if (!$webvar{page}) {
212# $page = HTML::Template->new(filename => "$templatedir/login.tmpl");
213#} else {
214#}
215
216my $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl");
217
218$page->param(sid => $sid);
219
220if ($webvar{page} eq 'login') {
221
222 $page->param(loginfailed => 1) if $webvar{loginfailed};
223##fixme: set up session init to actually *check* for session timeout
224 $page->param(timeout => 1) if $webvar{sesstimeout};
225
226} elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') {
227
228# hmm. seeing problems in some possibly-not-so-corner cases.
229# this currently only handles "domain on", "domain off"
230 if (defined($webvar{domstatus})) {
231 my $stat = domStatus($dbh,$webvar{id},$webvar{domstatus});
232 logaction($webvar{id}, $session->param("username"), parentID($webvar{id}, 'dom', 'group'),
233 "Changed ".domainName($dbh, $webvar{id})." state to ".($stat ? 'active' : 'inactive'));
234 }
235
236 $page->param(curpage => $webvar{page});
237 $page->param(errmsg => $webvar{errmsg}) if $webvar{errmsg};
238# if ($webvar{del_failed}) {
239# $page->param(del_failed => 1);
240# $page->param(errmsg => $webvar{errmsg});
241# }
242
243 listdomains();
244
245} elsif ($webvar{page} eq 'newdomain') {
246
247 changepage(page => "domlist", errmsg => "You are not permitted to add domains")
248 unless ($permissions{admin} || $permissions{domain_create});
249
250 fill_grouplist("grouplist");
251
252 if ($webvar{add_failed}) {
253 $page->param(add_failed => 1);
254 $page->param(errmsg => $webvar{errmsg});
255 $page->param(domain => $webvar{domain});
256 }
257
258} elsif ($webvar{page} eq 'adddomain') {
259
260 changepage(page => "domlist", errmsg => "You are not permitted to add domains")
261 unless ($permissions{admin} || $permissions{domain_create});
262
263 my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0));
264
265 if ($code eq 'OK') {
266 logaction($msg, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}");
267 changepage(page => "reclist", id => $msg);
268 } else {
269 logaction(0, $session->param("username"), $webvar{group}, "Failed adding domain $webvar{domain} ($msg)");
270 changepage(page => "newdomain", add_failed => 1, domain => $webvar{domain}, errmsg => $msg);
271 }
272
273} elsif ($webvar{page} eq 'deldom') {
274
275 changepage(page => "domlist", errmsg => "You are not permitted to delete domains")
276 unless ($permissions{admin} || $permissions{domain_delete});
277
278 $page->param(id => $webvar{id});
279
280 # first pass = confirm y/n (sorta)
281 if (!defined($webvar{del})) {
282
283 $page->param(del_getconf => 1);
284 $page->param(domain => domainName($dbh,$webvar{id}));
285
286 } elsif ($webvar{del} eq 'ok') {
287
288 my $pargroup = parentID($webvar{id}, 'dom', 'group');
289 my $dom = domainName($dbh, $webvar{id});
290 my ($code,$msg) = delDomain($dbh, $webvar{id});
291 if ($code ne 'OK') {
292# need to find failure mode
293 logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $dom ($msg)");
294 changepage(page => "domlist", errmsg => "Error deleting domain $dom: $msg");
295 } else {
296 logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $dom");
297 changepage(page => "domlist");
298 }
299
300 } else {
301 # cancelled. whee!
302 changepage(page => "domlist");
303 }
304
305} elsif ($webvar{page} eq 'reclist') {
306
307 $page->param(mayeditsoa => $permissions{admin} || $permissions{domain_edit});
308##fixme: ACL needs pondering. Does "edit domain" interact with record add/remove/etc?
309# Note this seems to be answered "no" in Vega.
310# ACLs
311 $page->param(record_create => ($permissions{admin} || $permissions{record_create}) );
312# $page->param(record_edit => ($permissions{admin} || $permissions{record_edit}) );
313 $page->param(record_delete => ($permissions{admin} || $permissions{record_delete}) );
314
315 # Handle record list for both default records (per-group) and live domain records
316
317 $page->param(defrec => $webvar{defrec});
318 $page->param(id => $webvar{id});
319 $page->param(curpage => $webvar{page});
320
321 my $count = getRecCount($dbh, $webvar{defrec}, $webvar{id}, $filter);
322
323 $sortby = 'host';
324# sort/order
325 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
326 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
327
328 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
329 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
330
331# set up the headers
332 my @cols = ('host', 'type', 'val', 'distance', 'weight', 'port', 'ttl');
333 my %colheads = (host => 'Name', type => 'Type', val => 'Address',
334 distance => 'Distance', weight => 'Weight', port => 'Port', ttl => 'TTL');
335 my %custom = (id => $webvar{id}, defrec => $webvar{defrec});
336 fill_colheads($sortby, $sortorder, \@cols, \%colheads, \%custom);
337
338# fill the page-count and first-previous-next-last-all details
339 fill_pgcount($count,"records",
340 ($webvar{defrec} eq 'y' ? "group ".groupName($dbh,$webvar{id}) : domainName($dbh,$webvar{id})));
341 fill_fpnla($count); # should put some params on this sub...
342
343 $page->param(defrec => $webvar{defrec});
344 if ($webvar{defrec} eq 'y') {
345 showdomain('y',$curgroup);
346 } else {
347 showdomain('n',$webvar{id});
348 $page->param(logdom => 1);
349 }
350
351 $page->param(errmsg => $webvar{errmsg}) if $webvar{errmsg};
352
353} elsif ($webvar{page} eq 'record') {
354
355 if ($webvar{recact} eq 'new') {
356
357 changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid})
358 unless ($permissions{admin} || $permissions{record_create});
359
360 $page->param(todo => "Add record");
361 $page->param(recact => "add");
362 $page->param(parentid => $webvar{parentid});
363 $page->param(defrec => $webvar{defrec});
364
365 fill_recdata();
366
367 } elsif ($webvar{recact} eq 'add') {
368
369 changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid})
370 unless ($permissions{admin} || $permissions{record_create});
371
372 my @recargs = ($dbh,$webvar{defrec},$webvar{parentid},$webvar{name},$webvar{type},$webvar{address},$webvar{ttl});
373 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) {
374 push @recargs, $webvar{distance};
375 if ($webvar{type} == $reverse_typemap{SRV}) {
376 push @recargs, $webvar{weight};
377 push @recargs, $webvar{port};
378 }
379 }
380
381 my ($code,$msg) = addRec(@recargs);
382
383 if ($code eq 'OK') {
384 if ($webvar{defrec} eq 'y') {
385 logaction(0, $session->param("username"), $webvar{parentid},
386 "Added default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
387 } else {
388 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'),
389 "Added record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
390 }
391 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
392 } else {
393 $page->param(failed => 1);
394 $page->param(errmsg => $msg);
395 $page->param(wastrying => "adding");
396 $page->param(todo => "Add record");
397 $page->param(recact => "add");
398 $page->param(parentid => $webvar{parentid});
399 $page->param(defrec => $webvar{defrec});
400 $page->param(id => $webvar{id});
401 fill_recdata(); # populate the form... er, mostly.
402 if ($webvar{defrec} eq 'y') {
403 logaction(0, $session->param("username"), $webvar{parentid},
404 "Failed adding default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)");
405 } else {
406 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'),
407 "Failed adding record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)");
408 }
409 }
410
411 } elsif ($webvar{recact} eq 'edit') {
412
413 changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid})
414 unless ($permissions{admin} || $permissions{record_edit});
415
416 $page->param(todo => "Update record");
417 $page->param(recact => "update");
418 $page->param(parentid => $webvar{parentid});
419 $page->param(id => $webvar{id});
420 $page->param(defrec => $webvar{defrec});
421 my $recdata = getRecLine($dbh, $webvar{defrec}, $webvar{id});
422 $page->param(name => $recdata->{host});
423 $page->param(address => $recdata->{val});
424 $page->param(distance => $recdata->{distance});
425 $page->param(weight => $recdata->{weight});
426 $page->param(port => $recdata->{port});
427 $page->param(ttl => $recdata->{ttl});
428 fill_rectypes($recdata->{type});
429
430 } elsif ($webvar{recact} eq 'update') {
431
432 changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid})
433 unless ($permissions{admin} || $permissions{record_edit});
434
435 my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{id},
436 $webvar{name},$webvar{type},$webvar{address},$webvar{ttl},
437 $webvar{distance},$webvar{weight},$webvar{port});
438
439 if ($code eq 'OK') {
440##fixme: need more magic to get proper group - if domain was fiddled
441# from search-subgroups listing, may not be "current" group
442
443# SELECT d.group_id FROM domains d INNER JOIN records r ON d.domain_id=r.domain_id WHERE r.record_id=?
444# $sth->execute($webvar{id});
445##log
446 if ($webvar{defrec} eq 'y') {
447 logaction(0, $session->param("username"), $webvar{parentid},
448 "Updated default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
449 } else {
450 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{id}, 'rec', 'group'),
451 "Updated record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
452 }
453 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
454 } else {
455 $page->param(failed => 1);
456 $page->param(errmsg => $msg);
457 $page->param(wastrying => "updating");
458 $page->param(todo => "Update record");
459 $page->param(recact => "update");
460 $page->param(parentid => $webvar{parentid});
461 $page->param(defrec => $webvar{defrec});
462 $page->param(id => $webvar{id});
463 fill_recdata();
464 if ($webvar{defrec} eq 'y') {
465 logaction(0, $session->param("username"), $webvar{parentid},
466 "Failed updating default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)");
467 } else {
468 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'),
469 "Failed updating record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)");
470 }
471 }
472 }
473
474 if ($webvar{defrec} eq 'y') {
475 $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid}));
476 } else {
477 $page->param(parentid => $webvar{parentid});
478 $page->param(dohere => domainName($dbh,$webvar{parentid}));
479 }
480
481} elsif ($webvar{page} eq 'delrec') {
482
483 # This is a complete separate segment since it uses a different template from add/edit records above
484
485 changepage(page => "reclist", errmsg => "You are not permitted to delete records", id => $webvar{parentid})
486 unless ($permissions{admin} || $permissions{record_delete});
487
488 $page->param(id => $webvar{id});
489 $page->param(defrec => $webvar{defrec});
490 $page->param(parentid => $webvar{parentid});
491 # first pass = confirm y/n (sorta)
492 if (!defined($webvar{del})) {
493 $page->param(del_getconf => 1);
494 my $rec = getRecLine($dbh,$webvar{defrec},$webvar{id});
495 $page->param(host => $rec->{host});
496 $page->param(ftype => $typemap{$rec->{type}});
497 $page->param(recval => $rec->{val});
498 } elsif ($webvar{del} eq 'ok') {
499# get rec data before we try to delete it
500 my $rec = getRecLine($dbh,$webvar{defrec},$webvar{id});
501 my ($code,$msg) = delRec($dbh,$webvar{defrec},$webvar{id});
502 if ($code ne 'OK') {
503## need to find failure mode
504 if ($webvar{defrec} eq 'y') {
505 logaction(0, $session->param("username"), $rec->{parid},
506 "Failed deleting default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}',".
507 " TTL $rec->{ttl} ($msg)");
508 } else {
509 logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'),
510 "Failed deleting record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl} ($msg)");
511 }
512 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
513 errmsg => "Error deleting record: $msg");
514# $page->param(del_failed => 1);
515# $page->param(errmsg => $msg);
516# showdomain($webvar{defrec}, $webvar{parentid});
517 } else {
518 if ($webvar{defrec} eq 'y') {
519 logaction(0, $session->param("username"), $rec->{parid},
520 "Deleted default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}");
521 } else {
522 logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'),
523 "Deleted record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}");
524 }
525 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
526 }
527 } else {
528 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
529 }
530
531} elsif ($webvar{page} eq 'editsoa') {
532
533 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
534 unless ($permissions{admin} || $permissions{domain_edit});
535
536 fillsoa($webvar{defrec},$webvar{id});
537
538} elsif ($webvar{page} eq 'updatesoa') {
539
540 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
541 unless ($permissions{admin} || $permissions{domain_edit});
542
543 my $sth;
544 my $sql = '';
545 # no domain ID, so we're editing the default SOA for a group (we don't care which one here)
546 # plus a bit of magic to update the appropriate table
547 $sql = "update ".($webvar{defrec} eq 'y' ? "default_records" : "records").
548 " set host='$webvar{prins}:$webvar{contact}',".
549 " val='$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}',".
550 " ttl=$webvar{ttl} where record_id=$webvar{recid}";
551 $sth = $dbh->prepare($sql);
552 $sth->execute;
553
554 if ($sth->err) {
555 $page->param(update_failed => 1);
556 $page->param(msg => $DBI::errstr);
557 fillsoa($webvar{defrec},$webvar{id});
558 } else {
559
560##fixme! need to set group ID properly here
561# SELECT group_id FROM domains WHERE domain_id=?
562# $sth->execute($webvar{id});
563##log
564 logaction(0, $session->param("username"), $webvar{group},
565 "Updated SOA (ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},".
566 " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl}");
567 changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec});
568# $page->param(update_failed => 0);
569# showdomain('y',1);
570 }
571
572} elsif ($webvar{page} eq 'grpman') {
573
574 listgroups();
575 $page->param(curpage => $webvar{page});
576
577} elsif ($webvar{page} eq 'newgrp') {
578
579 changepage(page => "grpman", errmsg => "You are not permitted to add groups", id => $webvar{parentid})
580 unless ($permissions{admin} || $permissions{group_add});
581
582 # do.. uhh.. stuff.. if we have no webvar{action}
583 if ($webvar{action} && $webvar{action} eq 'add') {
584 my %newperms;
585 foreach (@permtypes) {
586 $newperms{$_} = 0;
587 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
588 }
589 # not gonna provide the 4th param: template-or-clone flag, just yet
590 my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms);
591 if ($code eq 'OK') {
592 logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}");
593 changepage(page => "grpman");
594 }
595 # no point in doing extra work
596 fill_permissions($page, \%newperms);
597 $page->param(add_failed => 1);
598 $page->param(errmsg => $msg);
599 $page->param(newgroup => $webvar{newgroup});
600 fill_grouplist('pargroup',$webvar{pargroup});
601 } else {
602 fill_grouplist('pargroup',$curgroup);
603 # fill default permissions with immediate parent's current ones
604 my %parperms;
605 getPermissions($dbh, 'group', $curgroup, \%parperms);
606 fill_permissions($page, \%parperms);
607 }
608
609} elsif ($webvar{page} eq 'delgrp') {
610
611 changepage(page => "grpman", errmsg => "You are not permitted to delete groups", id => $webvar{parentid})
612 unless ($permissions{admin} || $permissions{group_delete});
613
614 $page->param(id => $webvar{id});
615 # first pass = confirm y/n (sorta)
616 if (!defined($webvar{del})) {
617 $page->param(del_getconf => 1);
618# $page->param(groupname => groupName($dbh,$webvar{id}));
619# print some neato things?
620
621# } else {
622# #whether actually deleting or cancelling we redirect to the group list, default format
623
624 } elsif ($webvar{del} eq 'ok') {
625 my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it...
626 my ($code,$msg) = delGroup($dbh, $webvar{id});
627 if ($code ne 'OK') {
628# need to find failure mode
629 logaction(0, $session->param("username"), $webvar{curgroup}, "Failure deleting group $deleteme: $msg");
630 changepage(page => "grpman", del_failed => 1, errmsg => $msg);
631 } else {
632##fixme: need to clean up log when deleting a major container
633 logaction(0, $session->param("username"), $webvar{curgroup}, "Deleted group $deleteme");
634 # success. go back to the domain list, do not pass "GO"
635 changepage(page => "grpman");
636 }
637 } else {
638 # cancelled. whee!
639 changepage(page => "grpman");
640 }
641 $page->param(delgroupname => groupName($dbh, $webvar{id}));
642
643} elsif ($webvar{page} eq 'edgroup') {
644
645 changepage(page => "grpman", errmsg => "You are not permitted to edit groups", id => $webvar{parentid})
646 unless ($permissions{admin} || $permissions{group_edit});
647
648 if ($webvar{action} eq 'updperms') {
649 # extra safety check; make sure user can't construct a URL to bypass ACLs
650 my %curperms;
651 getPermissions($dbh, 'group', $webvar{gid}, \%curperms);
652 my %chperms;
653 foreach (@permtypes) {
654 $webvar{$_} = 0 if !defined($webvar{$_});
655 $webvar{$_} = 1 if $webvar{$_} eq 'on';
656 $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_};
657 }
658 my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms);
659 if ($code eq 'OK') {
660 logaction(0, $session->param("username"), $webvar{gid}, "Changed default permissions in group $webvar{gid}");
661 changepage(page => "grpman");
662 }
663 # no point in doing extra work
664 fill_permissions($page, \%chperms);
665 $page->param(errmsg => $msg);
666 }
667 $page->param(gid => $webvar{gid});
668 $page->param(grpmeddle => groupName($dbh, $webvar{gid}));
669 my %grpperms;
670 getPermissions($dbh, 'group', $webvar{gid}, \%grpperms);
671 fill_permissions($page, \%grpperms);
672
673} elsif ($webvar{page} eq 'bulkdomain') {
674 # Bulk operations on domains. Note all but group move are available on the domain list.
675
676 changepage(page => "domlist", errmsg => "You are not permitted to make bulk domain changes")
677 unless ($permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
678
679 fill_grouplist("grouplist");
680
681##fixme
682##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
683##fixme
684
685##fixme: un-hardcode the limit?
686# $perpage = 50;
687
688 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
689 $sth->execute($curgroup);
690 my ($count) = ($sth->fetchrow_array);
691
692 $page->param(curpage => $webvar{page});
693 fill_pgcount($count,'domains',groupName($dbh,$curgroup));
694 fill_fpnla($count);
695 $page->param(offset => $offset); # since apparently this isn't set explicitly elsewhere. Who knew?
696 $page->param(perpage => $perpage);
697
698 my @domlist;
699 my $sql = "SELECT domain_id,domain FROM domains".
700 " WHERE group_id=?".
701 " ORDER BY domain".
702 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
703 $sth = $dbh->prepare($sql);
704 $sth->execute($curgroup);
705 my $rownum = 0;
706 while (my @data = $sth->fetchrow_array) {
707 my %row;
708 $row{domid} = $data[0];
709 $row{domain} = $data[1];
710 $rownum++; # putting this in the expression below causes failures. *eyeroll*
711 $row{newrow} = $rownum % 5 == 0;
712 push @domlist, \%row;
713 }
714 $page->param(domtable => \@domlist);
715 # ACLs
716 $page->param(maymove => ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete})));
717 $page->param(maystatus => $permissions{admin} || $permissions{domain_edit});
718 $page->param(maydelete => $permissions{admin} || $permissions{domain_delete});
719
720} elsif ($webvar{page} eq 'bulkchange') {
721
722 if ($webvar{action} eq 'move') {
723 changepage(page => "domlist", errmsg => "You are not permitted to bulk-move domains")
724 unless ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete}));
725 my $newgname = groupName($dbh,$webvar{destgroup});
726 $page->param(action => "Move to group $newgname");
727 my @bulkresults;
728 # nngh. due to alpha-sorting on the previous page, we can't use domid-numeric
729 # order here, and since we don't have the domain names until we go around this
730 # loop, we can't alpha-sort them here. :(
731 foreach (keys %webvar) {
732 my %row;
733 next unless $_ =~ /^dom_\d+$/;
734 $row{domain} = domainName($dbh,$webvar{$_});
735 my ($code, $msg) = changeGroup($dbh, 'domain', $webvar{$_}, $webvar{destgroup});
736 if ($code eq 'OK') {
737 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
738 "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname");
739 $row{domok} = ($code eq 'OK');
740 } else {
741 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
742 "Failure moving domain ".domainName($dbh, $webvar{$_})." to group $newgname: $msg");
743 }
744 $row{domerr} = $msg;
745 push @bulkresults, \%row;
746 }
747 $page->param(bulkresults => \@bulkresults);
748
749 } elsif ($webvar{action} eq 'deactivate' || $webvar{action} eq 'activate') {
750 changepage(page => "domlist", errmsg => "You are not permitted to bulk-$webvar{action} domains")
751 unless ($permissions{admin} || $permissions{domain_edit});
752 $page->param(action => "$webvar{action} domains");
753 my @bulkresults;
754 foreach (keys %webvar) {
755 my %row;
756 next unless $_ =~ /^dom_\d+$/;
757 $row{domain} = domainName($dbh,$webvar{$_});
758##fixme: error handling on status change
759 my $stat = domStatus($dbh,$webvar{$_},($webvar{action} eq 'activate' ? 'domon' : 'domoff'));
760 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
761 "Changed domain ".domainName($dbh, $webvar{$_})." state to ".($stat ? 'active' : 'inactive'));
762 $row{domok} = 1;
763# $row{domok} = ($code eq 'OK');
764# $row{domerr} = $msg;
765 push @bulkresults, \%row;
766 }
767 $page->param(bulkresults => \@bulkresults);
768
769 } elsif ($webvar{action} eq 'delete') {
770 changepage(page => "domlist", errmsg => "You are not permitted to bulk-delete domains")
771 unless ($permissions{admin} || $permissions{domain_delete});
772 $page->param(action => "$webvar{action} domains");
773 my @bulkresults;
774 foreach (keys %webvar) {
775 my %row;
776 next unless $_ =~ /^dom_\d+$/;
777 $row{domain} = domainName($dbh,$webvar{$_});
778 my $pargroup = parentID($webvar{$_}, 'dom', 'group');
779 my $dom = domainName($dbh, $webvar{$_});
780 my ($code, $msg) = delDomain($dbh, $webvar{$_});
781 if ($code eq 'OK') {
782 logaction($webvar{$_}, $session->param("username"), $pargroup, "Deleted domain $dom");
783 $row{domok} = ($code eq 'OK');
784 } else {
785 logaction($webvar{$_}, $session->param("username"), $pargroup, "Failure deleting domain $dom: $msg");
786 }
787 $row{domerr} = $msg;
788 push @bulkresults, \%row;
789 }
790 $page->param(bulkresults => \@bulkresults);
791
792 } # move/(de)activate/delete if()
793
794 # not going to handle the unknown $webvar{action} else; it should not be possible in normal
795 # operations, and anyone who meddles with the URL gets what they deserve.
796
797} elsif ($webvar{page} eq 'useradmin') {
798
799 if (defined($webvar{userstatus})) {
800 userStatus($dbh,$webvar{id},$webvar{userstatus});
801 }
802
803 $page->param(curpage => $webvar{page});
804
805 list_users();
806
807} elsif ($webvar{page} eq 'user') {
808
809 # All user add/edit actions fall through the same page, since there aren't
810 # really any hard differences between the templates
811
812 #fill_actypelist($webvar{accttype});
813 fill_clonemelist();
814 my %grpperms;
815 getPermissions($dbh, 'group', $curgroup, \%grpperms);
816
817 my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl");
818 my %noaccess;
819 fill_permissions($grppermlist, \%grpperms, \%noaccess);
820 $grppermlist->param(info => 1);
821 $page->param(grpperms => $grppermlist->output);
822
823 $page->param(is_admin => $permissions{admin});
824
825 $webvar{action} = '' if !$webvar{action};
826
827 if ($webvar{action} eq 'add' or $webvar{action} eq 'update') {
828
829 $page->param(add => 1) if $webvar{action} eq 'add';
830
831 my ($code,$msg);
832
833 my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits
834
835 my %newperms; # we're going to prefill the existing permissions, so we can change them.
836 getPermissions($dbh, 'user', $webvar{uid}, \%newperms);
837
838 if ($webvar{pass1} ne $webvar{pass2}) {
839 $code = 'FAIL';
840 $msg = "Passwords don't match";
841 } else {
842
843 # assemble a permission string - far simpler than trying to pass an
844 # indeterminate set of permission flags individually
845
846 # But first, we have to see if the user can add any particular
847 # permissions; otherwise we have a priviledge escalation. Whee.
848
849 if (!$permissions{admin}) {
850 my %grpperms;
851 getPermissions($dbh, 'group', $curgroup, \%grpperms);
852 my $ret = comparePermissions(\%permissions, \%grpperms);
853 if ($ret ne '<' && $ret ne '!') {
854 # User's permissions are not a superset or equivalent to group. Can't inherit
855 # (and include access user doesn't currently have), so we force custom.
856 $webvar{perms_type} = 'custom';
857 $alterperms = 1;
858 }
859 }
860
861 my $permstring;
862 if ($webvar{perms_type} eq 'custom') {
863 $permstring = 'C:';
864 foreach (@permtypes) {
865 if ($permissions{admin} || $permissions{$_}) {
866 $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on';
867 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
868 }
869 }
870 $page->param(perm_custom => 1);
871 } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') {
872 $permstring = "c:$webvar{clonesrc}";
873 getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms);
874 $page->param(perm_clone => 1);
875 } else {
876 $permstring = 'i';
877 }
878 if ($webvar{action} eq 'add') {
879 ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1},
880 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring,
881 $webvar{fname}, $webvar{lname}, $webvar{phone});
882 logaction(0, $session->param("username"), $curgroup, "Added user $webvar{uname} (uid $msg)")
883 if $code eq 'OK';
884 } else {
885# User update is icky. I'd really like to do this in one atomic
886# operation, but that would duplicate a **lot** of code in DNSDB.pm
887 # Allowing for changing group, but not coding web support just yet.
888 ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1},
889 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
890 $webvar{fname}, $webvar{lname}, $webvar{phone});
891 if ($code eq 'OK') {
892 $newperms{admin} = 1 if $webvar{accttype} eq 'S';
893 ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i'));
894 }
895 logaction(0, $session->param("username"), $curgroup,
896 "Updated uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})");
897 }
898 }
899
900 if ($code eq 'OK') {
901
902 if ($alterperms) {
903 changepage(page => "useradmin", warnmsg =>
904 "You can only grant permissions you hold. $webvar{uname} ".
905 ($webvar{action} eq 'add' ? 'added' : 'updated')." with reduced access.");
906 } else {
907 changepage(page => "useradmin");
908 }
909
910 # add/update failed:
911 } else {
912 $page->param(add_failed => 1);
913 $page->param(action => $webvar{action});
914 $page->param(set_permgroup => 1);
915 if ($webvar{perms_type} eq 'inherit') { # set permission class radio
916 $page->param(perm_inherit => 1);
917 } elsif ($webvar{perms_type} eq 'clone') {
918 $page->param(perm_clone => 1);
919 } else {
920 $page->param(perm_custom => 1);
921 }
922 $page->param(uname => $webvar{uname});
923 $page->param(fname => $webvar{fname});
924 $page->param(lname => $webvar{lname});
925 $page->param(pass1 => $webvar{pass1});
926 $page->param(pass2 => $webvar{pass2});
927 $page->param(errmsg => $msg);
928 fill_permissions($page, \%newperms);
929 fill_actypelist($webvar{accttype});
930 fill_clonemelist();
931##fixme: log
932 }
933
934 } elsif ($webvar{action} eq 'edit') {
935
936 $page->param(set_permgroup => 1);
937 $page->param(action => 'update');
938 $page->param(uid => $webvar{user});
939 fill_clonemelist();
940
941 my $userinfo = getUserData($dbh,$webvar{user});
942 fill_actypelist($userinfo->{type});
943 # not using this yet, but adding it now means we can *much* more easily do so later.
944 $page->param(gid => $webvar{group_id});
945
946 my %curperms;
947 getPermissions($dbh, 'user', $webvar{user}, \%curperms);
948 fill_permissions($page, \%curperms);
949
950 $page->param(uname => $userinfo->{username});
951 $page->param(fname => $userinfo->{firstname});
952 $page->param(lname => $userinfo->{lastname});
953 $page->param(set_permgroup => 1);
954 if ($userinfo->{inherit_perm}) {
955 $page->param(perm_inherit => 1);
956 } else {
957 $page->param(perm_custom => 1);
958 }
959##work
960# } elsif ($webvar{action} eq 'update') {
961 } else {
962 # default is "new"
963 $page->param(add => 1);
964 $page->param(action => 'add');
965 fill_permissions($page, \%grpperms);
966 fill_actypelist();
967 }
968
969} elsif ($webvar{page} eq 'newuser') {
970
971 # foo?
972 fill_actypelist();
973 fill_clonemelist();
974
975 my %grpperms;
976 getPermissions($dbh, 'group', $curgroup, \%grpperms);
977 fill_permissions($page, \%grpperms);
978
979 my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl");
980 my %noaccess;
981 fill_permissions($grppermlist, \%grpperms, \%noaccess);
982 $grppermlist->param(info => 1);
983 $page->param(grpperms => $grppermlist->output);
984
985#} elsif ($webvar{page} eq 'adduser') {
986#
987# my ($code,$msg);
988#
989# if ($webvar{pass1} ne $webvar{pass2}) {
990# $code = 'FAIL';
991# $msg = "Passwords don't match";
992# } else {
993## assemble a permission string - far simpler than trying to pass an
994## indeterminate set of permission flags individually
995#my $permstring;
996#if ($webvar{perms_type} eq 'custom') {
997# $permstring = 'C:,g:,u:,d:,r:';
998# $page->param(perm_custom => 1);
999#} elsif ($webvar{perms_type} eq 'clone') {
1000# $permstring = 'c:';
1001# $page->param(perm_clone => 1);
1002#} else {
1003# $permstring = 'i';
1004## $page->param(perm_inherit => 1);
1005#}
1006# ($code,$msg) = addUser($dbh,$webvar{uname}, $webvar{group}, $webvar{pass1},
1007# ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
1008# $webvar{fname}, $webvar{lname}, $webvar{phone});
1009# }
1010#
1011## hokay, a bit of magic to decide which page we hit.
1012# if ($code eq 'OK') {
1013###log
1014# logaction(0, $session->param("username"), $webvar{group},
1015# "Added user $webvar{uname} ($webvar{fname} $webvar{lname})");
1016# changepage(page => "useradmin");
1017# } else {
1018## oddity - apparently, xhtml 1.0 strict swallows username as an HTML::Template var. O_o
1019# $page->param(add_failed => 1);
1020# $page->param(uname => $webvar{uname});
1021# $page->param(fname => $webvar{fname});
1022# $page->param(lname => $webvar{lname});
1023# $page->param(pass1 => $webvar{pass1});
1024# $page->param(pass2 => $webvar{pass2});
1025# $page->param(errmsg => $msg);
1026# fill_actypelist($webvar{accttype});
1027# fill_clonemelist();
1028# }
1029#
1030## $page->param(add_failed => 1);
1031#
1032
1033} elsif ($webvar{page} eq 'deluser') {
1034
1035 $page->param(id => $webvar{id});
1036 # first pass = confirm y/n (sorta)
1037 if (!defined($webvar{del})) {
1038 $page->param(del_getconf => 1);
1039 $page->param(user => userFullName($dbh,$webvar{id}));
1040 } elsif ($webvar{del} eq 'ok') {
1041##fixme: find group id user is in (for logging) *before* we delete the user
1042##fixme: get other user data too for log
1043 my $userref = getUserData($dbh, $webvar{id});
1044 my ($code,$msg) = delUser($dbh, $webvar{id});
1045 if ($code ne 'OK') {
1046# need to find failure mode
1047 $page->param(del_failed => 1);
1048 $page->param(errmsg => $msg);
1049 list_users($curgroup);
1050 } else {
1051 # success. go back to the user list, do not pass "GO"
1052 # actions on users have a domain id of 0, always
1053 logaction(0, $session->param("username"), $curgroup, "Deleted user $webvar{id}/".$userref->{username}.
1054 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1055 changepage(page => "useradmin");
1056 }
1057 } else {
1058 # cancelled. whee!
1059 changepage(page => "useradmin");
1060 }
1061
1062#} elsif ($webvar{page} eq 'edituser') {
1063
1064} elsif ($webvar{page} eq 'dnsq') {
1065
1066 $page->param(qfor => $webvar{qfor}) if $webvar{qfor};
1067 fill_rectypes($webvar{type} ? $webvar{type} : '', 1);
1068 $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse};
1069 $page->param(resolver => $webvar{resolver}) if $webvar{resolver};
1070
1071 if ($webvar{qfor}) {
1072 my $resolv = Net::DNS::Resolver->new;
1073 $resolv->tcp_timeout(5); # make me adjustable!
1074 $resolv->udp_timeout(5); # make me adjustable!
1075 $resolv->recurse(0) if $webvar{nrecurse};
1076 $resolv->nameservers($webvar{resolver}) if $webvar{resolver};
1077 my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}});
1078 if ($query) {
1079
1080 $page->param(showresults => 1);
1081
1082 my @answer;
1083 foreach my $rr ($query->answer) {
1084# next unless $rr->type eq "A" or $rr->type eq 'NS';
1085 my %row;
1086 my ($host,$ttl,$class,$type,$data) =
1087 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s);
1088 $row{host} = $host;
1089 $row{ftype} = $type;
1090 $row{rdata} = ($type eq 'SOA' ? "<pre>$data</pre>" : $data);
1091 push @answer, \%row;
1092 }
1093 $page->param(answer => \@answer);
1094
1095 my @additional;
1096 foreach my $rr ($query->additional) {
1097# next unless $rr->type eq "A" or $rr->type eq 'NS';
1098 my %row;
1099 my ($host,$ttl,$class,$type,$data) =
1100 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1101 $row{host} = $host;
1102 $row{ftype} = $type;
1103 $row{rdata} = $data;
1104 push @additional, \%row;
1105 }
1106 $page->param(additional => \@additional);
1107
1108 my @authority;
1109 foreach my $rr ($query->authority) {
1110# next unless $rr->type eq "A" or $rr->type eq 'NS';
1111 my %row;
1112 my ($host,$ttl,$class,$type,$data) =
1113 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1114 $row{host} = $host;
1115 $row{ftype} = $type;
1116 $row{rdata} = $data;
1117 push @authority, \%row;
1118 }
1119 $page->param(authority => \@authority);
1120
1121 $page->param(usedresolver => $resolv->answerfrom);
1122 $page->param(frtype => $typemap{$webvar{type}});
1123
1124 } else {
1125 $page->param(errmsg => $resolv->errorstring);
1126 }
1127 }
1128 ## done DNS query
1129
1130} elsif ($webvar{page} eq 'axfr') {
1131
1132 changepage(page => "domlist", errmsg => "You are not permitted to import domains")
1133 unless ($permissions{admin} || $permissions{domain_create});
1134
1135 # don't need this while we've got the dropdown in the menu. hmm.
1136 fill_grouplist("grouplist");
1137
1138 $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom};
1139 $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa};
1140 $page->param(rwns => $webvar{rwns}) if $webvar{rwns};
1141 $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww.
1142 $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms};
1143
1144 # shut up warning about uninitialized variable
1145 $webvar{doit} = '' if !defined($webvar{doit});
1146
1147 if ($webvar{doit} eq 'y' && !$webvar{ifrom}) {
1148 $page->param(errmsg => "Need to set host to import from");
1149 } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) {
1150 $page->param(errmsg => "Need domains to import");
1151 } elsif ($webvar{doit} eq 'y') {
1152 my @domlist = split /\s+/, $webvar{importdoms};
1153 my @results;
1154 foreach my $domain (@domlist) {
1155 my %row;
1156 my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group},
1157 $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns});
1158 $row{domok} = $msg if $code eq 'OK';
1159 if ($code eq 'WARN') {
1160 $msg =~ s|\n|<br />|g;
1161 $row{domwarn} = $msg;
1162 }
1163 if ($code eq 'FAIL') {
1164 $msg =~ s|\n|<br />\n|g;
1165 $row{domerr} = $msg;
1166 }
1167 $msg = "<br />\n".$msg if $msg =~ m|<br />|;
1168 logaction(domainID($dbh, $domain), $session->param("username"), $webvar{group},
1169 "AXFR import $domain from $webvar{ifrom} ($code): $msg");
1170 $row{domain} = $domain;
1171 push @results, \%row;
1172 }
1173 $page->param(axfrresults => \@results);
1174 }
1175
1176} elsif ($webvar{page} eq 'whoisq') {
1177
1178 if ($webvar{qfor}) {
1179 use Net::Whois::Raw;
1180 use Text::Wrap;
1181
1182# caching useful?
1183#$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/";
1184#$Net::Whois::Raw::CACHE_TIME = 60;
1185
1186 my ($dominfo, $whois_server) = whois($webvar{qfor});
1187##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data
1188
1189 # le sigh. idjits spit out data without linefeeds...
1190 $Text::Wrap::columns = 88;
1191
1192# &%$@%@# high-bit crap. We should probably find a way to properly recode these
1193# instead of one-by-one. Note CGI::Simple's escapeHTML() doesn't do more than
1194# the bare minimum. :/
1195# Mainly an XHTML validation thing.
1196 $dominfo = $q->escapeHTML($dominfo);
1197 $dominfo =~ s/\xa9/\&copy;/g;
1198 $dominfo =~ s/\xae/\&reg;/g;
1199
1200 $page->param(qfor => $webvar{qfor});
1201 $page->param(dominfo => wrap('','',$dominfo));
1202 $page->param(whois_server => $whois_server);
1203 } else {
1204 $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway};
1205 }
1206
1207} elsif ($webvar{page} eq 'log') {
1208
1209##fixme put in some real log-munching stuff
1210##fixme need to add bits to *create* log entries...
1211 my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE ";
1212 my $id = $curgroup; # we do this because the group log may be called from (almost) any page,
1213 # but the others are much more limited. this is probably non-optimal.
1214 if ($webvar{ltype} && $webvar{ltype} eq 'user') {
1215 $sql .= "user_id=?";
1216 $id = $webvar{id};
1217 $page->param(logfor => 'user '.userFullName($dbh,$id));
1218 } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') {
1219 $sql .= "domain_id=?";
1220 $id = $webvar{id};
1221 $page->param(logfor => 'domain '.domainName($dbh,$id));
1222 } else {
1223 # Default to listing curgroup log
1224 $sql .= "group_id=?";
1225 $page->param(logfor => 'group '.groupName($dbh,$id));
1226 }
1227 my $sth = $dbh->prepare($sql);
1228 $sth->execute($id);
1229 my @logbits;
1230 while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) {
1231 my %row;
1232 $row{userfname} = $name;
1233 $row{userid} = $uid;
1234 $row{useremail} = $email;
1235 $row{logentry} = $entry;
1236 ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/);
1237 push @logbits, \%row;
1238 }
1239 $page->param(logentries => \@logbits);
1240
1241} # end $webvar{page} dance
1242
1243
1244# start output here so we can redirect pages.
1245print "Content-type: text/html\n\n", $header->output;
1246
1247##common bits
1248if ($webvar{page} ne 'login') {
1249 $page->param(username => $session->param("username"));
1250
1251 $page->param(group => $curgroup);
1252 $page->param(groupname => groupName($dbh,$curgroup));
1253 $page->param(logingrp => groupName($dbh,$logingroup));
1254 $page->param(logingrp_num => $logingroup);
1255
1256 $page->param(mayimport => $permissions{admin} || $permissions{domain_create});
1257 $page->param(maybulk => $permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
1258
1259 # group tree. should go elsewhere, probably
1260 my $tmpgrplist = fill_grptree($logingroup,$curgroup);
1261 $page->param(grptree => $tmpgrplist);
1262 $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean
1263 $page->param(inlogingrp => $curgroup == $logingroup);
1264
1265# fill in the URL-to-self
1266 $page->param(whereami => $uri_self);
1267}
1268
1269print "<pre>\n";
1270foreach (@debugbits) { print; }
1271print "</pre>\n";
1272
1273# spit it out
1274print $page->output;
1275
1276if ($debugenv) {
1277 print "<div id=\"debug\">webvar keys: <pre>\n";
1278 foreach my $key (keys %webvar) {
1279 print "key: $key\tval: $webvar{$key}\n";
1280 }
1281 print "</pre>\nsession:\n<pre>\n";
1282 my $sesdata = $session->dataref();
1283 foreach my $key (keys %$sesdata) {
1284 print "key: $key\tval: ".$sesdata->{$key}."\n";
1285 }
1286 print "</pre>\nENV:\n<pre>\n";
1287 foreach my $key (keys %ENV) {
1288 print "key: $key\tval: $ENV{$key}\n";
1289 }
1290 print "</pre></div>\n";
1291}
1292
1293print $footer->output;
1294
1295# as per the docs, Just In Case
1296$session->flush();
1297
1298exit 0;
1299
1300
1301sub fill_grptree {
1302 my $root = shift;
1303 my $cur = shift;
1304 my $indent = shift || ' ';
1305
1306 my @childlist;
1307
1308 my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl');
1309 getChildren($dbh,$root,\@childlist,'immediate');
1310 return if $#childlist == -1;
1311 my @grouplist;
1312 foreach (@childlist) {
1313 my %row;
1314 $row{grpname} = groupName($dbh,$_);
1315 $row{grpnum} = $_;
1316 $row{whereami} = $uri_self;
1317 # for all that HTML::Template is supposed to keep the HTML out of the Perl, this is so much more compact...
1318# $row{grpdisp} = ($_ == $cur ? "<b>$row{grpname}</b>" : $row{grpname});
1319$row{curgrp} = ($_ == $cur);
1320$row{expanded} = isParent($dbh, $_, 'group', $cur, 'group');
1321$row{expanded} = 1 if $_ == $cur;
1322 $row{subs} = fill_grptree($_,$cur,$indent.' ');
1323 $row{indent} = $indent;
1324 push @grouplist, \%row;
1325 }
1326 $grptree->param(indent => $indent);
1327 $grptree->param(treelvl => \@grouplist);
1328 return $grptree->output;
1329}
1330
1331sub changepage {
1332 my %params = @_; # think this works the way I want...
1333
1334 # handle user check
1335 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid";
1336 foreach (keys %params) {
1337 $newurl .= "&$_=".$q->url_encode($params{$_});
1338 }
1339
1340 # Just In Case
1341 $session->flush();
1342
1343 print "Status: 302\nLocation: $newurl\n\n";
1344 exit;
1345} # end changepage
1346
1347sub fillsoa {
1348 my $def = shift;
1349 my $id = shift;
1350 my $domname = ($def eq 'y' ? '' : "DOMAIN");
1351
1352 $page->param(defrec => $def);
1353
1354# i had a good reason to do this when I wrote it...
1355# $page->param(domain => $domname);
1356# $page->param(group => $DNSDB::group);
1357 $page->param(isgrp => 1) if $def eq 'y';
1358 $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) );
1359
1360# defaults
1361 $page->param(defcontact => $DNSDB::def{contact});
1362 $page->param(defns => $DNSDB::def{prins});
1363 $page->param(defsoattl => $DNSDB::def{soattl});
1364 $page->param(defrefresh => $DNSDB::def{refresh});
1365 $page->param(defretry => $DNSDB::def{retry});
1366 $page->param(defexpire => $DNSDB::def{expire});
1367 $page->param(defminttl => $DNSDB::def{minttl});
1368
1369 # there are probably better ways to do this. TMTOWTDI.
1370 my %soa = getSOA($dbh,$def,$id);
1371
1372 $page->param(id => $id);
1373 $page->param(recid => $soa{recid});
1374 $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins}));
1375 $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact}));
1376 $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh}));
1377 $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry}));
1378 $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire}));
1379 $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl}));
1380 $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl}));
1381}
1382
1383sub showdomain {
1384 my $def = shift;
1385 my $id = shift;
1386
1387 # get the SOA first
1388 my %soa = getSOA($dbh,$def,$id);
1389
1390 $page->param(recid => $soa{recid});
1391 $page->param(contact => $soa{contact});
1392 $page->param(prins => $soa{prins});
1393 $page->param(refresh => $soa{refresh});
1394 $page->param(retry => $soa{retry});
1395 $page->param(expire => $soa{expire});
1396 $page->param(minttl => $soa{minttl});
1397 $page->param(ttl => $soa{ttl});
1398
1399# $startwith = $session->param($webvar{page}.'startwith');
1400# $filter = $session->param($webvar{page}.'filter');
1401
1402 my $foo2 = getDomRecs($dbh,$def,$id,$perpage,$webvar{offset},$sortby,$sortorder,$filter);
1403
1404 my $row = 0;
1405 foreach my $rec (@$foo2) {
1406 $rec->{type} = $typemap{$rec->{type}};
1407 $rec->{row} = $row % 2;
1408 $rec->{defrec} = $def;
1409 $rec->{sid} = $webvar{sid};
1410 $rec->{id} = $id;
1411 $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV');
1412 $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV');
1413 $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV');
1414 $row++;
1415# ACLs
1416 $rec->{record_edit} = ($permissions{admin} || $permissions{record_edit});
1417 $rec->{record_delete} = ($permissions{admin} || $permissions{record_delete});
1418 }
1419 $page->param(reclist => $foo2);
1420}
1421
1422# fill in record type list on add/update/edit record template
1423sub fill_rectypes {
1424 my $type = shift || $reverse_typemap{A};
1425 my $soaflag = shift || 0;
1426
1427 my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder");
1428 $sth->execute;
1429 my @typelist;
1430 while (my ($rval,$rname) = $sth->fetchrow_array()) {
1431 my %row = ( recval => $rval, recname => $rname );
1432 $row{tselect} = 1 if $rval == $type;
1433 push @typelist, \%row;
1434 }
1435 if ($soaflag) {
1436 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
1437 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
1438 push @typelist, \%row;
1439 }
1440 $page->param(typelist => \@typelist);
1441} # fill_rectypes
1442
1443sub fill_recdata {
1444 fill_rectypes($webvar{type});
1445
1446# le sigh. we may get called with many empty %webvar keys
1447 no warnings qw( uninitialized );
1448
1449##todo: allow BIND-style bare names, ASS-U-ME that the name is within the domain?
1450# prefill <domain> or DOMAIN in "Host" space for new records
1451 my $domroot = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid}));
1452 $page->param(name => $domroot);
1453 $page->param(address => $webvar{address});
1454 $page->param(distance => $webvar{distance})
1455 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV});
1456 $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV};
1457 $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV};
1458# retrieve the right ttl instead of falling (way) back to the hardcoded system default
1459 my %soa = getSOA($dbh,$webvar{defrec},$webvar{parentid});
1460 $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $soa{minttl}));
1461}
1462
1463sub fill_actypelist {
1464 my $curtype = shift || 'u';
1465
1466 my @actypes;
1467
1468 my %row1 = (actypeval => 'u', actypename => 'user');
1469 $row1{typesel} = 1 if $curtype eq 'u';
1470 push @actypes, \%row1;
1471
1472 my %row2 = (actypeval => 'S', actypename => 'superuser');
1473 $row2{typesel} = 1 if $curtype eq 'S';
1474 push @actypes, \%row2;
1475
1476 $page->param(actypelist => \@actypes);
1477}
1478
1479sub fill_clonemelist {
1480 my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup");
1481 $sth->execute;
1482
1483 # shut up some warnings, but don't stomp on caller's state
1484 local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc});
1485
1486 my @clonesrc;
1487 while (my ($username,$uid) = $sth->fetchrow_array) {
1488 my %row = (
1489 username => $username,
1490 uid => $uid,
1491 selected => ($webvar{clonesrc} == $uid ? 1 : 0)
1492 );
1493 push @clonesrc, \%row;
1494 }
1495 $page->param(clonesrc => \@clonesrc);
1496}
1497
1498sub fill_fpnla {
1499 my $count = shift;
1500 if ($offset eq 'all') {
1501 $page->param(perpage => $perpage);
1502# uhm....
1503 } else {
1504 # all these bits only have sensible behaviour if offset is numeric. err, probably.
1505 if ($count > $perpage) {
1506 # if there are more results than the default, always show the "all" link
1507 $page->param(navall => 1);
1508
1509 if ($offset > 0) {
1510 $page->param(navfirst => 1);
1511 $page->param(navprev => 1);
1512 $page->param(prevoffs => $offset-1);
1513 }
1514
1515 # show "next" and "last" links if we're not on the last page of results
1516 if ( (($offset+1) * $perpage - $count) < 0 ) {
1517 $page->param(navnext => 1);
1518 $page->param(nextoffs => $offset+1);
1519 $page->param(navlast => 1);
1520 $page->param(lastoffs => int (($count-1)/$perpage));
1521 }
1522 } else {
1523 $page->param(onepage => 1);
1524 }
1525 }
1526} # end fill_fpnla()
1527
1528sub fill_pgcount {
1529 my $pgcount = shift;
1530 my $pgtype = shift;
1531 my $parent = shift;
1532
1533 # Fix display/UI bug where if you are not on the first page of the list, and
1534 # you add a search term or click one of the "starts with" links, you end up
1535 # on a page showing nothing.
1536 # For bonus points, this reverts to the original offset on clicking the "All" link (mostly)
1537 if ($offset ne 'all') {
1538 $offset-- while ($offset * $perpage) >= $pgcount;
1539 }
1540
1541 $page->param(ntot => $pgcount);
1542 $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1));
1543 $page->param(npglast => ($offset eq 'all' ? $pgcount :
1544 ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) )
1545 ));
1546 $page->param(pgtype => $pgtype);
1547 $page->param(parent => $parent);
1548 $page->param(filter => $filter);
1549} # end fill_pgcount()
1550
1551sub listdomains {
1552
1553# $startwith = $session->param($webvar{page}.'startwith');
1554# $filter = $session->param($webvar{page}.'filter');
1555 $searchsubs = $session->param($webvar{page}.'searchsubs');
1556
1557# ACLs
1558 $page->param(domain_create => ($permissions{admin} || $permissions{domain_create}) );
1559 $page->param(domain_edit => ($permissions{admin} || $permissions{domain_edit}) );
1560 $page->param(domain_delete => ($permissions{admin} || $permissions{domain_delete}) );
1561
1562##fixme: $logingroup or $curgroup?
1563 my @childgroups;
1564 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1565 my $childlist = join(',',@childgroups);
1566
1567 my $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1568 ($startwith ? " AND domain ~* '^[$startwith]'" : '').
1569 ($filter ? " AND domain ~* '$filter'" : '');
1570 my $sth = $dbh->prepare($sql);
1571 $sth->execute;
1572 my ($count) = $sth->fetchrow_array;
1573
1574# fill page count and first-previous-next-last-all bits
1575 fill_pgcount($count,"domains",groupName($dbh,$curgroup));
1576 fill_fpnla($count);
1577
1578# sort/order
1579 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1580 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1581
1582 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1583 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1584
1585# set up the headers
1586 my @cols = ('domain', 'status', 'group');
1587 my %colheads = (domain => 'Domain', status => 'Status', group => 'Group');
1588 fill_colheads($sortby, $sortorder, \@cols, \%colheads);
1589
1590# $page->param(sortorder => $sortorder);
1591 # hack! hack! pthbttt. have to rethink the status column storage,
1592 # or inactive comes "before" active. *sigh*
1593 $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status';
1594
1595# waffle, waffle - keep state on these as well as sortby, sortorder?
1596 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1597
1598 $page->param(filter => $filter) if $filter;
1599 $page->param(searchsubs => $searchsubs) if $searchsubs;
1600
1601##fixme
1602##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
1603##fixme
1604
1605 $page->param(group => $curgroup);
1606 my @domlist;
1607 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1608 " INNER JOIN groups ON domains.group_id=groups.group_id".
1609 " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1610##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1611 ($startwith ? " AND domain ~* '^[$startwith]'" : '').
1612 ($filter ? " AND domain ~* '$filter'" : '').
1613 " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $sortby).
1614 " $sortorder ".($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1615 $sth = $dbh->prepare($sql);
1616 $sth->execute;
1617 my $rownum = 0;
1618 while (my @data = $sth->fetchrow_array) {
1619 my %row;
1620 $row{domainid} = $data[0];
1621 $row{domain} = $data[1];
1622 $row{status} = ($data[2] ? 'Active' : 'Inactive');
1623 $row{group} = $data[3];
1624 $row{bg} = ($rownum++)%2;
1625# $row{mkactive} = ($data[2] eq 'inactive' ? 1 : 0);
1626 $row{mkactive} = !$data[2];
1627 $row{sid} = $sid;
1628 $row{offset} = $offset;
1629# ACLs
1630 $row{domain_edit} = ($permissions{admin} || $permissions{domain_edit});
1631 $row{domain_delete} = ($permissions{admin} || $permissions{domain_delete});
1632##fixme: need to clean up status indicator/usage/inversion
1633 push @domlist, \%row;
1634 }
1635 $page->param(domtable => \@domlist);
1636} # end listdomains()
1637
1638
1639sub listgroups {
1640
1641 my @childgroups;
1642 getChildren($dbh, $logingroup, \@childgroups, 'all') if $searchsubs;
1643 my $childlist = join(',',@childgroups);
1644
1645 my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
1646 ($startwith ? " AND group_name ~* '^[$startwith]'" : '').
1647 ($filter ? " AND group_name ~* '$filter'" : '');
1648 my $sth = $dbh->prepare($sql);
1649
1650 $sth->execute;
1651 my ($count) = ($sth->fetchrow_array);
1652# fill page count and first-previous-next-last-all bits
1653##fixme - hardcoded group bit
1654 fill_pgcount($count,"groups",'');
1655 fill_fpnla($count);
1656
1657 $page->param(gid => $curgroup);
1658
1659 $sortby = 'group';
1660# sort/order
1661 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1662 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1663
1664 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1665 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1666
1667# set up the headers
1668 my @cols = ('group','parent','nusers','ndomains');
1669 my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains');
1670 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1671
1672# waffle, waffle - keep state on these as well as sortby, sortorder?
1673 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1674
1675 $page->param(filter => $filter) if $filter;
1676 $page->param(searchsubs => $searchsubs) if $searchsubs;
1677
1678# munge sortby for columns in database
1679 $sortby = 'g.group_name' if $sortby eq 'group';
1680 $sortby = 'g2.group_name' if $sortby eq 'parent';
1681
1682 my @grouplist;
1683 $sth = $dbh->prepare("SELECT g.group_id, g.group_name, g2.group_name, ".
1684 "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ".
1685 "FROM groups g ".
1686 "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ".
1687 "LEFT OUTER JOIN users u ON u.group_id=g.group_id ".
1688 "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ".
1689 "WHERE g.parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').") ".
1690##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1691 ($startwith ? " AND g.group_name ~* '^[$startwith]'" : '').
1692 ($filter ? " AND g.group_name ~* '$filter'" : '').
1693 " GROUP BY g.group_id, g.group_name, g2.group_name ".
1694 " ORDER BY $sortby $sortorder ".
1695 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage));
1696 $sth->execute;
1697
1698 my $rownum = 0;
1699 while (my @data = $sth->fetchrow_array) {
1700 my %row;
1701 $row{groupid} = $data[0];
1702 $row{groupname} = $data[1];
1703 $row{pgroup} = $data[2];
1704 $row{nusers} = $data[3];
1705 $row{ndomains} = $data[4];
1706 $row{bg} = ($rownum++)%2;
1707 $row{sid} = $sid;
1708 push @grouplist, \%row;
1709 }
1710 $page->param(grouptable => \@grouplist);
1711} # end listgroups()
1712
1713
1714sub fill_grouplist {
1715 my $template_var = shift;
1716 my $cur = shift || $curgroup;
1717
1718 my @childgroups;
1719 getChildren($dbh, $logingroup, \@childgroups, 'all');
1720 my $childlist = join(',',@childgroups);
1721
1722##fixme: need to reorder list so that we can display a pseudotree in group dropdowns
1723
1724 # weesa gonna discard parent_group_id for now
1725 my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ".
1726 "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
1727 "ORDER BY group_id");
1728 $sth->execute;
1729 my @grouplist;
1730 while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) {
1731 my %row;
1732 $row{groupname} = $groupname;
1733 $row{groupval} = $groupid;
1734##fixme: need magic
1735## ... WTF?
1736# $row{defgroup} = '';
1737 $row{groupactive} = 1 if $groupid == $cur;
1738 push @grouplist, \%row;
1739 }
1740
1741 $page->param("$template_var" => \@grouplist);
1742
1743} # end fill_grouplist()
1744
1745
1746sub list_users {
1747
1748 my @childgroups;
1749 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1750 my $childlist = join(',',@childgroups);
1751
1752 my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1753 ($startwith ? " AND username ~* '^[$startwith]'" : '').
1754 ($filter ? " AND username ~* '$filter'" : '');
1755 my $sth = $dbh->prepare($sql);
1756 $sth->execute;
1757 my ($count) = ($sth->fetchrow_array);
1758
1759# fill page count and first-previous-next-last-all bits
1760##fixme - hardcoded group bit
1761 fill_pgcount($count,"users",'');
1762 fill_fpnla($count);
1763
1764 $sortby = 'user';
1765# sort/order
1766 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1767 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1768
1769 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1770 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1771
1772# set up the headers
1773 my @cols = ('user','fname','type','group','status');
1774 my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status');
1775 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1776
1777# waffle, waffle - keep state on these as well as sortby, sortorder?
1778 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1779
1780 $page->param(filter => $filter) if $filter;
1781 $page->param(searchsubs => $searchsubs) if $searchsubs;
1782
1783# munge sortby for columns in database
1784 $sortby = 'u.username' if $sortby eq 'user';
1785 $sortby = 'u.type' if $sortby eq 'type';
1786 $sortby = 'g.group_name' if $sortby eq 'group';
1787 $sortby = 'u.status' if $sortby eq 'status';
1788
1789 my @userlist;
1790 $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
1791 "FROM users u ".
1792 "INNER JOIN groups g ON u.group_id=g.group_id ".
1793 "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1794##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1795 ($startwith ? " AND u.username ~* '^[$startwith]'" : '').
1796 ($filter ? " AND u.username ~* '$filter'" : '').
1797 " ORDER BY $sortby $sortorder ".
1798 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1799
1800 $sth = $dbh->prepare($sql);
1801 $sth->execute;
1802
1803 my $rownum = 0;
1804 while (my @data = $sth->fetchrow_array) {
1805 no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name
1806 my %row;
1807 $row{userid} = $data[0];
1808 $row{username} = $data[1];
1809 $row{userfull} = $data[2];
1810 $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user");
1811 $row{usergroup} = $data[4];
1812 $row{active} = $data[5];
1813 $row{bg} = ($rownum++)%2;
1814 $row{sid} = $sid;
1815 push @userlist, \%row;
1816 }
1817 $page->param(usertable => \@userlist);
1818} # end list_users()
1819
1820
1821# Generate all of the glop necessary to add or not the appropriate marker/flag for
1822# the sort order and column in domain, user, group, and record lists
1823# Takes an array ref and hash ref
1824sub fill_colheads {
1825 my $sortby = shift;
1826 my $sortorder = shift;
1827 my $cols = shift;
1828 my $colnames = shift;
1829 my $custom = shift;
1830
1831 my @headings;
1832
1833 foreach my $col (@$cols) {
1834 my %coldata;
1835 $coldata{firstcol} = 1 if $col eq $cols->[0];
1836 $coldata{sid} = $sid;
1837 $coldata{page} = $webvar{page};
1838 $coldata{offset} = $webvar{offset} if $webvar{offset};
1839 $coldata{sortby} = $col;
1840 $coldata{colname} = $colnames->{$col};
1841 if ($col eq $sortby) {
1842 $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC');
1843 $coldata{sortorder} = $sortorder;
1844 } else {
1845 $coldata{order} = 'ASC';
1846 }
1847 if ($custom) {
1848 foreach my $ckey (keys %$custom) {
1849 $coldata{$ckey} = $custom->{$ckey};
1850 }
1851 }
1852 push @headings, \%coldata;
1853 }
1854
1855 $page->param(colheads => \@headings);
1856
1857} # end fill_colheads()
1858
1859
1860sub logaction {
1861 my $domid = shift;
1862 my $username = shift;
1863 my $groupid = shift;
1864 my $entry = shift;
1865
1866##fixme: push SQL into DNSDB.pm
1867##fixme: add bits to retrieve group/domain name info to retain after entity is deleted?
1868 my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?");
1869 $sth->execute($username);
1870 my ($user_id, $fullname) = $sth->fetchrow_array;
1871
1872 $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) ".
1873 "VALUES (?,?,?,?,?,?)") or warn $dbh->errstr;
1874 $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry) or warn $sth->errstr;
1875} # end logaction()
1876
1877
1878##fixme: generalize to return appropriate id on all cases (ie, use $partype)
1879sub parentID {
1880 my $id = shift;
1881 my $idtype = shift;
1882 my $partype = shift;
1883 my $defrec = shift || '';
1884
1885 my $sql = '';
1886
1887 if ($idtype eq 'dom') {
1888 return $id if $defrec eq 'y'; # "domain" + default records, we're really looking at a group.
1889 $sql = "SELECT group_id FROM domains WHERE domain_id=?";
1890 } elsif ($idtype eq 'rec') {
1891 if ($defrec eq 'y') {
1892 $sql = "SELECT group_id FROM default_records WHERE record_id=?";
1893 } else {
1894 return
1895 $sql = "SELECT d.group_id FROM domains d".
1896 " INNER JOIN records r ON d.domain_id=r.domain_id".
1897 " WHERE r.record_id=?";
1898 }
1899 } elsif ($idtype eq 'group') {
1900 $sql = "SELECT parent_group_id FROM groups WHERE group_id=?";
1901 } elsif ($idtype eq 'user') {
1902 $sql = "SELECT group_id FROM users WHERE user_id=?";
1903 } else {
1904 return "FOO", "BAR"; # can't get here.... we think.
1905 }
1906 my $sth = $dbh->prepare($sql);
1907 $sth->execute($id);
1908 my ($retid) = $sth->fetchrow_array;
1909 return $retid if $retid;
1910 # ahh! fall of the edge of the world if things went sideways
1911 ##fixme: really need to do a little more error handling, I think
1912} # end parentID()
1913
1914
1915# we have to do this in a variety of places; let's make it consistent
1916sub fill_permissions {
1917 my $template = shift; # may need to do several sets on a single page
1918 my $permset = shift; # hashref to permissions on object
1919 my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block
1920
1921 foreach (@permtypes) {
1922 $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_}));
1923 $template->param($_ => $permset->{$_});
1924 }
1925}
Note: See TracBrowser for help on using the repository browser.