source: trunk/dns.cgi@ 259

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

/trunk

More fixing on _log() and its callers and its caller's information
sources - general logic and behaviour cleanup this time

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