source: trunk/dns.cgi@ 276

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

/trunk

Convert domStatus() and caller to zoneStatus() for reverse DNS
Add status change to revzones page handling
See #26

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