source: trunk/dns.cgi@ 274

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

/trunk

Flesh out most reverse zone deletion. See #26.

  • Convert delDomain() to delZone()
  • Add checks to coerce the shared-zone record types down to standard types on removal of the second parent, either way around. (IE, A+PTR will be converted to PTR if the parent domain is removed, or A if the parent revzone is removed)

Make sure to show result or error messages on the reverse zone
list page

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