source: trunk/dns.cgi@ 186

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

/trunk

Fix isParent() to return correct results for checks where the
checked parent is not the immediate parent of the checked child.
This triggered a UI glitch where the group tree was not properly
expanded to the current group if a sub-sub-sub group of the
login group was set as the current group.

Clean up stale comments in fill_grptree

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