source: trunk/dns.cgi@ 283

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

/trunk

Convert zone status change logging to DNSDB-internal. See #35
Add a global for holding general result messages for subs that
return booleans. This allows us to easily display the same text
as was added to the log.
Fix docucomment on mailNotify(); it (still!) referred to its
copy-paste parent in the IP Database.

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 92.2 KB
Line 
1#!/usr/bin/perl -w -T
2# Main web UI script for DeepNet DNS Administrator
3##
4# $Id: dns.cgi 283 2012-03-22 20:12:32Z kdeugau $
5# Copyright 2008-2011 Kris Deugau <kdeugau@deepnet.cx>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19##
20
21use strict;
22use warnings;
23
24use CGI::Carp qw (fatalsToBrowser);
25use CGI::Simple;
26use HTML::Template;
27use CGI::Session;
28use Crypt::PasswdMD5;
29use Digest::MD5 qw(md5_hex);
30use Net::DNS;
31use DBI;
32use Data::Dumper;
33
34#sub is_tainted {
35# # from perldoc perlsec
36# return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 };
37#}
38#use Cwd 'abs_path';
39#use File::Basename;
40#use lib dirname( abs_path $0 );
41#die "argh! tainted!" if is_tainted($0);
42#die "argh! \@INC got tainted!" if is_tainted(@INC);
43
44# don't remove! required for GNU/FHS-ish install from tarball
45use lib '.'; ##uselib##
46
47use DNSDB qw(:ALL);
48
49my @debugbits; # temp, to be spit out near the end of processing
50my $debugenv = 0;
51
52# Let's do these templates right...
53my $templatedir = "templates";
54
55# Set up the CGI object...
56my $q = new CGI::Simple;
57# ... and get query-string params as well as POST params if necessary
58$q->parse_query_string;
59
60# This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about...
61my %webvar = $q->Vars;
62
63# shut up some warnings, in case we arrive somewhere we forgot to set this
64$webvar{defrec} = 'n' if !$webvar{defrec}; # non-default records
65$webvar{revrec} = 'n' if !$webvar{revrec}; # non-reverse (domain) records
66
67# load some local system defaults (mainly DB connect info)
68# note this is not *absolutely* fatal, since there's a default dbname/user/pass in DNSDB.pm
69# we'll catch a bad DB connect string once we get to trying that
70##fixme: pass params to loadConfig, and use them there, to allow one codebase to support multiple sites
71if (!loadConfig()) {
72 warn "Using default configuration; unable to load custom settings: $DNSDB::errstr";
73}
74
75# persistent stuff needed on most/all pages
76my $sid = ($webvar{sid} ? $webvar{sid} : undef);
77my $session = new CGI::Session("driver:File", $sid, {Directory => $config{sessiondir}})
78 or die CGI::Session->errstr();
79#$sid = $session->id() if !$sid;
80if (!$sid) {
81 # init stuff. can probably axe this down to just above if'n'when user manipulation happens
82 $sid = $session->id();
83 $session->expire($config{timeout});
84# need to know the "upper" group the user can deal with; may as well
85# stick this in the session rather than calling out to the DB every time.
86 $session->param('logingroup',1);
87 $session->param('curgroup',1); # yes, we *do* need to track this too. er, probably.
88 $session->param('domlistsortby','domain');
89 $session->param('domlistorder','ASC');
90 $session->param('revzonessortby','revnet');
91 $session->param('revzonesorder','ASC');
92 $session->param('useradminsortby','user');
93 $session->param('useradminorder','ASC');
94 $session->param('grpmansortby','group');
95 $session->param('grpmanorder','ASC');
96 $session->param('reclistsortby','host');
97 $session->param('reclistorder','ASC');
98}
99
100# Just In Case. Stale sessions should not be resurrectable.
101if ($sid ne $session->id()) {
102 $sid = '';
103 changepage(page=> "login", sessexpired => 1);
104}
105
106# normal expiry, more or less
107if ($session->is_expired) {
108 $sid = '';
109 changepage(page=> "login", sessexpired => 1);
110}
111
112my $logingroup = ($session->param('logingroup') ? $session->param('logingroup') : 1);
113my $curgroup = ($session->param('curgroup') ? $session->param('curgroup') : $logingroup);
114
115# decide which page to spit out...
116# also set $webvar{page} before we try to use it.
117$webvar{page} = 'login' if !$webvar{page};
118
119# per-page startwith, filter, searchsubs
120
121##fixme: complain-munge-and-continue with non-"[a-z0-9-.]" filter and startwith
122$webvar{startwith} =~ s/^(0-9|[a-z]).*/$1/ if $webvar{startwith};
123# not much call for chars not allowed in domain names
124$webvar{filter} =~ s/[^a-zA-Z0-9_.:@-]//g if $webvar{filter};
125## only set 'y' if box is checked, no other values legal
126## however, see https://secure.deepnet.cx/trac/dnsadmin/ticket/31
127# first, drop obvious fakes
128delete $webvar{searchsubs} if $webvar{searchsubs} && $webvar{searchsubs} !~ /^[ny]/;
129# strip the known "turn me off!" bit.
130$webvar{searchsubs} =~ s/^n\s?// if $webvar{searchsubs};
131# strip non-y/n - note this legitimately allows {searchsubs} to go empty
132$webvar{searchsubs} =~ s/[^yn]//g if $webvar{searchsubs};
133
134$session->param($webvar{page}.'startwith', $webvar{startwith}) if defined($webvar{startwith});
135$session->param($webvar{page}.'filter', $webvar{filter}) if defined($webvar{filter});
136$session->param($webvar{page}.'searchsubs', $webvar{searchsubs}) if defined($webvar{searchsubs});
137
138my $startwith = $session->param($webvar{page}.'startwith');
139my $filter = $session->param($webvar{page}.'filter');
140my $searchsubs = $session->param($webvar{page}.'searchsubs');
141
142# ... and assemble the args
143my @filterargs;
144push @filterargs, "^[$startwith]" if $startwith;
145push @filterargs, $filter if $filter;
146
147# nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet
148
149my $header = HTML::Template->new(filename => "$templatedir/header.tmpl");
150my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl");
151$header->param(orgname => $config{orgname}) if $config{orgname} ne 'Example Corp';
152$footer->param(version => $DNSDB::VERSION);
153
154## set up "URL to self"
155# @#$%@%@#% XHTML - & in a URL must be escaped. >:(
156my $uri_self = $ENV{REQUEST_URI};
157$uri_self =~ s/\&([a-z])/\&amp\;$1/g;
158
159# le sigh. and we need to strip any previous action
160$uri_self =~ s/\&amp;action=[^&]+//g;
161
162# and search filter options. these get stored in the session, but discarded
163# as soon as you switch to a different page.
164##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits
165no warnings qw(uninitialized);
166$uri_self =~ s/\&amp;startwith=[a-z09-]*(\&)?/$1/g;
167$uri_self =~ s/\&amp;searchsubs=[a-z09-]*(\&)?/$1/g;
168$uri_self =~ s/\&amp;filter=[a-z09-]*(\&)?/$1/g;
169use warnings qw(uninitialized);
170
171# Fix up $uri_self so we don't lose the session/page
172$uri_self .= "?sid=$sid&amp;page=$webvar{page}" if $uri_self =~ m{/dns.cgi$};
173$uri_self = "$ENV{SCRIPT_NAME}?sid=$sid&amp;page=$webvar{page}$1" if $uri_self =~ m{/dns.cgi\&(.+)$};
174
175# pagination
176my $perpage = 15;
177$perpage = $config{perpage} if $config{perpage};
178my $offset = ($webvar{offset} ? $webvar{offset} : 0);
179
180# NB: these must match the field name and SQL ascend/descend syntax respectively
181my $sortby = "domain";
182my $sortorder = "ASC";
183
184##fixme: quit throwing the database handle around, and put all the SQL and direct DB fiddling into DNSDB.pm
185# dbname, user, pass, host (optional)
186my ($dbh,$msg) = connectDB($config{dbname}, $config{dbuser}, $config{dbpass}, $config{dbhost});
187
188if (!$dbh) {
189 print "Content-type: text/html\n\n";
190 print $header->output;
191 my $errpage = HTML::Template->new(filename => "$templatedir/dberr.tmpl");
192 $errpage->param(errmsg => $msg);
193 print $errpage->output;
194 print $footer->output;
195 exit;
196}
197
198# Load config pieces from the database. Ideally all but the DB user/pass/etc should be loaded here.
199initGlobals($dbh);
200
201# security check - does the user have permission to view this entity?
202# this is a prep step used "many" places
203my @viewablegroups;
204getChildren($dbh, $logingroup, \@viewablegroups, 'all');
205push @viewablegroups, $logingroup;
206
207my $page;
208eval {
209 # sigh. can't set loop_context_vars or global_vars once instantiated.
210 $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl",
211 loop_context_vars => 1, global_vars => 1);
212};
213if ($@) {
214 my $msg = $@;
215 $page = HTML::Template->new(filename => "$templatedir/badpage.tmpl");
216 if (-e "$templatedir/$webvar{page}.tmpl") {
217 $page->param(badtemplate => $q->escapeHTML($msg));
218 } else {
219 warn "Bad page $webvar{page} requested";
220 $page->param(badpage => $q->escapeHTML($webvar{page}));
221 }
222 $webvar{page} = 'badpage';
223}
224
225# handle login redirect
226if ($webvar{action}) {
227 if ($webvar{action} eq 'login') {
228 # Snag ACL/permissions here too
229
230# my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
231# $sth->execute($webvar{username});
232#
233# if (my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array) {
234# $webvar{password} = '' if !$webvar{password};
235#
236# if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
237# # native passwords (crypt-md5)
238# $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1);
239# } elsif ($pass =~ /^[0-9a-f]{32}$/) {
240# # VegaDNS import (hex-coded MD5)
241# $webvar{loginfailed} = 1 if $pass ne md5_hex($webvar{password});
242# } else {
243# # plaintext (convenient now and then)
244# $webvar{loginfailed} = 1 if $pass ne $webvar{password};
245# }
246
247 my $userdata = login($dbh, $webvar{username}, $webvar{password});
248
249 if ($userdata) {
250
251 # set session bits
252 $session->param('logingroup',$userdata->{group_id});
253 $session->param('curgroup',$userdata->{group_id});
254 $session->param('uid',$userdata->{user_id});
255 $session->param('username',$webvar{username});
256
257 changepage(page => "domlist");
258
259 } else {
260 $webvar{loginfailed} = 1;
261 } # user data fetch check
262
263 } elsif ($webvar{action} eq 'logout') {
264 # delete the session
265 $session->delete();
266 $session->flush();
267
268 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}";
269 $newurl =~ s|/[^/]+$|/|;
270 print "Status: 302\nLocation: $newurl\n\n";
271 exit;
272
273 } elsif ($webvar{action} eq 'chgroup') {
274 # fiddle session-stored group data
275 # magic incantation to... uhhh...
276
277 # ... and the "change group" bits...
278 $uri_self =~ s/\&amp;group=[^&]*//g;
279
280 # security check - does the user have permission to view this entity?
281 my $errmsg;
282 if (!(grep /^$webvar{group}$/, @viewablegroups)) {
283 # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere.
284 $session->param('curgroup',$logingroup);
285 $webvar{group} = $logingroup;
286 $curgroup = $logingroup;
287 $errmsg = "You are not permitted to view or make changes in the requested group";
288 $page->param(errmsg => $errmsg);
289 }
290
291 $session->param('curgroup', $webvar{group});
292 $curgroup = ($webvar{group} ? $webvar{group} : $session->param('curgroup'));
293
294 # I hate special cases.
295##fixme: probably need to handle webvar{revrec}=='y' too
296 if ($webvar{page} eq 'reclist' && $webvar{defrec} eq 'y') {
297 my %args = (page => $webvar{page}, id => $curgroup, defrec => $webvar{defrec}, revrec => $webvar{revrec});
298 $args{errmsg} = $errmsg if $errmsg;
299 changepage(%args);
300 }
301
302 }
303} # handle global webvar{action}s
304
305# Misc Things To Do on most pages
306initPermissions($dbh, $session->param('uid'));
307initActionLog($dbh, $session->param('uid'));
308
309$page->param(sid => $sid) unless $webvar{page} eq 'login'; # no session ID on the login page
310
311if ($webvar{page} eq 'login') {
312
313 $page->param(loginfailed => 1) if $webvar{loginfailed};
314 $page->param(sessexpired => 1) if $webvar{sessexpired};
315# $page->param(orgname => $config{orgname}) if $config{orgname} ne 'Example Corp';
316 $page->param(version => $DNSDB::VERSION);
317
318} elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') {
319
320 $page->param(domlist => 1);
321
322# hmm. seeing problems in some possibly-not-so-corner cases.
323# this currently only handles "domain on", "domain off"
324 if (defined($webvar{zonestatus})) {
325 # security check - does the user have permission to access this entity?
326 my $flag = 0;
327 foreach (@viewablegroups) {
328 $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'domain');
329 }
330 if ($flag && ($permissions{admin} || $permissions{domain_edit})) {
331 my $stat = zoneStatus($dbh,$webvar{id},'n',$webvar{zonestatus});
332 $page->param(resultmsg => $DNSDB::resultstr);
333 } else {
334 $page->param(errmsg => "You are not permitted to view or change the requested domain");
335 }
336 $uri_self =~ s/\&amp;zonestatus=[^&]*//g; # clean up URL for stuffing into templates
337 }
338
339 if ($session->param('resultmsg')) {
340 $page->param(resultmsg => $session->param('resultmsg'));
341 $session->clear('resultmsg');
342 }
343 if ($session->param('errmsg')) {
344 $page->param(errmsg => $session->param('errmsg'));
345 $session->clear('errmsg');
346 }
347
348 $page->param(curpage => $webvar{page});
349
350 listdomains();
351
352} elsif ($webvar{page} eq 'newdomain') {
353
354 changepage(page => "domlist", errmsg => "You are not permitted to add domains")
355 unless ($permissions{admin} || $permissions{domain_create});
356
357 fill_grouplist("grouplist");
358
359 if ($session->param('add_failed')) {
360 $session->clear('add_failed');
361 $page->param(add_failed => 1);
362 $page->param(errmsg => $session->param('errmsg'));
363 $session->clear('errmsg');
364 $page->param(domain => $webvar{domain});
365 }
366
367} elsif ($webvar{page} eq 'adddomain') {
368
369 changepage(page => "domlist", errmsg => "You are not permitted to add domains")
370 unless ($permissions{admin} || $permissions{domain_create});
371
372 # security check - does the user have permission to access this entity?
373 if (!check_scope(id => $webvar{group}, type => 'group')) {
374 $session->param('add_failed', 1);
375##fixme: domain a security risk for XSS?
376 changepage(page => "newdomain", domain => $webvar{domain},
377 errmsg => "You do not have permission to add a domain to the requested group");
378 }
379
380 $webvar{makeactive} = 0 if !defined($webvar{makeactive});
381
382 my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0),
383 (username => $session->param("username"), id => $session->param("uid")));
384
385 if ($code eq 'OK') {
386 mailNotify($dbh, "New ".($webvar{makeactive} eq 'on' ? 'Active' : 'Inactive')." Domain Created",
387 ($webvar{makeactive} eq 'on' ? 'Active' : 'Inactive').qq( domain "$webvar{domain}" added by ).
388 $session->param("username"));
389 changepage(page => "reclist", id => $msg);
390 } else {
391 logaction(0, $session->param("username"), $webvar{group}, "Failed adding domain $webvar{domain} ($msg)")
392 if $config{log_failures};
393 $session->param('add_failed', 1);
394##fixme: domain a security risk for XSS?
395##fixme: keep active/inactive state, group selection
396 changepage(page => "newdomain", domain => $webvar{domain}, errmsg => $msg);
397 }
398
399} elsif ($webvar{page} eq 'deldom') {
400
401 changepage(page => "domlist", errmsg => "You are not permitted to delete domains")
402 unless ($permissions{admin} || $permissions{domain_delete});
403
404 # security check - does the user have permission to access this entity?
405 if (!check_scope(id => $webvar{id}, type => 'domain')) {
406 changepage(page => "domlist", errmsg => "You do not have permission to delete the requested domain");
407 }
408
409 $page->param(id => $webvar{id});
410
411 # first pass = confirm y/n (sorta)
412 if (!defined($webvar{del})) {
413
414 $page->param(del_getconf => 1);
415 $page->param(domain => domainName($dbh,$webvar{id}));
416
417 } elsif ($webvar{del} eq 'ok') {
418 my $pargroup = parentID($dbh, (id => $webvar{id}, type => 'domain', revrec => $webvar{revrec}));
419 my $dom = domainName($dbh, $webvar{id});
420 my ($code,$msg) = delZone($dbh, $webvar{id}, $webvar{revrec});
421 if ($code eq 'OK') {
422 logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $dom");
423 changepage(page => "domlist", resultmsg => "Deleted domain $dom");
424 } else {
425 logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $dom ($msg)")
426 if $config{log_failures};
427 changepage(page => "domlist", errmsg => "Error deleting domain $dom: $msg");
428 }
429
430 } else {
431 # cancelled. whee!
432 changepage(page => "domlist");
433 }
434
435} elsif ($webvar{page} eq 'revzones') {
436
437 $webvar{revrec} = 'y';
438
439 if (defined($webvar{zonestatus})) {
440 # security check - does the user have permission to access this entity?
441 my $flag = 0;
442 foreach (@viewablegroups) {
443 $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'revzone');
444 }
445 if ($flag && ($permissions{admin} || $permissions{domain_edit})) {
446 my $stat = zoneStatus($dbh,$webvar{id},'y',$webvar{zonestatus});
447 $page->param(resultmsg => $DNSDB::resultstr);
448 } else {
449 $page->param(errmsg => "You are not permitted to view or change the requested reverse zone");
450 }
451 $uri_self =~ s/\&amp;zonestatus=[^&]*//g; # clean up URL for stuffing into templates
452 }
453
454 if ($session->param('resultmsg')) {
455 $page->param(resultmsg => $session->param('resultmsg'));
456 $session->clear('resultmsg');
457 }
458 if ($session->param('errmsg')) {
459 $page->param(errmsg => $session->param('errmsg'));
460 $session->clear('errmsg');
461 }
462
463 $page->param(curpage => $webvar{page});
464 listzones();
465
466} elsif ($webvar{page} eq 'newrevzone') {
467
468## scope/access check - use domain settings? invent new (bleh)
469 changepage(page => "revzones", errmsg => "You are not permitted to add reverse zones")
470 unless ($permissions{admin} || $permissions{domain_create});
471
472 fill_grouplist("grouplist");
473
474 # prepopulate revpatt with the matching default record
475# getRecByName($dbh, (revrec => $webvar{revrec}, defrec => $webvar{defrec}, host => 'string'));
476
477 if ($session->param('add_failed')) {
478 $session->clear('add_failed');
479 $page->param(errmsg => $session->param('errmsg'));
480 $session->clear('errmsg');
481 $page->param(revzone => $webvar{revzone});
482 $page->param(revpatt => $webvar{revpatt});
483 }
484
485} elsif ($webvar{page} eq 'addrevzone') {
486
487 changepage(page => "revzones", errmsg => "You are not permitted to add reverse zones")
488 unless ($permissions{admin} || $permissions{domain_create});
489
490 # security check - does the user have permission to access this entity?
491 if (!check_scope(id => $webvar{group}, type => 'group')) {
492 changepage(page => "newrevzone", add_failed => 1, revzone => $webvar{revzone}, revpatt => $webvar{revpatt},
493 errmsg => "You do not have permission to add a reverse zone to the requested group");
494 }
495
496 my ($code,$msg) = addRDNS($dbh, $webvar{revzone}, $webvar{revpatt}, $webvar{group},
497 ($webvar{makeactive} eq 'on' ? 1 : 0),
498 (username => $session->param("username"), id => $session->param("uid")) );
499
500 if ($code eq 'OK') {
501 logaction(0, $session->param("username"), $webvar{group}, "Added reverse zone $webvar{revzone}", $msg);
502 changepage(page => "reclist", id => $msg, revrec => 'y');
503 } else {
504 logaction(0, $session->param("username"), $webvar{group}, "Failed adding reverse zone $webvar{revzone} ($msg)");
505 $session->param('add_failed', 1);
506 changepage(page => "newrevzone", revzone => $webvar{revzone}, revpatt => $webvar{revpatt}, errmsg => $msg);
507 }
508
509} elsif ($webvar{page} eq 'delrevzone') {
510
511 changepage(page => "revzones", errmsg => "You are not permitted to delete reverse zones")
512 unless ($permissions{admin} || $permissions{domain_delete});
513
514 # security check - does the user have permission to access this entity?
515 if (!check_scope(id => $webvar{id}, type => 'revzone')) {
516 changepage(page => "revzones", errmsg => "You do not have permission to delete the requested reverse zone");
517 }
518
519 $page->param(id => $webvar{id});
520
521 # first pass = confirm y/n (sorta)
522 if (!defined($webvar{del})) {
523
524 $page->param(del_getconf => 1);
525 $page->param(revzone => revName($dbh,$webvar{id}));
526
527 } elsif ($webvar{del} eq 'ok') {
528 my $pargroup = parentID($dbh, (id => $webvar{id}, type => 'revzone', revrec => $webvar{revrec}));
529 my $zone = revName($dbh, $webvar{id});
530 my ($code,$msg) = delZone($dbh, $webvar{id}, 'y');
531 if ($code eq 'OK') {
532##fixme: logaction needs to take "domid OR revid" and some way to know which it is
533 logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted reverse zone $zone");
534 changepage(page => "revzones", resultmsg => "Deleted reverse zone $zone");
535 } else {
536 logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $zone ($msg)")
537 if $config{log_failures};
538#push @debugbits, "got back $code, $msg\n";
539 changepage(page => "revzones", errmsg => "Error deleting reverse zone $zone: $msg");
540 }
541
542 } else {
543 # cancelled. whee!
544 changepage(page => "revzones");
545 }
546
547} elsif ($webvar{page} eq 'reclist') {
548
549 # security check - does the user have permission to view this entity?
550 if (!check_scope(id => $webvar{id}, type =>
551 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
552 $page->param(errmsg => "You are not permitted to view or change the requested ".
553 ($webvar{defrec} eq 'y' ? "group's default records" :
554 ($webvar{revrec} eq 'y' ? "reverse zone's records" : "domain's records")));
555 $page->param(perm_err => 1); # this causes the template to skip the record listing output.
556 goto DONERECLIST; # and now we skip filling in the content which is not printed due to perm_err above
557 }
558
559# hmm. where do we send them?
560 if ($webvar{defrec} eq 'y' && !$permissions{admin}) {
561 $page->param(errmsg => "You are not permitted to edit default records");
562 $page->param(perm_err => 1);
563 } else {
564
565 $page->param(mayeditsoa => $permissions{admin} || $permissions{domain_edit});
566##fixme: ACL needs pondering. Does "edit domain" interact with record add/remove/etc?
567# Note this seems to be answered "no" in Vega.
568# ACLs
569 $page->param(record_create => ($permissions{admin} || $permissions{record_create}) );
570# we don't have any general edit links on the page; they're all embedded in the TMPL_LOOP
571# $page->param(record_edit => ($permissions{admin} || $permissions{record_edit}) );
572 $page->param(record_delete => ($permissions{admin} || $permissions{record_delete}) );
573
574 # Handle record list for both default records (per-group) and live domain records
575
576 $page->param(defrec => $webvar{defrec});
577 $page->param(revrec => $webvar{revrec});
578 $page->param(id => $webvar{id});
579 $page->param(curpage => $webvar{page});
580
581 my $count = getRecCount($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id}, $filter);
582
583 $sortby = 'host';
584# sort/order
585 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
586 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
587
588 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
589 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
590
591# set up the headers
592 my @cols;
593 my %colheads;
594 if ($webvar{revrec} eq 'n') {
595 @cols = ('host', 'type', 'val', 'distance', 'weight', 'port', 'ttl');
596 %colheads = (host => 'Name', type => 'Type', val => 'Address',
597 distance => 'Distance', weight => 'Weight', port => 'Port', ttl => 'TTL');
598 } else {
599 @cols = ('val', 'type', 'host', 'ttl');
600 %colheads = (val => 'IP Address', type => 'Type', host => 'Hostname', ttl => 'TTL');
601 }
602 my %custom = (id => $webvar{id}, defrec => $webvar{defrec}, revrec => $webvar{revrec});
603 fill_colheads($sortby, $sortorder, \@cols, \%colheads, \%custom);
604
605# fill the page-count and first-previous-next-last-all details
606 fill_pgcount($count,"records",
607 ($webvar{defrec} eq 'y' ? "group ".groupName($dbh,$webvar{id}) :
608 ($webvar{revrec} eq 'y' ? revName($dbh,$webvar{id}) : domainName($dbh,$webvar{id}))
609 ));
610 fill_fpnla($count); # should put some params on this sub...
611
612 $page->param(defrec => $webvar{defrec});
613 showzone($webvar{defrec}, $webvar{revrec}, $webvar{id});
614 if ($webvar{defrec} eq 'n') {
615# showzone('n',$webvar{id});
616##fixme: permission for viewing logs?
617##fixme: determine which slice of the log we view (group, domain, revzone)
618 if ($webvar{revrec} eq 'n') {
619 $page->param(logdom => 1);
620 } else {
621 $page->param(logrdns => 1);
622 }
623 }
624
625 if ($session->param('resultmsg')) {
626 $page->param(resultmsg => $session->param('resultmsg'));
627 $session->clear('resultmsg');
628 }
629 if ($session->param('warnmsg')) {
630 $page->param(warnmsg => $session->param('warnmsg'));
631 $session->clear('warnmsg');
632 }
633 if ($session->param('errmsg')) {
634 $page->param(errmsg => $session->param('errmsg'));
635 $session->clear('errmsg');
636 }
637
638 } # close "you can't edit default records" check
639
640 # Yes, this is a GOTO target. PTBHTTT.
641 DONERECLIST: ;
642
643} elsif ($webvar{page} eq 'record') {
644
645 # security check - does the user have permission to access this entity?
646 if (!check_scope(id => $webvar{id}, type =>
647 ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) {
648 $page->param(perm_err => "You are not permitted to edit the requested record");
649 goto DONEREC;
650 }
651 # round 2, check the parent.
652 if (!check_scope(id => $webvar{parentid}, type =>
653 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
654 my $msg = ($webvar{defrec} eq 'y' ?
655 "You are not permitted to add or edit default records in the requested group" :
656 "You are not permitted to add or edit records in the requested domain/zone");
657 $page->param(perm_err => $msg);
658 goto DONEREC;
659 }
660
661 $page->param(defrec => $webvar{defrec});
662 $page->param(revrec => $webvar{revrec});
663 $page->param(fwdzone => $webvar{revrec} eq 'n');
664
665 if ($webvar{recact} eq 'new') {
666
667 changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid})
668 unless ($permissions{admin} || $permissions{record_create});
669
670 $page->param(todo => "Add record");
671 $page->param(recact => "add");
672 $page->param(parentid => $webvar{parentid});
673
674 fill_recdata();
675
676 } elsif ($webvar{recact} eq 'add') {
677
678 changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid})
679 unless ($permissions{admin} || $permissions{record_create});
680
681 my @recargs = ($dbh,$webvar{defrec},$webvar{revrec},$webvar{parentid},
682 \$webvar{name},\$webvar{type},\$webvar{address},$webvar{ttl});
683 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) {
684 push @recargs, $webvar{distance};
685 if ($webvar{type} == $reverse_typemap{SRV}) {
686 push @recargs, $webvar{weight};
687 push @recargs, $webvar{port};
688 }
689 }
690
691 my ($code,$msg) = addRec(@recargs);
692
693 if ($code eq 'OK' || $code eq 'WARN') {
694 my $restr;
695 if ($webvar{defrec} eq 'y') {
696 $restr = "Added default record '$webvar{name} $typemap{$webvar{type}}";
697 $restr .= " [distance $webvar{distance}]" if $typemap{$webvar{type}} eq 'MX';
698 $restr .= " [priority $webvar{distance}] [weight $webvar{weight}] [port $webvar{port}]"
699 if $typemap{$webvar{type}} eq 'SRV';
700 $restr .= " $webvar{address}', TTL $webvar{ttl}";
701 logaction(0, $session->param("username"), $webvar{parentid}, $restr);
702 } else {
703 $restr = "Added record '$webvar{name} $typemap{$webvar{type}}";
704 $restr .= " [distance $webvar{distance}]" if $typemap{$webvar{type}} eq 'MX';
705 $restr .= " [priority $webvar{distance}] [weight $webvar{weight}] [port $webvar{port}]"
706 if $typemap{$webvar{type}} eq 'SRV';
707 $restr .= " $webvar{address}', TTL $webvar{ttl}";
708 logaction($webvar{parentid}, $session->param("username"),
709 parentID($dbh, (id => $webvar{parentid}, type => 'domain', revrec => $webvar{revrec})), $restr);
710 }
711 my %pageparams = (page => "reclist", id => $webvar{parentid},
712 defrec => $webvar{defrec}, revrec => $webvar{revrec});
713 $pageparams{warnmsg} = $msg."<br><br>\n".$restr if $code eq 'WARN';
714 $pageparams{resultmsg} = $restr if $code eq 'OK';
715 changepage(%pageparams);
716 } else {
717 $page->param(failed => 1);
718 $page->param(errmsg => $msg);
719 $page->param(wastrying => "adding");
720 $page->param(todo => "Add record");
721 $page->param(recact => "add");
722 $page->param(parentid => $webvar{parentid});
723 $page->param(id => $webvar{id});
724 fill_recdata(); # populate the form... er, mostly.
725 if ($config{log_failures}) {
726 if ($webvar{defrec} eq 'y') {
727 logaction(0, $session->param("username"), $webvar{parentid},
728 "Failed adding default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)");
729 } else {
730 logaction($webvar{parentid}, $session->param("username"),
731 parentID($dbh, (id => $webvar{parentid}, type => 'domain', revrec => $webvar{revrec})),
732 "Failed adding record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)");
733 }
734 }
735 }
736
737 } elsif ($webvar{recact} eq 'edit') {
738
739 changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid})
740 unless ($permissions{admin} || $permissions{record_edit});
741
742 $page->param(todo => "Update record");
743 $page->param(recact => "update");
744 $page->param(parentid => $webvar{parentid});
745 $page->param(id => $webvar{id});
746 my $recdata = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
747 $page->param(name => $recdata->{host});
748 $page->param(address => $recdata->{val});
749 $page->param(distance => $recdata->{distance});
750 $page->param(weight => $recdata->{weight});
751 $page->param(port => $recdata->{port});
752 $page->param(ttl => $recdata->{ttl});
753 $page->param(typelist => getTypelist($dbh, $webvar{revrec}, $recdata->{type}));
754
755 } elsif ($webvar{recact} eq 'update') {
756
757 changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid})
758 unless ($permissions{admin} || $permissions{record_edit});
759
760# # prevent out-of-domain records from getting added by appending the domain, or DOMAIN for default records
761# my $pname = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid}));
762# $webvar{name} =~ s/\.*$/\.$pname/ if $webvar{name} !~ /$pname$/;
763
764 # get current/previous record info so we can log "updated 'foo A 1.2.3.4' to 'foo A 2.3.4.5'"
765 my $oldrec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
766
767 my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{revrec},$webvar{id},$webvar{parentid},
768 \$webvar{name},\$webvar{type},\$webvar{address},$webvar{ttl},
769 $webvar{distance},$webvar{weight},$webvar{port});
770
771 if ($code eq 'OK' || $code eq 'WARN') {
772 my $restr;
773 if ($webvar{defrec} eq 'y') {
774 $restr = "Updated default record from '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl}\n".
775 "to '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}";
776 logaction(0, $session->param("username"), $webvar{parentid}, $restr);
777 } else {
778 $restr = "Updated record from '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl}\n".
779 "to '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}";
780 logaction($webvar{parentid}, $session->param("username"),
781 parentID($dbh, (id => $webvar{id}, type => 'record', defrec => $webvar{defrec},
782 revrec => $webvar{revrec}, partype => 'group')),
783 $restr);
784 }
785 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
786 revrec => $webvar{revrec}, resultmsg => $restr, warnmsg => ($code ne 'OK' ? $msg : ''));
787 } else {
788 $page->param(failed => 1);
789 $page->param(errmsg => $msg);
790 $page->param(wastrying => "updating");
791 $page->param(todo => "Update record");
792 $page->param(recact => "update");
793 $page->param(parentid => $webvar{parentid});
794 $page->param(id => $webvar{id});
795 fill_recdata();
796 if ($config{log_failures}) {
797 if ($webvar{defrec} eq 'y') {
798 logaction(0, $session->param("username"), $webvar{parentid},
799 "Failed updating default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)");
800 } else {
801 logaction($webvar{parentid}, $session->param("username"),
802 parentID($dbh, (id => $webvar{parentid}, type => 'domain', revrec => $webvar{revrec})),
803 "Failed updating record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)");
804 }
805 }
806 }
807 }
808
809 if ($webvar{defrec} eq 'y') {
810 $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid}));
811 } else {
812 $page->param(parentid => $webvar{parentid});
813 $page->param(dohere => domainName($dbh,$webvar{parentid})) if $webvar{revrec} eq 'n';
814 $page->param(dohere => revName($dbh,$webvar{parentid})) if $webvar{revrec} eq 'y';
815 }
816
817 # Yes, this is a GOTO target. PTBHTTT.
818 DONEREC: ;
819
820} elsif ($webvar{page} eq 'delrec') {
821
822 # This is a complete separate segment since it uses a different template from add/edit records above
823
824 changepage(page => "reclist", errmsg => "You are not permitted to delete records", id => $webvar{parentid},
825 defrec => $webvar{defrec}, revrec => $webvar{revrec})
826 unless ($permissions{admin} || $permissions{record_delete});
827
828 if (!check_scope(id => $webvar{id}, type =>
829 ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) {
830 # redirect to domlist because we don't have permission for the entity requested
831 changepage(page => 'domlist', revrec => $webvar{revrec},
832 errmsg => "You do not have permission to delete records in the requested ".
833 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
834 }
835
836 $page->param(id => $webvar{id});
837 $page->param(defrec => $webvar{defrec});
838 $page->param(revrec => $webvar{revrec});
839 $page->param(parentid => $webvar{parentid});
840 # first pass = confirm y/n (sorta)
841 if (!defined($webvar{del})) {
842 $page->param(del_getconf => 1);
843 my $rec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
844 $page->param(host => $rec->{host});
845 $page->param(ftype => $typemap{$rec->{type}});
846 $page->param(recval => $rec->{val});
847 } elsif ($webvar{del} eq 'ok') {
848# get rec data before we try to delete it
849 my $rec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
850 my ($code,$msg) = delRec($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
851 if ($code eq 'OK') {
852 if ($webvar{defrec} eq 'y') {
853 my $recclass = ($webvar{revrec} eq 'n' ? 'default record' : 'default reverse record');
854##fixme: log distance for MX; log port/weight/distance for SRV
855 my $restr = "Deleted $recclass '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}";
856 logaction(0, $session->param("username"), $rec->{parid}, $restr);
857 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
858 revrec => $webvar{revrec}, resultmsg => $restr);
859 } else {
860 my $recclass = ($webvar{revrec} eq 'n' ? 'record' : 'reverse record');
861 my $restr = "Deleted $recclass '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}";
862 logaction($rec->{parid}, $session->param("username"),
863 parentID($dbh, (id => $rec->{parid}, type => 'domain', revrec => $webvar{revrec})),
864 $restr);
865 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
866 revrec => $webvar{revrec}, resultmsg => $restr);
867 }
868 } else {
869## need to find failure mode
870 if ($config{log_failures}) {
871 if ($webvar{defrec} eq 'y') {
872 logaction(0, $session->param("username"), $rec->{parid},
873 "Failed deleting default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}',".
874 " TTL $rec->{ttl} ($msg)");
875 } else {
876 logaction($rec->{parid}, $session->param("username"),
877 parentID($dbh, (id => $rec->{parid}, type => 'domain', revrec => $webvar{revrec})),
878 "Failed deleting record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl} ($msg)");
879 }
880 }
881 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
882 revrec => $webvar{revrec}, errmsg => "Error deleting record: $msg");
883 }
884 } else {
885 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec});
886 }
887
888} elsif ($webvar{page} eq 'editsoa') {
889
890 # security check - does the user have permission to view this entity?
891 # id is domain/revzone/group id
892 if (!check_scope(id => $webvar{id}, type =>
893 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
894 changepage(page => 'domlist', errmsg => "You do not have permission to edit the ".
895 ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ".
896 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
897 }
898
899 if ($webvar{defrec} eq 'y') {
900 changepage(page => "domlist", errmsg => "You are not permitted to edit default records")
901 unless $permissions{admin};
902 } else {
903 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
904 unless ($permissions{admin} || $permissions{domain_edit});
905 }
906
907 fillsoa($webvar{defrec},$webvar{revrec},$webvar{id});
908
909} elsif ($webvar{page} eq 'updatesoa') {
910
911 # security check - does the user have permission to view this entity?
912 # pass 1, record ID
913 if (!check_scope(id => $webvar{recid}, type =>
914 ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) {
915 changepage(page => 'domlist', errmsg => "You do not have permission to edit the requested SOA record");
916 }
917 # pass 2, parent (group or domain) ID
918 if (!check_scope(id => $webvar{id}, type =>
919 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
920 changepage(page => 'domlist', errmsg => "You do not have permission to edit the ".
921 ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ".
922 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
923 }
924
925 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
926 unless ($permissions{admin} || $permissions{domain_edit});
927
928 # get old SOA for log
929 my %soa = getSOA($dbh,$webvar{defrec},$webvar{revrec},$webvar{id});
930
931# my $sth;
932###fixme: push SQL into DNSDB.pm
933###fixme: data validation: make sure {recid} is really the SOA for {id}
934# # no domain ID, so we're editing the default SOA for a group (we don't care which one here)
935# # plus a bit of magic to update the appropriate table
936# my $sql = "UPDATE ".($webvar{defrec} eq 'y' ? "default_records" : "records").
937# " SET host=?, val=?, ttl=? WHERE record_id=?";
938# $sth = $dbh->prepare($sql);
939# $sth->execute("$webvar{contact}:$webvar{prins}",
940# "$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}",
941# $webvar{ttl},
942# $webvar{recid});
943
944 my ($code, $msg) = updateSOA($dbh, $webvar{defrec}, $webvar{revrec},
945 (contact => $webvar{contact}, prins => $webvar{prins}, refresh => $webvar{refresh},
946 retry => $webvar{retry}, expire => $webvar{expire}, minttl => $soa{minttl},
947 ttl => $webvar{ttl}, recid => $webvar{recid}) );
948 if ($code eq 'OK') {
949 changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec}, revrec => $webvar{revrec},
950 resultmsg => "SOA record updated");
951 } else {
952 $page->param(update_failed => 1);
953 $page->param(msg => $DNSDB::errstr);
954 fillsoa($webvar{defrec},$webvar{revrec},$webvar{id});
955 }
956
957##fixme: faillog
958# } else {
959if (0) {
960 # do this in the order of "default to most common case"
961 my $loggroup;
962 my $logdomain = $webvar{id};
963 if ($webvar{defrec} eq 'y') {
964 $loggroup = $webvar{id};
965 $logdomain = 0;
966 } else {
967 $loggroup = parentID($dbh, (id => $logdomain, type => 'domain', revrec => $webvar{revrec}));
968 }
969
970 logaction($logdomain, $session->param("username"), $loggroup,
971 "Updated ".($webvar{defrec} eq 'y' ? 'default ' : '')."SOA for ".
972 ($webvar{defrec} eq 'y' ? groupName($dbh, $webvar{id}) : domainName($dbh, $webvar{id}) ).
973 ": (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
974 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl}) to ".
975 "(ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},".
976 " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl})");
977 } # if (0)
978
979} elsif ($webvar{page} eq 'grpman') {
980
981 listgroups();
982
983# Permissions!
984 $page->param(addgrp => $permissions{admin} || $permissions{group_create});
985 $page->param(edgrp => $permissions{admin} || $permissions{group_edit});
986 $page->param(delgrp => $permissions{admin} || $permissions{group_delete});
987
988 if ($session->param('resultmsg')) {
989 $page->param(resultmsg => $session->param('resultmsg'));
990 $session->clear('resultmsg');
991 }
992 if ($session->param('warnmsg')) {
993 $page->param(warnmsg => $session->param('warnmsg'));
994 $session->clear('warnmsg');
995 }
996 if ($session->param('errmsg')) {
997 $page->param(errmsg => $session->param('errmsg'));
998 $session->clear('errmsg');
999 }
1000 $page->param(curpage => $webvar{page});
1001
1002} elsif ($webvar{page} eq 'newgrp') {
1003
1004 changepage(page => "grpman", errmsg => "You are not permitted to add groups")
1005 unless ($permissions{admin} || $permissions{group_create});
1006
1007 # do.. uhh.. stuff.. if we have no webvar{grpaction}
1008 if ($webvar{grpaction} && $webvar{grpaction} eq 'add') {
1009
1010 # security check - does the user have permission to access this entity?
1011 if (!check_scope(id => $webvar{pargroup}, type => 'group')) {
1012 changepage(page => "grpman", errmsg => "You are not permitted to add a group to the requested parent group");
1013 }
1014
1015 my %newperms;
1016 my $alterperms = 0;
1017 foreach (@permtypes) {
1018 $newperms{$_} = 0;
1019 if ($permissions{admin} || $permissions{$_}) {
1020 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
1021 } else {
1022 $alterperms = 1;
1023 }
1024 }
1025 # not gonna provide the 4th param: template-or-clone flag, just yet
1026 my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms);
1027 if ($code eq 'OK') {
1028 logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}");
1029 if ($alterperms) {
1030 changepage(page => "grpman", warnmsg =>
1031 "You can only grant permissions you hold. New group $webvar{newgroup} added with reduced access.");
1032 } else {
1033 changepage(page => "grpman", resultmsg => "Added group $webvar{newgroup}");
1034 }
1035 } # fallthrough else
1036 logaction(0, $session->param("username"), $webvar{pargroup}, "Failed to add group $webvar{newgroup}: $msg")
1037 if $config{log_failures};
1038 # no point in doing extra work
1039 fill_permissions($page, \%newperms);
1040 $page->param(add_failed => 1);
1041 $page->param(errmsg => $msg);
1042 $page->param(newgroup => $webvar{newgroup});
1043 fill_grouplist('pargroup',$webvar{pargroup});
1044 } else {
1045 fill_grouplist('pargroup',$curgroup);
1046 # fill default permissions with immediate parent's current ones
1047 my %parperms;
1048 getPermissions($dbh, 'group', $curgroup, \%parperms);
1049 fill_permissions($page, \%parperms);
1050 }
1051
1052} elsif ($webvar{page} eq 'delgrp') {
1053
1054 changepage(page => "grpman", errmsg => "You are not permitted to delete groups", id => $webvar{parentid})
1055 unless ($permissions{admin} || $permissions{group_delete});
1056
1057 # security check - does the user have permission to access this entity?
1058 if (!check_scope(id => $webvar{id}, type => 'group')) {
1059 changepage(page => "grpman", errmsg => "You are not permitted to delete the requested group");
1060 }
1061
1062 $page->param(id => $webvar{id});
1063 # first pass = confirm y/n (sorta)
1064 if (!defined($webvar{del})) {
1065 $page->param(del_getconf => 1);
1066
1067##fixme
1068# do a check for "group has stuff in it", and splatter a big warning
1069# up along with an unchecked-by-default check box to YES DAMMIT DELETE THE WHOLE THING
1070
1071 } elsif ($webvar{del} eq 'ok') {
1072 my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it...
1073 my $delparent = parentID($dbh, (id => $webvar{id}, type => 'group'));
1074 my ($code,$msg) = delGroup($dbh, $webvar{id});
1075 if ($code eq 'OK') {
1076##fixme: need to clean up log when deleting a major container
1077 logaction(0, $session->param("username"), $delparent, "Deleted group $deleteme");
1078 changepage(page => "grpman", resultmsg => "Deleted group $deleteme");
1079 } else {
1080# need to find failure mode
1081 logaction(0, $session->param("username"), $delparent, "Failed to delete group $deleteme: $msg")
1082 if $config{log_failures};
1083 changepage(page => "grpman", errmsg => "Error deleting group $deleteme: $msg");
1084 }
1085 } else {
1086 # cancelled. whee!
1087 changepage(page => "grpman");
1088 }
1089 $page->param(delgroupname => groupName($dbh, $webvar{id}));
1090
1091} elsif ($webvar{page} eq 'edgroup') {
1092
1093 changepage(page => "grpman", errmsg => "You are not permitted to edit groups")
1094 unless ($permissions{admin} || $permissions{group_edit});
1095
1096 # security check - does the user have permission to access this entity?
1097 if (!check_scope(id => $webvar{gid}, type => 'group')) {
1098 changepage(page => "grpman", errmsg => "You are not permitted to edit the requested group");
1099 }
1100
1101 if ($webvar{grpaction} eq 'updperms') {
1102 # extra safety check; make sure user can't construct a URL to bypass ACLs
1103 my %curperms;
1104 getPermissions($dbh, 'group', $webvar{gid}, \%curperms);
1105 my %chperms;
1106 my $alterperms = 0;
1107 foreach (@permtypes) {
1108 $webvar{$_} = 0 if !defined($webvar{$_});
1109 $webvar{$_} = 1 if $webvar{$_} eq 'on';
1110 if ($permissions{admin} || $permissions{$_}) {
1111 $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_};
1112 } else {
1113 $alterperms = 1;
1114 $chperms{$_} = 0;
1115 }
1116 }
1117 my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms);
1118 if ($code eq 'OK') {
1119 logaction(0, $session->param("username"), $webvar{gid},
1120 "Updated default permissions in group $webvar{gid} (".groupName($dbh, $webvar{gid}).")");
1121 if ($alterperms) {
1122 changepage(page => "grpman", warnmsg =>
1123 "You can only grant permissions you hold. Default permissions in group ".
1124 groupName($dbh, $webvar{gid})." updated with reduced access");
1125 } else {
1126 changepage(page => "grpman", resultmsg =>
1127 "Updated default permissions in group ".groupName($dbh, $webvar{gid}));
1128 }
1129 } # fallthrough else
1130 logaction(0, $session->param("username"), $webvar{gid}, "Failed to update default permissions in group ".
1131 groupName($dbh, $webvar{gid}).": $msg")
1132 if $config{log_failures};
1133 # no point in doing extra work
1134 fill_permissions($page, \%chperms);
1135 $page->param(errmsg => $msg);
1136 }
1137 $page->param(gid => $webvar{gid});
1138 $page->param(grpmeddle => groupName($dbh, $webvar{gid}));
1139 my %grpperms;
1140 getPermissions($dbh, 'group', $webvar{gid}, \%grpperms);
1141 fill_permissions($page, \%grpperms);
1142
1143} elsif ($webvar{page} eq 'bulkdomain') {
1144 # Bulk operations on domains. Note all but group move are available on the domain list.
1145
1146 changepage(page => "domlist", errmsg => "You are not permitted to make bulk domain changes")
1147 unless ($permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
1148
1149 fill_grouplist("grouplist");
1150
1151##fixme
1152##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
1153##fixme
1154
1155 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
1156 $sth->execute($curgroup);
1157 my ($count) = ($sth->fetchrow_array);
1158
1159 $page->param(curpage => $webvar{page});
1160 fill_pgcount($count,'domains',groupName($dbh,$curgroup));
1161 fill_fpnla($count);
1162 $page->param(perpage => $perpage);
1163
1164 my @domlist;
1165 my $sql = "SELECT domain_id,domain FROM domains".
1166 " WHERE group_id=?".
1167 " ORDER BY domain".
1168 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1169 $sth = $dbh->prepare($sql);
1170 $sth->execute($curgroup);
1171 my $rownum = 0;
1172 while (my @data = $sth->fetchrow_array) {
1173 my %row;
1174 $row{domid} = $data[0];
1175 $row{domain} = $data[1];
1176 $rownum++; # putting this in the expression below causes failures. *eyeroll*
1177 $row{newrow} = $rownum % 5 == 0;
1178 push @domlist, \%row;
1179 }
1180 $page->param(domtable => \@domlist);
1181 # ACLs
1182 $page->param(maymove => ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete})));
1183 $page->param(maystatus => $permissions{admin} || $permissions{domain_edit});
1184 $page->param(maydelete => $permissions{admin} || $permissions{domain_delete});
1185
1186} elsif ($webvar{page} eq 'bulkchange') {
1187
1188 # security check - does the user have permission to access this entity?
1189 if (!check_scope(id => $webvar{destgroup}, type => 'group')) {
1190 $page->param(errmsg => "You are not permitted to make bulk changes in the requested group");
1191 goto DONEBULK;
1192 }
1193
1194 if ($webvar{bulkaction} eq 'move') {
1195 changepage(page => "domlist", errmsg => "You are not permitted to bulk-move domains")
1196 unless ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete}));
1197 my $newgname = groupName($dbh,$webvar{destgroup});
1198 $page->param(action => "Move to group $newgname");
1199 my @bulkresults;
1200 # nngh. due to alpha-sorting on the previous page, we can't use domid-numeric
1201 # order here, and since we don't have the domain names until we go around this
1202 # loop, we can't alpha-sort them here. :(
1203 foreach (keys %webvar) {
1204 my %row;
1205 next unless $_ =~ /^dom_\d+$/;
1206 # second security check - does the user have permission to meddle with this domain?
1207 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1208 $row{domerr} = "You are not permitted to make changes to the requested domain";
1209 $row{domain} = $webvar{$_};
1210 push @bulkresults, \%row;
1211 next;
1212 }
1213 $row{domain} = domainName($dbh,$webvar{$_});
1214 my ($code, $msg) = changeGroup($dbh, 'domain', $webvar{$_}, $webvar{destgroup});
1215 if ($code eq 'OK') {
1216 logaction($webvar{$_}, $session->param("username"),
1217 parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})),
1218 "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname");
1219 $row{domok} = ($code eq 'OK');
1220 } else {
1221 logaction($webvar{$_}, $session->param("username"),
1222 parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})),
1223 "Failed to move domain ".domainName($dbh, $webvar{$_})." to group $newgname: $msg")
1224 if $config{log_failures};
1225 }
1226 $row{domerr} = $msg;
1227 push @bulkresults, \%row;
1228 }
1229 $page->param(bulkresults => \@bulkresults);
1230
1231 } elsif ($webvar{bulkaction} eq 'deactivate' || $webvar{bulkaction} eq 'activate') {
1232 changepage(page => "domlist", errmsg => "You are not permitted to bulk-$webvar{bulkaction} domains")
1233 unless ($permissions{admin} || $permissions{domain_edit});
1234 $page->param(action => "$webvar{bulkaction} domains");
1235 my @bulkresults;
1236 foreach (keys %webvar) {
1237 my %row;
1238 next unless $_ =~ /^dom_\d+$/;
1239 # second security check - does the user have permission to meddle with this domain?
1240 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1241 $row{domerr} = "You are not permitted to make changes to the requested domain";
1242 $row{domain} = $webvar{$_};
1243 push @bulkresults, \%row;
1244 next;
1245 }
1246 $row{domain} = domainName($dbh,$webvar{$_});
1247##fixme: error handling on status change
1248 my $stat = zoneStatus($dbh,$webvar{$_},($webvar{bulkaction} eq 'activate' ? 'domon' : 'domoff'));
1249 logaction($webvar{$_}, $session->param("username"),
1250 parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})),
1251 "Changed domain ".domainName($dbh, $webvar{$_})." state to ".($stat ? 'active' : 'inactive'));
1252 $row{domok} = 1;
1253# $row{domok} = ($code eq 'OK');
1254# $row{domerr} = $msg;
1255 push @bulkresults, \%row;
1256 }
1257 $page->param(bulkresults => \@bulkresults);
1258
1259 } elsif ($webvar{bulkaction} eq 'delete') {
1260 changepage(page => "domlist", errmsg => "You are not permitted to bulk-delete domains")
1261 unless ($permissions{admin} || $permissions{domain_delete});
1262 $page->param(action => "$webvar{bulkaction} domains");
1263 my @bulkresults;
1264 foreach (keys %webvar) {
1265 my %row;
1266 next unless $_ =~ /^dom_\d+$/;
1267 # second security check - does the user have permission to meddle with this domain?
1268 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1269 $row{domerr} = "You are not permitted to make changes to the requested domain";
1270 $row{domain} = $webvar{$_};
1271 push @bulkresults, \%row;
1272 next;
1273 }
1274 $row{domain} = domainName($dbh,$webvar{$_});
1275 my $pargroup = parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec}));
1276 my $dom = domainName($dbh, $webvar{$_});
1277 my ($code, $msg) = delZone($dbh, $webvar{$_}, 'n');
1278 if ($code eq 'OK') {
1279 logaction($webvar{$_}, $session->param("username"), $pargroup, "Deleted domain $dom");
1280 $row{domok} = ($code eq 'OK');
1281 } else {
1282 logaction($webvar{$_}, $session->param("username"), $pargroup, "Failed to delete domain $dom: $msg")
1283 if $config{log_failures};
1284 }
1285 $row{domerr} = $msg;
1286 push @bulkresults, \%row;
1287 }
1288 $page->param(bulkresults => \@bulkresults);
1289
1290 } # move/(de)activate/delete if()
1291
1292 # not going to handle the unknown $webvar{action} else; it should not be possible in normal
1293 # operations, and anyone who meddles with the URL gets what they deserve.
1294
1295 # Yes, this is a GOTO target. PTHBTTT.
1296 DONEBULK: ;
1297
1298} elsif ($webvar{page} eq 'useradmin') {
1299
1300 if (defined($webvar{userstatus})) {
1301 # security check - does the user have permission to access this entity?
1302 my $flag = 0;
1303 foreach (@viewablegroups) {
1304 $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'user');
1305 }
1306 if ($flag && ($permissions{admin} || $permissions{user_edit})) {
1307 my $stat = userStatus($dbh,$webvar{id},$webvar{userstatus});
1308 logaction(0, $session->param("username"), parentID($dbh, (id => $webvar{id}, type => 'user')),
1309 ($stat ? 'Enabled' : 'Disabled')." ".userFullName($dbh, $webvar{id}, '%u'));
1310 $page->param(resultmsg => ($stat ? 'Enabled' : 'Disabled')." ".userFullName($dbh, $webvar{id}, '%u'));
1311 } else {
1312 $page->param(errmsg => "You are not permitted to view or change the requested user");
1313 }
1314 $uri_self =~ s/\&amp;userstatus=[^&]*//g; # clean up URL for stuffing into templates
1315 }
1316
1317 list_users();
1318
1319# Permissions!
1320 $page->param(adduser => $permissions{admin} || $permissions{user_create});
1321# should we block viewing other users? Vega blocks "editing"...
1322# NB: no "edit self" link as with groups here. maybe there should be?
1323# $page->param(eduser => $permissions{admin} || $permissions{user_edit});
1324 $page->param(deluser => $permissions{admin} || $permissions{user_delete});
1325
1326 if ($session->param('resultmsg')) {
1327 $page->param(resultmsg => $session->param('resultmsg'));
1328 $session->clear('resultmsg');
1329 }
1330 if ($session->param('warnmsg')) {
1331 $page->param(warnmsg => $session->param('warnmsg'));
1332 $session->clear('warnmsg');
1333 }
1334 if ($session->param('errmsg')) {
1335 $page->param(errmsg => $session->param('errmsg'));
1336 $session->clear('errmsg');
1337 }
1338 $page->param(curpage => $webvar{page});
1339
1340} elsif ($webvar{page} eq 'user') {
1341
1342 # All user add/edit actions fall through the same page, since there aren't
1343 # really any hard differences between the templates
1344
1345 #fill_actypelist($webvar{accttype});
1346 fill_clonemelist();
1347 my %grpperms;
1348 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1349
1350 my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl");
1351 my %noaccess;
1352 fill_permissions($grppermlist, \%grpperms, \%noaccess);
1353 $grppermlist->param(info => 1);
1354 $page->param(grpperms => $grppermlist->output);
1355
1356 $page->param(is_admin => $permissions{admin});
1357
1358 $webvar{useraction} = '' if !$webvar{useraction};
1359
1360 if ($webvar{useraction} eq 'add' or $webvar{useraction} eq 'update') {
1361
1362 $page->param(add => 1) if $webvar{useraction} eq 'add';
1363
1364 my ($code,$msg);
1365
1366 my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits
1367
1368 my %newperms; # we're going to prefill the existing permissions, so we can change them.
1369 getPermissions($dbh, 'user', $webvar{uid}, \%newperms);
1370
1371 if ($webvar{pass1} ne $webvar{pass2}) {
1372 $code = 'FAIL';
1373 $msg = "Passwords don't match";
1374 } else {
1375
1376 # assemble a permission string - far simpler than trying to pass an
1377 # indeterminate set of permission flags individually
1378
1379 # But first, we have to see if the user can add any particular
1380 # permissions; otherwise we have a priviledge escalation. Whee.
1381
1382 if (!$permissions{admin}) {
1383 my %grpperms;
1384 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1385 my $ret = comparePermissions(\%permissions, \%grpperms);
1386 if ($ret eq '<' || $ret eq '!') {
1387 # User's permissions are not a superset or equivalent to group. Can't inherit
1388 # (and include access user doesn't currently have), so we force custom.
1389 $webvar{perms_type} = 'custom';
1390 $alterperms = 1;
1391 }
1392 }
1393
1394 my $permstring;
1395 if ($webvar{perms_type} eq 'custom') {
1396 $permstring = 'C:';
1397 foreach (@permtypes) {
1398 if ($permissions{admin} || $permissions{$_}) {
1399 $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on';
1400 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
1401 }
1402 }
1403 $page->param(perm_custom => 1);
1404 } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') {
1405 $permstring = "c:$webvar{clonesrc}";
1406 getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms);
1407 $page->param(perm_clone => 1);
1408 } else {
1409 $permstring = 'i';
1410 }
1411 if ($webvar{useraction} eq 'add') {
1412 changepage(page => "useradmin", errmsg => "You do not have permission to add new users")
1413 unless $permissions{admin} || $permissions{user_create};
1414 # no scope check; user is created in the current group
1415 ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1},
1416 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring,
1417 $webvar{fname}, $webvar{lname}, $webvar{phone});
1418 logaction(0, $session->param("username"), $curgroup, "Added user $webvar{uname} (uid $msg)")
1419 if $code eq 'OK';
1420 } else {
1421 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1422 unless $permissions{admin} || $permissions{user_edit};
1423 # security check - does the user have permission to access this entity?
1424 if (!check_scope(id => $webvar{user}, type => 'user')) {
1425 changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user");
1426 }
1427# User update is icky. I'd really like to do this in one atomic
1428# operation, but that would duplicate a **lot** of code in DNSDB.pm
1429 # Allowing for changing group, but not coding web support just yet.
1430 ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1},
1431 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
1432 $webvar{fname}, $webvar{lname}, $webvar{phone});
1433 if ($code eq 'OK') {
1434 $newperms{admin} = 1 if $webvar{accttype} eq 'S';
1435 ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i'));
1436 logaction(0, $session->param("username"), $curgroup,
1437 "Updated uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})");
1438 }
1439 }
1440 }
1441
1442 if ($code eq 'OK') {
1443
1444 if ($alterperms) {
1445 changepage(page => "useradmin", warnmsg =>
1446 "You can only grant permissions you hold. $webvar{uname} ".
1447 ($webvar{useraction} eq 'add' ? 'added' : 'updated')." with reduced access.");
1448 } else {
1449 changepage(page => "useradmin", resultmsg => "Successfully ".
1450 ($webvar{useraction} eq 'add' ? 'added' : 'updated')." user $webvar{uname}");
1451 }
1452
1453 # add/update failed:
1454 } else {
1455 $page->param(add_failed => 1);
1456 $page->param(action => $webvar{useraction});
1457 $page->param(set_permgroup => 1);
1458 if ($webvar{perms_type} eq 'inherit') { # set permission class radio
1459 $page->param(perm_inherit => 1);
1460 } elsif ($webvar{perms_type} eq 'clone') {
1461 $page->param(perm_clone => 1);
1462 } else {
1463 $page->param(perm_custom => 1);
1464 }
1465 $page->param(uname => $webvar{uname});
1466 $page->param(fname => $webvar{fname});
1467 $page->param(lname => $webvar{lname});
1468 $page->param(pass1 => $webvar{pass1});
1469 $page->param(pass2 => $webvar{pass2});
1470 $page->param(errmsg => $msg);
1471 fill_permissions($page, \%newperms);
1472 fill_actypelist($webvar{accttype});
1473 fill_clonemelist();
1474 logaction(0, $session->param("username"), $curgroup, "Failed to $webvar{useraction} user ".
1475 "$webvar{uname}: $msg")
1476 if $config{log_failures};
1477 }
1478
1479 } elsif ($webvar{useraction} eq 'edit') {
1480
1481 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1482 unless $permissions{admin} || $permissions{user_edit};
1483
1484 # security check - does the user have permission to access this entity?
1485 if (!check_scope(id => $webvar{user}, type => 'user')) {
1486 changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user");
1487 }
1488
1489 $page->param(set_permgroup => 1);
1490 $page->param(action => 'update');
1491 $page->param(uid => $webvar{user});
1492 fill_clonemelist();
1493
1494 my $userinfo = getUserData($dbh,$webvar{user});
1495 fill_actypelist($userinfo->{type});
1496 # not using this yet, but adding it now means we can *much* more easily do so later.
1497 $page->param(gid => $webvar{group_id});
1498
1499 my %curperms;
1500 getPermissions($dbh, 'user', $webvar{user}, \%curperms);
1501 fill_permissions($page, \%curperms);
1502
1503 $page->param(uname => $userinfo->{username});
1504 $page->param(fname => $userinfo->{firstname});
1505 $page->param(lname => $userinfo->{lastname});
1506 $page->param(set_permgroup => 1);
1507 if ($userinfo->{inherit_perm}) {
1508 $page->param(perm_inherit => 1);
1509 } else {
1510 $page->param(perm_custom => 1);
1511 }
1512 } else {
1513 changepage(page => "useradmin", errmsg => "You are not allowed to add new users")
1514 unless $permissions{admin} || $permissions{user_create};
1515 # default is "new"
1516 $page->param(add => 1);
1517 $page->param(action => 'add');
1518 fill_permissions($page, \%grpperms);
1519 fill_actypelist();
1520 }
1521
1522} elsif ($webvar{page} eq 'deluser') {
1523
1524 changepage(page=> "useradmin", errmsg => "You are not allowed to delete users")
1525 unless $permissions{admin} || $permissions{user_delete};
1526
1527 # security check - does the user have permission to access this entity?
1528 if (!check_scope(id => $webvar{id}, type => 'user')) {
1529 changepage(page => "useradmin", errmsg => "You are not permitted to delete the requested user");
1530 }
1531
1532 $page->param(id => $webvar{id});
1533 # first pass = confirm y/n (sorta)
1534 if (!defined($webvar{del})) {
1535 $page->param(del_getconf => 1);
1536 $page->param(user => userFullName($dbh,$webvar{id}));
1537 } elsif ($webvar{del} eq 'ok') {
1538##fixme: find group id user is in (for logging) *before* we delete the user
1539##fixme: get other user data too for log
1540 my $userref = getUserData($dbh, $webvar{id});
1541 my ($code,$msg) = delUser($dbh, $webvar{id});
1542 if ($code eq 'OK') {
1543 # success. go back to the user list, do not pass "GO"
1544 # actions on users have a domain id of 0, always
1545 logaction(0, $session->param("username"), $curgroup, "Deleted user $webvar{id}/".$userref->{username}.
1546 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1547 changepage(page => "useradmin", resultmsg => "Deleted user ".$userref->{username}.
1548 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1549 } else {
1550# need to find failure mode
1551 $page->param(del_failed => 1);
1552 $page->param(errmsg => $msg);
1553 list_users($curgroup);
1554 logaction(0, $session->param("username"), $curgroup, "Failed to delete user ".
1555 "$webvar{id}/".$userref->{username}.": $msg")
1556 if $config{log_failures};
1557 }
1558 } else {
1559 # cancelled. whee!
1560 changepage(page => "useradmin");
1561 }
1562
1563} elsif ($webvar{page} eq 'dnsq') {
1564
1565 $page->param(qfor => $webvar{qfor}) if $webvar{qfor};
1566 $page->param(typelist => getTypelist($dbh, 'l', ($webvar{type} ? $webvar{type} : undef)));
1567 $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse};
1568 $page->param(resolver => $webvar{resolver}) if $webvar{resolver};
1569
1570 if ($webvar{qfor}) {
1571 my $resolv = Net::DNS::Resolver->new;
1572 $resolv->tcp_timeout(5); # make me adjustable!
1573 $resolv->udp_timeout(5); # make me adjustable!
1574 $resolv->recurse(0) if $webvar{nrecurse};
1575 $resolv->nameservers($webvar{resolver}) if $webvar{resolver};
1576 my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}});
1577 if ($query) {
1578
1579 $page->param(showresults => 1);
1580
1581 my @answer;
1582 foreach my $rr ($query->answer) {
1583# next unless $rr->type eq "A" or $rr->type eq 'NS';
1584 my %row;
1585 my ($host,$ttl,$class,$type,$data) =
1586 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s);
1587 $row{host} = $host;
1588 $row{ftype} = $type;
1589 $row{rdata} = ($type eq 'SOA' ? "<pre>$data</pre>" : $data);
1590 push @answer, \%row;
1591 }
1592 $page->param(answer => \@answer);
1593
1594 my @additional;
1595 foreach my $rr ($query->additional) {
1596# next unless $rr->type eq "A" or $rr->type eq 'NS';
1597 my %row;
1598 my ($host,$ttl,$class,$type,$data) =
1599 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1600 $row{host} = $host;
1601 $row{ftype} = $type;
1602 $row{rdata} = $data;
1603 push @additional, \%row;
1604 }
1605 $page->param(additional => \@additional);
1606
1607 my @authority;
1608 foreach my $rr ($query->authority) {
1609# next unless $rr->type eq "A" or $rr->type eq 'NS';
1610 my %row;
1611 my ($host,$ttl,$class,$type,$data) =
1612 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1613 $row{host} = $host;
1614 $row{ftype} = $type;
1615 $row{rdata} = $data;
1616 push @authority, \%row;
1617 }
1618 $page->param(authority => \@authority);
1619
1620 $page->param(usedresolver => $resolv->answerfrom);
1621 $page->param(frtype => $typemap{$webvar{type}});
1622
1623 } else {
1624 $page->param(errmsg => $resolv->errorstring);
1625 }
1626 }
1627 ## done DNS query
1628
1629} elsif ($webvar{page} eq 'axfr') {
1630
1631 changepage(page => "domlist", errmsg => "You are not permitted to import domains")
1632 unless ($permissions{admin} || $permissions{domain_create});
1633
1634 # don't need this while we've got the dropdown in the menu. hmm.
1635 fill_grouplist("grouplist");
1636
1637 $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom};
1638 $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa};
1639 $page->param(rwns => $webvar{rwns}) if $webvar{rwns};
1640 $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww.
1641 $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms};
1642
1643 # shut up warning about uninitialized variable
1644 $webvar{doit} = '' if !defined($webvar{doit});
1645
1646 if ($webvar{doit} eq 'y' && !$webvar{ifrom}) {
1647 $page->param(errmsg => "Need to set host to import from");
1648 } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) {
1649 $page->param(errmsg => "Need domains to import");
1650 } elsif ($webvar{doit} eq 'y') {
1651
1652 # security check - does the user have permission to access this entity?
1653 if (!check_scope(id => $webvar{group}, type => 'group')) {
1654 $page->param(errmsg => "You are not permitted to import domains into the requested group");
1655 goto DONEAXFR;
1656 }
1657
1658 my @domlist = split /\s+/, $webvar{importdoms};
1659 my @results;
1660 foreach my $domain (@domlist) {
1661 my %row;
1662 my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group},
1663 $webvar{zonestatus}, $webvar{rwsoa}, $webvar{rwns});
1664 $row{domok} = $msg if $code eq 'OK';
1665 if ($code eq 'WARN') {
1666 $msg =~ s|\n|<br />|g;
1667 $row{domwarn} = $msg;
1668 }
1669 if ($code eq 'FAIL') {
1670 $msg =~ s|\n|<br />\n|g;
1671 $row{domerr} = $msg;
1672 }
1673 $msg = "<br />\n".$msg if $msg =~ m|<br />|;
1674 logaction(domainID($dbh, $domain), $session->param("username"), $webvar{group},
1675 "AXFR import $domain from $webvar{ifrom} ($code): $msg");
1676 $row{domain} = $domain;
1677 push @results, \%row;
1678 }
1679 $page->param(axfrresults => \@results);
1680 }
1681
1682 # Yes, this is a GOTO target. PTBHTTT.
1683 DONEAXFR: ;
1684
1685} elsif ($webvar{page} eq 'whoisq') {
1686
1687 if ($webvar{qfor}) {
1688 use Net::Whois::Raw;
1689 use Text::Wrap;
1690
1691# caching useful?
1692#$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/";
1693#$Net::Whois::Raw::CACHE_TIME = 60;
1694
1695 my ($dominfo, $whois_server) = whois($webvar{qfor});
1696##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data
1697
1698 # le sigh. idjits spit out data without linefeeds...
1699 $Text::Wrap::columns = 88;
1700
1701# &%$@%@# high-bit crap. We should probably find a way to properly recode these
1702# instead of one-by-one. Note CGI::Simple's escapeHTML() doesn't do more than
1703# the bare minimum. :/
1704# Mainly an XHTML validation thing.
1705 $dominfo = $q->escapeHTML($dominfo);
1706 $dominfo =~ s/\xa9/\&copy;/g;
1707 $dominfo =~ s/\xae/\&reg;/g;
1708
1709 $page->param(qfor => $webvar{qfor});
1710 $page->param(dominfo => wrap('','',$dominfo));
1711 $page->param(whois_server => $whois_server);
1712 } else {
1713 $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway};
1714 }
1715
1716} elsif ($webvar{page} eq 'log') {
1717
1718##fixme put in some real log-munching stuff
1719 my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE ";
1720 my $id = $curgroup; # we do this because the group log may be called from (almost) any page,
1721 # but the others are much more limited. this is probably non-optimal.
1722
1723 if ($webvar{ltype} && $webvar{ltype} eq 'user') {
1724 $sql .= "user_id=?";
1725 $id = $webvar{id};
1726 if (!check_scope(id => $id, type => 'user')) {
1727 $page->param(errmsg => "You are not permitted to view log entries for the requested user");
1728 goto DONELOG;
1729 }
1730 $page->param(logfor => 'user '.userFullName($dbh,$id));
1731 } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') {
1732 $sql .= "domain_id=?";
1733 $id = $webvar{id};
1734 if (!check_scope(id => $id, type => 'domain')) {
1735 $page->param(errmsg => "You are not permitted to view log entries for the requested domain");
1736 goto DONELOG;
1737 }
1738 $page->param(logfor => 'domain '.domainName($dbh,$id));
1739 } elsif ($webvar{ltype} && $webvar{ltype} eq 'rdns') {
1740 $sql .= "rdns_id=?";
1741 $id = $webvar{id};
1742 if (!check_scope(id => $id, type => 'revzone')) {
1743 $page->param(errmsg => "You are not permitted to view log entries for the requested reverse zone");
1744 goto DONELOG;
1745 }
1746 $page->param(logfor => 'reverse zone '.revName($dbh,$id));
1747 } else {
1748 # Default to listing curgroup log
1749 $sql .= "group_id=?";
1750 $page->param(logfor => 'group '.groupName($dbh,$id));
1751 # note that scope limitations are applied via the change-group check;
1752 # group log is always for the "current" group
1753 }
1754##fixme:
1755# - filtering
1756# - show reverse zone column?
1757# - pagination/limiting number of records - put newest-first so user
1758# doesn't always need to go to the last page for recent activity?
1759 my $sth = $dbh->prepare($sql);
1760 $sth->execute($id);
1761 my @logbits;
1762 while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) {
1763 my %row;
1764 $row{userfname} = $name;
1765 $row{userid} = $uid;
1766 $row{useremail} = $email;
1767 ($row{logentry} = $entry) =~ s/\n/<br>\n/g;
1768 ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/);
1769 push @logbits, \%row;
1770 }
1771 $page->param(logentries => \@logbits);
1772
1773 # scope check fail target
1774 DONELOG: ;
1775
1776} # end $webvar{page} dance
1777
1778
1779# start output here so we can redirect pages.
1780print "Content-type: text/html\n\n", $header->output;
1781
1782##common bits
1783if ($webvar{page} ne 'login' && $webvar{page} ne 'badpage') {
1784 $page->param(username => $session->param("username"));
1785
1786 $page->param(group => $curgroup);
1787 $page->param(groupname => groupName($dbh,$curgroup));
1788 $page->param(logingrp => groupName($dbh,$logingroup));
1789 $page->param(logingrp_num => $logingroup);
1790
1791##fixme
1792 $page->param(mayrdns => 1);
1793
1794 $page->param(maydefrec => $permissions{admin});
1795 $page->param(mayimport => $permissions{admin} || $permissions{domain_create});
1796 $page->param(maybulk => $permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
1797
1798 $page->param(chggrps => ($permissions{admin} || $permissions{group_create} || $permissions{group_edit} || $permissions{group_delete}));
1799
1800 # group tree. should go elsewhere, probably
1801 my $tmpgrplist = fill_grptree($logingroup,$curgroup);
1802 $page->param(grptree => $tmpgrplist);
1803 $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean
1804 $page->param(inlogingrp => $curgroup == $logingroup);
1805
1806# fill in the URL-to-self
1807 $page->param(whereami => $uri_self);
1808}
1809
1810if (@debugbits) {
1811 print "<pre>\n";
1812 foreach (@debugbits) { print; }
1813 print "</pre>\n";
1814}
1815
1816# spit it out
1817print $page->output;
1818
1819if ($debugenv) {
1820 print "<div id=\"debug\">webvar keys: <pre>\n";
1821 foreach my $key (keys %webvar) {
1822 print "key: $key\tval: $webvar{$key}\n";
1823 }
1824 print "</pre>\nsession:\n<pre>\n";
1825 my $sesdata = $session->dataref();
1826 foreach my $key (keys %$sesdata) {
1827 print "key: $key\tval: ".$sesdata->{$key}."\n";
1828 }
1829 print "</pre>\nENV:\n<pre>\n";
1830 foreach my $key (keys %ENV) {
1831 print "key: $key\tval: $ENV{$key}\n";
1832 }
1833 print "</pre></div>\n";
1834}
1835
1836print $footer->output;
1837
1838# as per the docs, Just In Case
1839$session->flush();
1840
1841exit 0;
1842
1843
1844sub fill_grptree {
1845 my $root = shift;
1846 my $cur = shift;
1847 my $indent = shift || ' ';
1848
1849 my @childlist;
1850
1851 my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl');
1852 getChildren($dbh,$root,\@childlist,'immediate');
1853 return if $#childlist == -1;
1854 my @grouplist;
1855 foreach (@childlist) {
1856 my %row;
1857 $row{grpname} = groupName($dbh,$_);
1858 $row{grpnum} = $_;
1859 $row{whereami} = $uri_self;
1860 $row{curgrp} = ($_ == $cur);
1861 $row{expanded} = isParent($dbh, $_, 'group', $cur, 'group');
1862 $row{expanded} = 1 if $_ == $cur;
1863 $row{subs} = fill_grptree($_,$cur,$indent.' ');
1864 $row{indent} = $indent;
1865 push @grouplist, \%row;
1866 }
1867 $grptree->param(indent => $indent);
1868 $grptree->param(treelvl => \@grouplist);
1869 return $grptree->output;
1870}
1871
1872sub changepage {
1873 my %params = @_; # think this works the way I want...
1874
1875 # cross-site scripting fixup. instead of passing error messages by URL/form
1876 # variable, put them in the session where the nasty user can't meddle.
1877 # these are done here since it's far simpler to pass them in from wherever
1878 # than set them locally everywhere.
1879 foreach my $sessme ('resultmsg','warnmsg','errmsg') {
1880 if (my $tmp = $params{$sessme}) {
1881 $tmp =~ s|\n|<br />\n|g;
1882 $session->param($sessme, $params{$sessme});
1883 delete $params{$sessme};
1884 }
1885 }
1886
1887 # handle user check
1888 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid";
1889 foreach (sort keys %params) {
1890 $newurl .= "&$_=".$q->url_encode($params{$_});
1891 }
1892
1893 # Just In Case
1894 $session->flush();
1895
1896 print "Status: 302\nLocation: $newurl\n\n";
1897 exit;
1898} # end changepage
1899
1900sub fillsoa {
1901 my $defrec = shift;
1902 my $revrec = shift;
1903 my $id = shift;
1904 my $domname = ($defrec eq 'y' ? '' : "DOMAIN");
1905
1906 $page->param(defrec => $defrec);
1907 $page->param(revrec => $revrec);
1908
1909# i had a good reason to do this when I wrote it...
1910# $page->param(domain => $domname);
1911# $page->param(group => $DNSDB::group);
1912 $page->param(isgrp => 1) if $defrec eq 'y';
1913 $page->param(parent => ($defrec eq 'y' ? groupName($dbh, $id) :
1914 ($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)) ) );
1915
1916# defaults
1917 $page->param(defcontact => $DNSDB::def{contact});
1918 $page->param(defns => $DNSDB::def{prins});
1919 $page->param(defsoattl => $DNSDB::def{soattl});
1920 $page->param(defrefresh => $DNSDB::def{refresh});
1921 $page->param(defretry => $DNSDB::def{retry});
1922 $page->param(defexpire => $DNSDB::def{expire});
1923 $page->param(defminttl => $DNSDB::def{minttl});
1924
1925 # there are probably better ways to do this. TMTOWTDI.
1926 my %soa = getSOA($dbh,$defrec,$revrec,$id);
1927
1928 $page->param(id => $id);
1929 $page->param(recid => $soa{recid});
1930 $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins}));
1931 $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact}));
1932 $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh}));
1933 $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry}));
1934 $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire}));
1935 $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl}));
1936 $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl}));
1937}
1938
1939sub showzone {
1940 my $def = shift;
1941 my $rev = shift;
1942 my $id = shift;
1943
1944 # get the SOA first
1945 my %soa = getSOA($dbh,$def,$rev,$id);
1946
1947 $page->param(contact => $soa{contact});
1948 $page->param(prins => $soa{prins});
1949 $page->param(refresh => $soa{refresh});
1950 $page->param(retry => $soa{retry});
1951 $page->param(expire => $soa{expire});
1952 $page->param(minttl => $soa{minttl});
1953 $page->param(ttl => $soa{ttl});
1954
1955 my $foo2 = getDomRecs($dbh,$def,$rev,$id,$perpage,$webvar{offset},$sortby,$sortorder,$filter);
1956
1957 my $row = 0;
1958 foreach my $rec (@$foo2) {
1959 $rec->{type} = $typemap{$rec->{type}};
1960 $rec->{row} = $row % 2;
1961 $rec->{defrec} = $def;
1962 $rec->{revrec} = $rev;
1963 $rec->{sid} = $webvar{sid};
1964 $rec->{id} = $id;
1965 $rec->{fwdzone} = $rev eq 'n';
1966 $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV');
1967 $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV');
1968 $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV');
1969 $row++;
1970# ACLs
1971 $rec->{record_edit} = ($permissions{admin} || $permissions{record_edit});
1972 $rec->{record_delete} = ($permissions{admin} || $permissions{record_delete});
1973 }
1974 $page->param(reclist => $foo2);
1975}
1976
1977sub fill_recdata {
1978 $page->param(typelist => getTypelist($dbh, $webvar{revrec}, $webvar{type}));
1979
1980# le sigh. we may get called with many empty %webvar keys
1981 no warnings qw( uninitialized );
1982
1983##todo: allow BIND-style bare names, ASS-U-ME that the name is within the domain?
1984# prefill <domain> or DOMAIN in "Host" space for new records
1985 if ($webvar{revrec} eq 'n') {
1986 my $domroot = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid}));
1987 $page->param(name => $domroot);
1988 $page->param(address => $webvar{address});
1989 $page->param(distance => $webvar{distance})
1990 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV});
1991 $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV};
1992 $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV};
1993 } else {
1994 my $domroot = ($webvar{defrec} eq 'y' ? 'ADMINDOMAIN' : ".$config{domain}");
1995 $page->param(name => ($webvar{name} ? $webvar{name} : $domroot));
1996 my $zname = ($webvar{defrec} eq 'y' ? 'ZONE' : revName($dbh,$webvar{parentid}));
1997 $zname =~ s|\d*/\d+$||;
1998 $page->param(address => ($webvar{address} ? $webvar{address} : $zname));
1999 }
2000# retrieve the right ttl instead of falling (way) back to the hardcoded system default
2001 my %soa = getSOA($dbh,$webvar{defrec},$webvar{revrec},$webvar{parentid});
2002 $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $soa{minttl}));
2003}
2004
2005sub fill_actypelist {
2006 my $curtype = shift || 'u';
2007
2008 my @actypes;
2009
2010 my %row1 = (actypeval => 'u', actypename => 'user');
2011 $row1{typesel} = 1 if $curtype eq 'u';
2012 push @actypes, \%row1;
2013
2014 my %row2 = (actypeval => 'S', actypename => 'superuser');
2015 $row2{typesel} = 1 if $curtype eq 'S';
2016 push @actypes, \%row2;
2017
2018 $page->param(actypelist => \@actypes);
2019}
2020
2021sub fill_clonemelist {
2022 my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup");
2023 $sth->execute;
2024
2025 # shut up some warnings, but don't stomp on caller's state
2026 local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc});
2027
2028 my @clonesrc;
2029 while (my ($username,$uid) = $sth->fetchrow_array) {
2030 my %row = (
2031 username => $username,
2032 uid => $uid,
2033 selected => ($webvar{clonesrc} == $uid ? 1 : 0)
2034 );
2035 push @clonesrc, \%row;
2036 }
2037 $page->param(clonesrc => \@clonesrc);
2038}
2039
2040sub fill_fpnla {
2041 my $count = shift;
2042 if ($offset eq 'all') {
2043 $page->param(perpage => $perpage);
2044# uhm....
2045 } else {
2046 # all these bits only have sensible behaviour if offset is numeric. err, probably.
2047 if ($count > $perpage) {
2048 # if there are more results than the default, always show the "all" link
2049 $page->param(navall => 1);
2050
2051 if ($offset > 0) {
2052 $page->param(navfirst => 1);
2053 $page->param(navprev => 1);
2054 $page->param(prevoffs => $offset-1);
2055 }
2056
2057 # show "next" and "last" links if we're not on the last page of results
2058 if ( (($offset+1) * $perpage - $count) < 0 ) {
2059 $page->param(navnext => 1);
2060 $page->param(nextoffs => $offset+1);
2061 $page->param(navlast => 1);
2062 $page->param(lastoffs => int (($count-1)/$perpage));
2063 }
2064 } else {
2065 $page->param(onepage => 1);
2066 }
2067 }
2068} # end fill_fpnla()
2069
2070sub fill_pgcount {
2071 my $pgcount = shift;
2072 my $pgtype = shift;
2073 my $parent = shift;
2074
2075 # Fix display/UI bug where if you are not on the first page of the list, and
2076 # you add a search term or click one of the "starts with" links, you end up
2077 # on a page showing nothing.
2078 # For bonus points, this reverts to the original offset on clicking the "All" link (mostly)
2079 if ($offset ne 'all') {
2080 $offset-- while ($offset * $perpage) >= $pgcount;
2081 }
2082
2083 $page->param(ntot => $pgcount);
2084 $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1));
2085 $page->param(npglast => ($offset eq 'all' ? $pgcount :
2086 ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) )
2087 ));
2088 $page->param(pgtype => $pgtype);
2089 $page->param(parent => $parent);
2090 $page->param(filter => $filter);
2091} # end fill_pgcount()
2092
2093
2094sub listdomains { listzones(); } # temp
2095
2096sub listzones {
2097# ACLs
2098 $page->param(domain_create => ($permissions{admin} || $permissions{domain_create}) );
2099 $page->param(domain_edit => ($permissions{admin} || $permissions{domain_edit}) );
2100 $page->param(domain_delete => ($permissions{admin} || $permissions{domain_delete}) );
2101
2102 my @childgroups;
2103 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
2104 my $childlist = join(',',@childgroups);
2105
2106 my $count = getZoneCount($dbh, (childlist => $childlist, curgroup => $curgroup, revrec => $webvar{revrec},
2107 filter => ($filter ? $filter : undef), startwith => ($startwith ? $startwith : undef) ) );
2108
2109# fill page count and first-previous-next-last-all bits
2110 fill_pgcount($count,($webvar{revrec} eq 'n' ? 'domains' : 'revzones'),groupName($dbh,$curgroup));
2111 fill_fpnla($count);
2112
2113# sort/order
2114 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
2115 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
2116
2117 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
2118 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
2119
2120# set up the headers
2121 my @cols = (($webvar{revrec} eq 'n' ? 'domain' : 'revnet'), 'status', 'group');
2122 my %colheads = (domain => 'Domain', revnet => 'Reverse Zone', status => 'Status', group => 'Group');
2123 fill_colheads($sortby, $sortorder, \@cols, \%colheads);
2124
2125 # hack! hack! pthbttt. have to rethink the status column storage,
2126 # or inactive comes "before" active. *sigh*
2127 $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status';
2128
2129# waffle, waffle - keep state on these as well as sortby, sortorder?
2130##fixme: put this higher so the count doesn't get munched?
2131 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
2132
2133 $page->param(filter => $filter) if $filter;
2134 $page->param(searchsubs => $searchsubs) if $searchsubs;
2135
2136 $page->param(group => $curgroup);
2137
2138 my $zonelist = getZoneList($dbh, (childlist => $childlist, curgroup => $curgroup,
2139 revrec => $webvar{revrec},
2140 filter => ($filter ? $filter : undef), startwith => ($startwith ? $startwith : undef),
2141 offset => $webvar{offset}, sortby => $sortby, sortorder => $sortorder
2142 ) );
2143# probably don't need this, keeping for reference for now
2144# foreach (@$zonelist) {
2145# }
2146 $page->param(domtable => $zonelist);
2147} # end listdomains()
2148
2149
2150sub listgroups {
2151
2152# security check - does the user have permission to view this entity?
2153 if (!(grep /^$curgroup$/, @viewablegroups)) {
2154 # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere.
2155 $session->param('curgroup',$logingroup);
2156 $page->param(errmsg => "You are not permitted to view the requested group");
2157 $curgroup = $logingroup;
2158 }
2159
2160 my @childgroups;
2161 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
2162 my $childlist = join(',',@childgroups);
2163
2164 my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2165 ($startwith ? " AND group_name ~* ?" : '').
2166 ($filter ? " AND group_name ~* ?" : '');
2167 my $sth = $dbh->prepare($sql);
2168 $sth->execute(@filterargs);
2169 my ($count) = ($sth->fetchrow_array);
2170
2171# fill page count and first-previous-next-last-all bits
2172 fill_pgcount($count,"groups",'');
2173 fill_fpnla($count);
2174
2175 $page->param(gid => $curgroup);
2176
2177 $sortby = 'group';
2178# sort/order
2179 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
2180 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
2181
2182 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
2183 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
2184
2185# set up the headers
2186 my @cols = ('group','parent','nusers','ndomains');
2187 my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains');
2188 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
2189
2190# waffle, waffle - keep state on these as well as sortby, sortorder?
2191 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
2192
2193 $page->param(filter => $filter) if $filter;
2194 $page->param(searchsubs => $searchsubs) if $searchsubs;
2195
2196# munge sortby for columns in database
2197 $sortby = 'g.group_name' if $sortby eq 'group';
2198 $sortby = 'g2.group_name' if $sortby eq 'parent';
2199
2200 my @grouplist;
2201 $sql = "SELECT g.group_id, g.group_name, g2.group_name, ".
2202 "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ".
2203 "FROM groups g ".
2204 "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ".
2205 "LEFT OUTER JOIN users u ON u.group_id=g.group_id ".
2206 "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ".
2207 "WHERE g.parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').") ".
2208 ($startwith ? " AND g.group_name ~* ?" : '').
2209 ($filter ? " AND g.group_name ~* ?" : '').
2210 " GROUP BY g.group_id, g.group_name, g2.group_name ".
2211 " ORDER BY $sortby $sortorder ".
2212 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
2213 $sth = $dbh->prepare($sql);
2214 $sth->execute(@filterargs);
2215
2216 my $rownum = 0;
2217 while (my @data = $sth->fetchrow_array) {
2218 my %row;
2219 $row{groupid} = $data[0];
2220 $row{groupname} = $data[1];
2221 $row{pgroup} = $data[2];
2222 $row{nusers} = $data[3];
2223 $row{ndomains} = $data[4];
2224 $row{bg} = ($rownum++)%2;
2225 $row{sid} = $sid;
2226 $row{edgrp} = ($permissions{admin} || $permissions{group_edit});
2227 $row{delgrp} = ($permissions{admin} || $permissions{group_delete});
2228 push @grouplist, \%row;
2229 }
2230 $page->param(grouptable => \@grouplist);
2231} # end listgroups()
2232
2233
2234sub fill_grouplist {
2235 my $template_var = shift;
2236 my $cur = shift || $curgroup;
2237
2238 my @childgroups;
2239 getChildren($dbh, $logingroup, \@childgroups, 'all');
2240 my $childlist = join(',',@childgroups);
2241
2242##fixme: need to reorder list so that we can display a pseudotree in group dropdowns
2243
2244 # weesa gonna discard parent_group_id for now
2245 my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ".
2246 "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
2247 "ORDER BY group_id");
2248 $sth->execute;
2249 my @grouplist;
2250 while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) {
2251 my %row;
2252 $row{groupname} = $groupname;
2253 $row{groupval} = $groupid;
2254##fixme: need magic
2255## ... WTF?
2256# $row{defgroup} = '';
2257 $row{groupactive} = 1 if $groupid == $cur;
2258 push @grouplist, \%row;
2259 }
2260
2261 $page->param("$template_var" => \@grouplist);
2262
2263} # end fill_grouplist()
2264
2265
2266sub list_users {
2267
2268 my @childgroups;
2269 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
2270 my $childlist = join(',',@childgroups);
2271
2272 my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2273 ($startwith ? " AND username ~* ?" : '').
2274 ($filter ? " AND username ~* ?" : '');
2275 my $sth = $dbh->prepare($sql);
2276 $sth->execute(@filterargs);
2277 my ($count) = ($sth->fetchrow_array);
2278
2279# fill page count and first-previous-next-last-all bits
2280 fill_pgcount($count,"users",'');
2281 fill_fpnla($count);
2282
2283 $sortby = 'user';
2284# sort/order
2285 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
2286 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
2287
2288 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
2289 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
2290
2291# set up the headers
2292 my @cols = ('user','fname','type','group','status');
2293 my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status');
2294 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
2295
2296# waffle, waffle - keep state on these as well as sortby, sortorder?
2297 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
2298
2299 $page->param(filter => $filter) if $filter;
2300 $page->param(searchsubs => $searchsubs) if $searchsubs;
2301
2302# munge sortby for columns in database
2303 $sortby = 'u.username' if $sortby eq 'user';
2304 $sortby = 'u.type' if $sortby eq 'type';
2305 $sortby = 'g.group_name' if $sortby eq 'group';
2306 $sortby = 'u.status' if $sortby eq 'status';
2307
2308 my @userlist;
2309 $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
2310 "FROM users u ".
2311 "INNER JOIN groups g ON u.group_id=g.group_id ".
2312 "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2313 ($startwith ? " AND u.username ~* ?" : '').
2314 ($filter ? " AND u.username ~* ?" : '').
2315 " ORDER BY $sortby $sortorder ".
2316 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
2317
2318 $sth = $dbh->prepare($sql);
2319 $sth->execute(@filterargs);
2320
2321 my $rownum = 0;
2322 while (my @data = $sth->fetchrow_array) {
2323 no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name
2324 my %row;
2325 $row{userid} = $data[0];
2326 $row{username} = $data[1];
2327 $row{userfull} = $data[2];
2328 $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user");
2329 $row{usergroup} = $data[4];
2330 $row{active} = $data[5];
2331 $row{bg} = ($rownum++)%2;
2332 $row{sid} = $sid;
2333 $row{eduser} = ($permissions{admin} || $permissions{user_edit});
2334 $row{deluser} = ($permissions{admin} || $permissions{user_delete});
2335 push @userlist, \%row;
2336 }
2337 $page->param(usertable => \@userlist);
2338} # end list_users()
2339
2340
2341# Generate all of the glop necessary to add or not the appropriate marker/flag for
2342# the sort order and column in domain, user, group, and record lists
2343# Takes an array ref and hash ref
2344sub fill_colheads {
2345 my $sortby = shift;
2346 my $sortorder = shift;
2347 my $cols = shift;
2348 my $colnames = shift;
2349 my $custom = shift;
2350
2351 my @headings;
2352
2353 foreach my $col (@$cols) {
2354 my %coldata;
2355 $coldata{firstcol} = 1 if $col eq $cols->[0];
2356 $coldata{sid} = $sid;
2357 $coldata{page} = $webvar{page};
2358 $coldata{offset} = $webvar{offset} if $webvar{offset};
2359 $coldata{sortby} = $col;
2360 $coldata{colname} = $colnames->{$col};
2361 if ($col eq $sortby) {
2362 $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC');
2363 $coldata{sortorder} = $sortorder;
2364 } else {
2365 $coldata{order} = 'ASC';
2366 }
2367 if ($custom) {
2368 foreach my $ckey (keys %$custom) {
2369 $coldata{$ckey} = $custom->{$ckey};
2370 }
2371 }
2372 push @headings, \%coldata;
2373 }
2374
2375 $page->param(colheads => \@headings);
2376
2377} # end fill_colheads()
2378
2379
2380sub logaction {
2381 my $domid = shift;
2382 my $username = shift;
2383 my $groupid = shift;
2384 my $entry = shift;
2385 my $revid = shift || 0;
2386
2387##fixme: push SQL into DNSDB.pm
2388##fixme: add bits to retrieve group/domain name info to retain after entity is deleted?
2389 my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?");
2390 $sth->execute($username);
2391 my ($user_id, $fullname) = $sth->fetchrow_array;
2392
2393 $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry,rdns_id) ".
2394 "VALUES (?,?,?,?,?,?,?)") or warn $dbh->errstr;
2395 $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry,$revid) or warn $sth->errstr;
2396} # end logaction()
2397
2398
2399# we have to do this in a variety of places; let's make it consistent
2400sub fill_permissions {
2401 my $template = shift; # may need to do several sets on a single page
2402 my $permset = shift; # hashref to permissions on object
2403 my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block
2404
2405 foreach (@permtypes) {
2406 $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_}));
2407 $template->param($_ => $permset->{$_});
2408 }
2409}
2410
2411# so simple when defined as a sub instead of inline. O_o
2412sub check_scope {
2413 my %args = @_;
2414 my $entity = $args{id} || 0; # prevent the shooting of feet with SQL "... intcolumn = '' ..."
2415 my $entype = $args{type} || '';
2416
2417 if ($entype eq 'group') {
2418 return 1 if grep /^$entity$/, @viewablegroups;
2419 } else {
2420 foreach (@viewablegroups) {
2421 return 1 if isParent($dbh, $_, 'group', $entity, $entype);
2422 }
2423 }
2424}
Note: See TracBrowser for help on using the repository browser.