source: trunk/dns.cgi@ 153

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

/trunk

Start adding scope checks so that users can't casually access
data they have no way of linking to legitimately

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