source: trunk/dns.cgi@ 198

Last change on this file since 198 was 198, checked in by Kris Deugau, 12 years ago

/trunk

Finish Vega-equivalent mail notifications (domain creation)

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