source: trunk/dns.cgi@ 218

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

/trunk

Found some not-so-little things missing for a tarball

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