source: trunk/dns.cgi@ 294

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

/trunk

"Move action logging for change group default permissions" mutated
into "Move action logging for (change group default permissions),
(add user), (update user), (update user permissions)". See #35.

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