source: trunk/dns.cgi@ 187

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

/trunk

Check that all major actions log both successes and failures
Make coding style more consistent (always "if $code eq 'OK'/else")
Make logged failure messages a little more consistent (always "Failed <blah>")

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 83.0 KB
Line 
1#!/usr/bin/perl -w -T
2# dns/cgi-bin/dns.cgi
3###
4# SVN revision info
5# $Date: 2011-12-06 20:58:51 +0000 (Tue, 06 Dec 2011) $
6# SVN revision $Rev: 187 $
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 eq 'OK') {
376 logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $dom");
377 changepage(page => "domlist", resultmsg => "Deleted domain $dom");
378 } else {
379 logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $dom ($msg)");
380 changepage(page => "domlist", errmsg => "Error deleting domain $dom: $msg");
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 eq 'OK') {
646 if ($webvar{defrec} eq 'y') {
647##fixme: log distance for MX; log port/weight/distance for SRV
648 my $restr = "Deleted default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}";
649 logaction(0, $session->param("username"), $rec->{parid}, $restr);
650 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr);
651 } else {
652 my $restr = "Deleted record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}";
653 logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'), $restr);
654 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr);
655 }
656 } else {
657## need to find failure mode
658 if ($webvar{defrec} eq 'y') {
659 logaction(0, $session->param("username"), $rec->{parid},
660 "Failed deleting default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}',".
661 " TTL $rec->{ttl} ($msg)");
662 } else {
663 logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'),
664 "Failed deleting record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl} ($msg)");
665 }
666 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
667 errmsg => "Error deleting record: $msg");
668 }
669 } else {
670 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
671 }
672
673} elsif ($webvar{page} eq 'editsoa') {
674
675 # security check - does the user have permission to view this entity?
676 if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? 'group' : 'domain'))) {
677 changepage(page => 'domlist', errmsg => "You do not have permission to edit the ".
678 ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ".
679 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
680 }
681
682 if ($webvar{defrec} eq 'y') {
683 changepage(page => "domlist", errmsg => "You are not permitted to edit default records")
684 unless $permissions{admin};
685 } else {
686 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
687 unless ($permissions{admin} || $permissions{domain_edit});
688 }
689
690 fillsoa($webvar{defrec},$webvar{id});
691
692} elsif ($webvar{page} eq 'updatesoa') {
693
694 # security check - does the user have permission to view this entity?
695 # pass 1, record ID
696 if (!check_scope(id => $webvar{recid}, type => ($webvar{defrec} eq 'y' ? 'defrec' : 'record'))) {
697 changepage(page => 'domlist', errmsg => "You do not have permission to edit the requested SOA record");
698 }
699 # pass 2, parent (group or domain) ID
700 if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? 'group' : 'domain'))) {
701 changepage(page => 'domlist', errmsg => "You do not have permission to edit the ".
702 ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ".
703 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
704 }
705
706 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
707 unless ($permissions{admin} || $permissions{domain_edit});
708
709 # get old SOA for log
710 my %soa = getSOA($dbh,$webvar{defrec},$webvar{id});
711
712 my $sth;
713##fixme: push SQL into DNSDB.pm
714##fixme: data validation: make sure {recid} is really the SOA for {id}
715 # no domain ID, so we're editing the default SOA for a group (we don't care which one here)
716 # plus a bit of magic to update the appropriate table
717 my $sql = "UPDATE ".($webvar{defrec} eq 'y' ? "default_records" : "records").
718 " SET host=?, val=?, ttl=? WHERE record_id=?";
719 $sth = $dbh->prepare($sql);
720 $sth->execute("$webvar{prins}:$webvar{contact}",
721 "$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}",
722 $webvar{ttl},
723 $webvar{recid});
724
725 if ($sth->err) {
726 $page->param(update_failed => 1);
727 $page->param(msg => $DBI::errstr);
728 fillsoa($webvar{defrec},$webvar{id});
729 } else {
730
731 # do this in the order of "default to most common case"
732 my $loggroup;
733 my $logdomain = $webvar{id};
734 if ($webvar{defrec} eq 'y') {
735 $loggroup = $webvar{id};
736 $logdomain = 0;
737 } else {
738 $loggroup = parentID($logdomain, 'dom', 'group', $webvar{defrec});
739 }
740
741 logaction($logdomain, $session->param("username"), $loggroup,
742 "Updated ".($webvar{defrec} eq 'y' ? 'default ' : '')."SOA for ".
743 ($webvar{defrec} eq 'y' ? groupName($dbh, $webvar{id}) : domainName($dbh, $webvar{id}) ).
744 ": (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
745 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl}) to ".
746 "(ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},".
747 " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl})");
748 changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec},
749 resultmsg => "SOA record updated");
750 }
751
752} elsif ($webvar{page} eq 'grpman') {
753
754 listgroups();
755
756# Permissions!
757 $page->param(addgrp => $permissions{admin} || $permissions{group_create});
758 $page->param(edgrp => $permissions{admin} || $permissions{group_edit});
759 $page->param(delgrp => $permissions{admin} || $permissions{group_delete});
760
761 if ($session->param('resultmsg')) {
762 $page->param(resultmsg => $session->param('resultmsg'));
763 $session->clear('resultmsg');
764 }
765 if ($session->param('warnmsg')) {
766 $page->param(warnmsg => $session->param('warnmsg'));
767 $session->clear('warnmsg');
768 }
769 if ($session->param('errmsg')) {
770 $page->param(errmsg => $session->param('errmsg'));
771 $session->clear('errmsg');
772 }
773 $page->param(curpage => $webvar{page});
774
775} elsif ($webvar{page} eq 'newgrp') {
776
777 changepage(page => "grpman", errmsg => "You are not permitted to add groups")
778 unless ($permissions{admin} || $permissions{group_create});
779
780 # do.. uhh.. stuff.. if we have no webvar{action}
781 if ($webvar{action} && $webvar{action} eq 'add') {
782
783 # security check - does the user have permission to access this entity?
784 if (!check_scope(id => $webvar{pargroup}, type => 'group')) {
785 changepage(page => "grpman", errmsg => "You are not permitted to add a group to the requested parent group");
786 }
787
788 my %newperms;
789 my $alterperms = 0;
790 foreach (@permtypes) {
791 $newperms{$_} = 0;
792 if ($permissions{admin} || $permissions{$_}) {
793 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
794 } else {
795 $alterperms = 1;
796 }
797 }
798 # not gonna provide the 4th param: template-or-clone flag, just yet
799 my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms);
800 if ($code eq 'OK') {
801 logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}");
802 if ($alterperms) {
803 changepage(page => "grpman", warnmsg =>
804 "You can only grant permissions you hold. New group $webvar{newgroup} added with reduced access.");
805 } else {
806 changepage(page => "grpman", resultmsg => "Added group $webvar{newgroup}");
807 }
808 } # fallthrough else
809 logaction(0, $session->param("username"), $webvar{pargroup}, "Failed to add group $webvar{newgroup}: $msg");
810 # no point in doing extra work
811 fill_permissions($page, \%newperms);
812 $page->param(add_failed => 1);
813 $page->param(errmsg => $msg);
814 $page->param(newgroup => $webvar{newgroup});
815 fill_grouplist('pargroup',$webvar{pargroup});
816 } else {
817 fill_grouplist('pargroup',$curgroup);
818 # fill default permissions with immediate parent's current ones
819 my %parperms;
820 getPermissions($dbh, 'group', $curgroup, \%parperms);
821 fill_permissions($page, \%parperms);
822 }
823
824} elsif ($webvar{page} eq 'delgrp') {
825
826 changepage(page => "grpman", errmsg => "You are not permitted to delete groups", id => $webvar{parentid})
827 unless ($permissions{admin} || $permissions{group_delete});
828
829 # security check - does the user have permission to access this entity?
830 if (!check_scope(id => $webvar{id}, type => 'group')) {
831 changepage(page => "grpman", errmsg => "You are not permitted to delete the requested group");
832 }
833
834 $page->param(id => $webvar{id});
835 # first pass = confirm y/n (sorta)
836 if (!defined($webvar{del})) {
837 $page->param(del_getconf => 1);
838
839##fixme
840# do a check for "group has stuff in it", and splatter a big warning
841# up along with an unchecked-by-default check box to YES DAMMIT DELETE THE WHOLE THING
842
843 } elsif ($webvar{del} eq 'ok') {
844 my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it...
845 my $delparent = parentID($webvar{id}, 'group','group');
846 my ($code,$msg) = delGroup($dbh, $webvar{id});
847 if ($code eq 'OK') {
848##fixme: need to clean up log when deleting a major container
849 logaction(0, $session->param("username"), $delparent, "Deleted group $deleteme");
850 changepage(page => "grpman", resultmsg => "Deleted group $deleteme");
851 } else {
852# need to find failure mode
853 logaction(0, $session->param("username"), $delparent, "Failed to delete group $deleteme: $msg");
854 changepage(page => "grpman", errmsg => "Error deleting group $deleteme: $msg");
855 }
856 } else {
857 # cancelled. whee!
858 changepage(page => "grpman");
859 }
860 $page->param(delgroupname => groupName($dbh, $webvar{id}));
861
862} elsif ($webvar{page} eq 'edgroup') {
863
864 changepage(page => "grpman", errmsg => "You are not permitted to edit groups")
865 unless ($permissions{admin} || $permissions{group_edit});
866
867 # security check - does the user have permission to access this entity?
868 if (!check_scope(id => $webvar{gid}, type => 'group')) {
869 changepage(page => "grpman", errmsg => "You are not permitted to edit the requested group");
870 }
871
872 if ($webvar{action} eq 'updperms') {
873 # extra safety check; make sure user can't construct a URL to bypass ACLs
874 my %curperms;
875 getPermissions($dbh, 'group', $webvar{gid}, \%curperms);
876 my %chperms;
877 my $alterperms = 0;
878 foreach (@permtypes) {
879 $webvar{$_} = 0 if !defined($webvar{$_});
880 $webvar{$_} = 1 if $webvar{$_} eq 'on';
881 if ($permissions{admin} || $permissions{$_}) {
882 $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_};
883 } else {
884 $alterperms = 1;
885 $chperms{$_} = 0;
886 }
887 }
888 my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms);
889 if ($code eq 'OK') {
890 logaction(0, $session->param("username"), $webvar{gid},
891 "Updated default permissions in group $webvar{gid} (".groupName($dbh, $webvar{gid}).")");
892 if ($alterperms) {
893 changepage(page => "grpman", warnmsg =>
894 "You can only grant permissions you hold. Default permissions in group ".
895 groupName($dbh, $webvar{gid})." updated with reduced access");
896 } else {
897 changepage(page => "grpman", resultmsg =>
898 "Updated default permissions in group ".groupName($dbh, $webvar{gid}));
899 }
900 } # fallthrough else
901 logaction(0, $session->param("username"), $webvar{gid}, "Failed to update default permissions in group ".
902 groupName($dbh, $webvar{gid}).": $msg");
903 # no point in doing extra work
904 fill_permissions($page, \%chperms);
905 $page->param(errmsg => $msg);
906 }
907 $page->param(gid => $webvar{gid});
908 $page->param(grpmeddle => groupName($dbh, $webvar{gid}));
909 my %grpperms;
910 getPermissions($dbh, 'group', $webvar{gid}, \%grpperms);
911 fill_permissions($page, \%grpperms);
912
913} elsif ($webvar{page} eq 'bulkdomain') {
914 # Bulk operations on domains. Note all but group move are available on the domain list.
915
916 changepage(page => "domlist", errmsg => "You are not permitted to make bulk domain changes")
917 unless ($permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
918
919 fill_grouplist("grouplist");
920
921##fixme
922##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
923##fixme
924
925 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
926 $sth->execute($curgroup);
927 my ($count) = ($sth->fetchrow_array);
928
929 $page->param(curpage => $webvar{page});
930 fill_pgcount($count,'domains',groupName($dbh,$curgroup));
931 fill_fpnla($count);
932 $page->param(perpage => $perpage);
933
934 my @domlist;
935 my $sql = "SELECT domain_id,domain FROM domains".
936 " WHERE group_id=?".
937 " ORDER BY domain".
938 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
939 $sth = $dbh->prepare($sql);
940 $sth->execute($curgroup);
941 my $rownum = 0;
942 while (my @data = $sth->fetchrow_array) {
943 my %row;
944 $row{domid} = $data[0];
945 $row{domain} = $data[1];
946 $rownum++; # putting this in the expression below causes failures. *eyeroll*
947 $row{newrow} = $rownum % 5 == 0;
948 push @domlist, \%row;
949 }
950 $page->param(domtable => \@domlist);
951 # ACLs
952 $page->param(maymove => ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete})));
953 $page->param(maystatus => $permissions{admin} || $permissions{domain_edit});
954 $page->param(maydelete => $permissions{admin} || $permissions{domain_delete});
955
956} elsif ($webvar{page} eq 'bulkchange') {
957
958 # security check - does the user have permission to access this entity?
959 if (!check_scope(id => $webvar{destgroup}, type => 'group')) {
960 $page->param(errmsg => "You are not permitted to make bulk changes in the requested group");
961 goto DONEBULK;
962 }
963
964 if ($webvar{action} eq 'move') {
965 changepage(page => "domlist", errmsg => "You are not permitted to bulk-move domains")
966 unless ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete}));
967 my $newgname = groupName($dbh,$webvar{destgroup});
968 $page->param(action => "Move to group $newgname");
969 my @bulkresults;
970 # nngh. due to alpha-sorting on the previous page, we can't use domid-numeric
971 # order here, and since we don't have the domain names until we go around this
972 # loop, we can't alpha-sort them here. :(
973 foreach (keys %webvar) {
974 my %row;
975 next unless $_ =~ /^dom_\d+$/;
976 # second security check - does the user have permission to meddle with this domain?
977 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
978 $row{domerr} = "You are not permitted to make changes to the requested domain";
979 $row{domain} = $webvar{$_};
980 push @bulkresults, \%row;
981 next;
982 }
983 $row{domain} = domainName($dbh,$webvar{$_});
984 my ($code, $msg) = changeGroup($dbh, 'domain', $webvar{$_}, $webvar{destgroup});
985 if ($code eq 'OK') {
986 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
987 "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname");
988 $row{domok} = ($code eq 'OK');
989 } else {
990 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
991 "Failed to move domain ".domainName($dbh, $webvar{$_})." to group $newgname: $msg");
992 }
993 $row{domerr} = $msg;
994 push @bulkresults, \%row;
995 }
996 $page->param(bulkresults => \@bulkresults);
997
998 } elsif ($webvar{action} eq 'deactivate' || $webvar{action} eq 'activate') {
999 changepage(page => "domlist", errmsg => "You are not permitted to bulk-$webvar{action} domains")
1000 unless ($permissions{admin} || $permissions{domain_edit});
1001 $page->param(action => "$webvar{action} domains");
1002 my @bulkresults;
1003 foreach (keys %webvar) {
1004 my %row;
1005 next unless $_ =~ /^dom_\d+$/;
1006 # second security check - does the user have permission to meddle with this domain?
1007 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1008 $row{domerr} = "You are not permitted to make changes to the requested domain";
1009 $row{domain} = $webvar{$_};
1010 push @bulkresults, \%row;
1011 next;
1012 }
1013 $row{domain} = domainName($dbh,$webvar{$_});
1014##fixme: error handling on status change
1015 my $stat = domStatus($dbh,$webvar{$_},($webvar{action} eq 'activate' ? 'domon' : 'domoff'));
1016 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
1017 "Changed domain ".domainName($dbh, $webvar{$_})." state to ".($stat ? 'active' : 'inactive'));
1018 $row{domok} = 1;
1019# $row{domok} = ($code eq 'OK');
1020# $row{domerr} = $msg;
1021 push @bulkresults, \%row;
1022 }
1023 $page->param(bulkresults => \@bulkresults);
1024
1025 } elsif ($webvar{action} eq 'delete') {
1026 changepage(page => "domlist", errmsg => "You are not permitted to bulk-delete domains")
1027 unless ($permissions{admin} || $permissions{domain_delete});
1028 $page->param(action => "$webvar{action} domains");
1029 my @bulkresults;
1030 foreach (keys %webvar) {
1031 my %row;
1032 next unless $_ =~ /^dom_\d+$/;
1033 # second security check - does the user have permission to meddle with this domain?
1034 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1035 $row{domerr} = "You are not permitted to make changes to the requested domain";
1036 $row{domain} = $webvar{$_};
1037 push @bulkresults, \%row;
1038 next;
1039 }
1040 $row{domain} = domainName($dbh,$webvar{$_});
1041 my $pargroup = parentID($webvar{$_}, 'dom', 'group');
1042 my $dom = domainName($dbh, $webvar{$_});
1043 my ($code, $msg) = delDomain($dbh, $webvar{$_});
1044 if ($code eq 'OK') {
1045 logaction($webvar{$_}, $session->param("username"), $pargroup, "Deleted domain $dom");
1046 $row{domok} = ($code eq 'OK');
1047 } else {
1048 logaction($webvar{$_}, $session->param("username"), $pargroup, "Failed to delete domain $dom: $msg");
1049 }
1050 $row{domerr} = $msg;
1051 push @bulkresults, \%row;
1052 }
1053 $page->param(bulkresults => \@bulkresults);
1054
1055 } # move/(de)activate/delete if()
1056
1057 # not going to handle the unknown $webvar{action} else; it should not be possible in normal
1058 # operations, and anyone who meddles with the URL gets what they deserve.
1059
1060 # Yes, this is a GOTO target. PTHBTTT.
1061 DONEBULK: ;
1062
1063} elsif ($webvar{page} eq 'useradmin') {
1064
1065 if (defined($webvar{userstatus})) {
1066 # security check - does the user have permission to access this entity?
1067 my $flag = 0;
1068 foreach (@viewablegroups) {
1069 $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'user');
1070 }
1071 if ($flag) {
1072 userStatus($dbh,$webvar{id},$webvar{userstatus});
1073 } else {
1074 $page->param(errmsg => "You are not permitted to view or change the requested user");
1075 }
1076 }
1077
1078 list_users();
1079
1080# Permissions!
1081 $page->param(adduser => $permissions{admin} || $permissions{user_create});
1082# should we block viewing other users? Vega blocks "editing"...
1083# NB: no "edit self" link as with groups here. maybe there should be?
1084# $page->param(eduser => $permissions{admin} || $permissions{user_edit});
1085 $page->param(deluser => $permissions{admin} || $permissions{user_delete});
1086
1087 if ($session->param('resultmsg')) {
1088 $page->param(resultmsg => $session->param('resultmsg'));
1089 $session->clear('resultmsg');
1090 }
1091 if ($session->param('warnmsg')) {
1092 $page->param(warnmsg => $session->param('warnmsg'));
1093 $session->clear('warnmsg');
1094 }
1095 if ($session->param('errmsg')) {
1096 $page->param(errmsg => $session->param('errmsg'));
1097 $session->clear('errmsg');
1098 }
1099 $page->param(curpage => $webvar{page});
1100
1101} elsif ($webvar{page} eq 'user') {
1102
1103 # All user add/edit actions fall through the same page, since there aren't
1104 # really any hard differences between the templates
1105
1106 #fill_actypelist($webvar{accttype});
1107 fill_clonemelist();
1108 my %grpperms;
1109 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1110
1111 my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl");
1112 my %noaccess;
1113 fill_permissions($grppermlist, \%grpperms, \%noaccess);
1114 $grppermlist->param(info => 1);
1115 $page->param(grpperms => $grppermlist->output);
1116
1117 $page->param(is_admin => $permissions{admin});
1118
1119 $webvar{action} = '' if !$webvar{action};
1120
1121 if ($webvar{action} eq 'add' or $webvar{action} eq 'update') {
1122
1123 $page->param(add => 1) if $webvar{action} eq 'add';
1124
1125 my ($code,$msg);
1126
1127 my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits
1128
1129 my %newperms; # we're going to prefill the existing permissions, so we can change them.
1130 getPermissions($dbh, 'user', $webvar{uid}, \%newperms);
1131
1132 if ($webvar{pass1} ne $webvar{pass2}) {
1133 $code = 'FAIL';
1134 $msg = "Passwords don't match";
1135 } else {
1136
1137 # assemble a permission string - far simpler than trying to pass an
1138 # indeterminate set of permission flags individually
1139
1140 # But first, we have to see if the user can add any particular
1141 # permissions; otherwise we have a priviledge escalation. Whee.
1142
1143 if (!$permissions{admin}) {
1144 my %grpperms;
1145 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1146 my $ret = comparePermissions(\%permissions, \%grpperms);
1147 if ($ret eq '<' || $ret eq '!') {
1148 # User's permissions are not a superset or equivalent to group. Can't inherit
1149 # (and include access user doesn't currently have), so we force custom.
1150 $webvar{perms_type} = 'custom';
1151 $alterperms = 1;
1152 }
1153 }
1154
1155 my $permstring;
1156 if ($webvar{perms_type} eq 'custom') {
1157 $permstring = 'C:';
1158 foreach (@permtypes) {
1159 if ($permissions{admin} || $permissions{$_}) {
1160 $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on';
1161 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
1162 }
1163 }
1164 $page->param(perm_custom => 1);
1165 } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') {
1166 $permstring = "c:$webvar{clonesrc}";
1167 getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms);
1168 $page->param(perm_clone => 1);
1169 } else {
1170 $permstring = 'i';
1171 }
1172 if ($webvar{action} eq 'add') {
1173 changepage(page => "useradmin", errmsg => "You do not have permission to add new users")
1174 unless $permissions{admin} || $permissions{user_create};
1175 # no scope check; user is created in the current group
1176 ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1},
1177 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring,
1178 $webvar{fname}, $webvar{lname}, $webvar{phone});
1179 logaction(0, $session->param("username"), $curgroup, "Added user $webvar{uname} (uid $msg)")
1180 if $code eq 'OK';
1181 } else {
1182 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1183 unless $permissions{admin} || $permissions{user_edit};
1184 # security check - does the user have permission to access this entity?
1185 if (!check_scope(id => $webvar{user}, type => 'user')) {
1186 changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user");
1187 }
1188# User update is icky. I'd really like to do this in one atomic
1189# operation, but that would duplicate a **lot** of code in DNSDB.pm
1190 # Allowing for changing group, but not coding web support just yet.
1191 ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1},
1192 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
1193 $webvar{fname}, $webvar{lname}, $webvar{phone});
1194 if ($code eq 'OK') {
1195 $newperms{admin} = 1 if $webvar{accttype} eq 'S';
1196 ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i'));
1197 logaction(0, $session->param("username"), $curgroup,
1198 "Updated uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})");
1199 }
1200 }
1201 }
1202
1203 if ($code eq 'OK') {
1204
1205 if ($alterperms) {
1206 changepage(page => "useradmin", warnmsg =>
1207 "You can only grant permissions you hold. $webvar{uname} ".
1208 ($webvar{action} eq 'add' ? 'added' : 'updated')." with reduced access.");
1209 } else {
1210 changepage(page => "useradmin", resultmsg => "Successfully ".
1211 ($webvar{action} eq 'add' ? 'added' : 'updated')." user $webvar{uname}");
1212 }
1213
1214 # add/update failed:
1215 } else {
1216 $page->param(add_failed => 1);
1217 $page->param(action => $webvar{action});
1218 $page->param(set_permgroup => 1);
1219 if ($webvar{perms_type} eq 'inherit') { # set permission class radio
1220 $page->param(perm_inherit => 1);
1221 } elsif ($webvar{perms_type} eq 'clone') {
1222 $page->param(perm_clone => 1);
1223 } else {
1224 $page->param(perm_custom => 1);
1225 }
1226 $page->param(uname => $webvar{uname});
1227 $page->param(fname => $webvar{fname});
1228 $page->param(lname => $webvar{lname});
1229 $page->param(pass1 => $webvar{pass1});
1230 $page->param(pass2 => $webvar{pass2});
1231 $page->param(errmsg => $msg);
1232 fill_permissions($page, \%newperms);
1233 fill_actypelist($webvar{accttype});
1234 fill_clonemelist();
1235 logaction(0, $session->param("username"), $curgroup, "Failed to $webvar{action} user ".
1236 "$webvar{uname}: $msg");
1237 }
1238
1239 } elsif ($webvar{action} eq 'edit') {
1240
1241 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1242 unless $permissions{admin} || $permissions{user_edit};
1243
1244 # security check - does the user have permission to access this entity?
1245 if (!check_scope(id => $webvar{user}, type => 'user')) {
1246 changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user");
1247 }
1248
1249 $page->param(set_permgroup => 1);
1250 $page->param(action => 'update');
1251 $page->param(uid => $webvar{user});
1252 fill_clonemelist();
1253
1254 my $userinfo = getUserData($dbh,$webvar{user});
1255 fill_actypelist($userinfo->{type});
1256 # not using this yet, but adding it now means we can *much* more easily do so later.
1257 $page->param(gid => $webvar{group_id});
1258
1259 my %curperms;
1260 getPermissions($dbh, 'user', $webvar{user}, \%curperms);
1261 fill_permissions($page, \%curperms);
1262
1263 $page->param(uname => $userinfo->{username});
1264 $page->param(fname => $userinfo->{firstname});
1265 $page->param(lname => $userinfo->{lastname});
1266 $page->param(set_permgroup => 1);
1267 if ($userinfo->{inherit_perm}) {
1268 $page->param(perm_inherit => 1);
1269 } else {
1270 $page->param(perm_custom => 1);
1271 }
1272 } else {
1273 changepage(page => "useradmin", errmsg => "You are not allowed to add new users")
1274 unless $permissions{admin} || $permissions{user_create};
1275 # default is "new"
1276 $page->param(add => 1);
1277 $page->param(action => 'add');
1278 fill_permissions($page, \%grpperms);
1279 fill_actypelist();
1280 }
1281
1282} elsif ($webvar{page} eq 'deluser') {
1283
1284 changepage(page=> "useradmin", errmsg => "You are not allowed to delete users")
1285 unless $permissions{admin} || $permissions{user_delete};
1286
1287 # security check - does the user have permission to access this entity?
1288 if (!check_scope(id => $webvar{id}, type => 'user')) {
1289 changepage(page => "useradmin", errmsg => "You are not permitted to delete the requested user");
1290 }
1291
1292 $page->param(id => $webvar{id});
1293 # first pass = confirm y/n (sorta)
1294 if (!defined($webvar{del})) {
1295 $page->param(del_getconf => 1);
1296 $page->param(user => userFullName($dbh,$webvar{id}));
1297 } elsif ($webvar{del} eq 'ok') {
1298##fixme: find group id user is in (for logging) *before* we delete the user
1299##fixme: get other user data too for log
1300 my $userref = getUserData($dbh, $webvar{id});
1301 my ($code,$msg) = delUser($dbh, $webvar{id});
1302 if ($code eq 'OK') {
1303 # success. go back to the user list, do not pass "GO"
1304 # actions on users have a domain id of 0, always
1305 logaction(0, $session->param("username"), $curgroup, "Deleted user $webvar{id}/".$userref->{username}.
1306 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1307 changepage(page => "useradmin", resultmsg => "Deleted user ".$userref->{username}.
1308 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1309 } else {
1310# need to find failure mode
1311 $page->param(del_failed => 1);
1312 $page->param(errmsg => $msg);
1313 list_users($curgroup);
1314 logaction(0, $session->param("username"), $curgroup, "Failed to delete user ".
1315 "$webvar{id}/".$userref->{username}.": $msg");
1316 }
1317 } else {
1318 # cancelled. whee!
1319 changepage(page => "useradmin");
1320 }
1321
1322} elsif ($webvar{page} eq 'dnsq') {
1323
1324 $page->param(qfor => $webvar{qfor}) if $webvar{qfor};
1325 fill_rectypes($webvar{type} ? $webvar{type} : '', 1);
1326 $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse};
1327 $page->param(resolver => $webvar{resolver}) if $webvar{resolver};
1328
1329 if ($webvar{qfor}) {
1330 my $resolv = Net::DNS::Resolver->new;
1331 $resolv->tcp_timeout(5); # make me adjustable!
1332 $resolv->udp_timeout(5); # make me adjustable!
1333 $resolv->recurse(0) if $webvar{nrecurse};
1334 $resolv->nameservers($webvar{resolver}) if $webvar{resolver};
1335 my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}});
1336 if ($query) {
1337
1338 $page->param(showresults => 1);
1339
1340 my @answer;
1341 foreach my $rr ($query->answer) {
1342# next unless $rr->type eq "A" or $rr->type eq 'NS';
1343 my %row;
1344 my ($host,$ttl,$class,$type,$data) =
1345 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s);
1346 $row{host} = $host;
1347 $row{ftype} = $type;
1348 $row{rdata} = ($type eq 'SOA' ? "<pre>$data</pre>" : $data);
1349 push @answer, \%row;
1350 }
1351 $page->param(answer => \@answer);
1352
1353 my @additional;
1354 foreach my $rr ($query->additional) {
1355# next unless $rr->type eq "A" or $rr->type eq 'NS';
1356 my %row;
1357 my ($host,$ttl,$class,$type,$data) =
1358 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1359 $row{host} = $host;
1360 $row{ftype} = $type;
1361 $row{rdata} = $data;
1362 push @additional, \%row;
1363 }
1364 $page->param(additional => \@additional);
1365
1366 my @authority;
1367 foreach my $rr ($query->authority) {
1368# next unless $rr->type eq "A" or $rr->type eq 'NS';
1369 my %row;
1370 my ($host,$ttl,$class,$type,$data) =
1371 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1372 $row{host} = $host;
1373 $row{ftype} = $type;
1374 $row{rdata} = $data;
1375 push @authority, \%row;
1376 }
1377 $page->param(authority => \@authority);
1378
1379 $page->param(usedresolver => $resolv->answerfrom);
1380 $page->param(frtype => $typemap{$webvar{type}});
1381
1382 } else {
1383 $page->param(errmsg => $resolv->errorstring);
1384 }
1385 }
1386 ## done DNS query
1387
1388} elsif ($webvar{page} eq 'axfr') {
1389
1390 changepage(page => "domlist", errmsg => "You are not permitted to import domains")
1391 unless ($permissions{admin} || $permissions{domain_create});
1392
1393 # don't need this while we've got the dropdown in the menu. hmm.
1394 fill_grouplist("grouplist");
1395
1396 $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom};
1397 $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa};
1398 $page->param(rwns => $webvar{rwns}) if $webvar{rwns};
1399 $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww.
1400 $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms};
1401
1402 # shut up warning about uninitialized variable
1403 $webvar{doit} = '' if !defined($webvar{doit});
1404
1405 if ($webvar{doit} eq 'y' && !$webvar{ifrom}) {
1406 $page->param(errmsg => "Need to set host to import from");
1407 } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) {
1408 $page->param(errmsg => "Need domains to import");
1409 } elsif ($webvar{doit} eq 'y') {
1410
1411 # security check - does the user have permission to access this entity?
1412 if (!check_scope(id => $webvar{group}, type => 'group')) {
1413 $page->param(errmsg => "You are not permitted to import domains into the requested group");
1414 goto DONEAXFR;
1415 }
1416
1417 my @domlist = split /\s+/, $webvar{importdoms};
1418 my @results;
1419 foreach my $domain (@domlist) {
1420 my %row;
1421 my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group},
1422 $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns});
1423 $row{domok} = $msg if $code eq 'OK';
1424 if ($code eq 'WARN') {
1425 $msg =~ s|\n|<br />|g;
1426 $row{domwarn} = $msg;
1427 }
1428 if ($code eq 'FAIL') {
1429 $msg =~ s|\n|<br />\n|g;
1430 $row{domerr} = $msg;
1431 }
1432 $msg = "<br />\n".$msg if $msg =~ m|<br />|;
1433 logaction(domainID($dbh, $domain), $session->param("username"), $webvar{group},
1434 "AXFR import $domain from $webvar{ifrom} ($code): $msg");
1435 $row{domain} = $domain;
1436 push @results, \%row;
1437 }
1438 $page->param(axfrresults => \@results);
1439 }
1440
1441 # Yes, this is a GOTO target. PTBHTTT.
1442 DONEAXFR: ;
1443
1444} elsif ($webvar{page} eq 'whoisq') {
1445
1446 if ($webvar{qfor}) {
1447 use Net::Whois::Raw;
1448 use Text::Wrap;
1449
1450# caching useful?
1451#$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/";
1452#$Net::Whois::Raw::CACHE_TIME = 60;
1453
1454 my ($dominfo, $whois_server) = whois($webvar{qfor});
1455##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data
1456
1457 # le sigh. idjits spit out data without linefeeds...
1458 $Text::Wrap::columns = 88;
1459
1460# &%$@%@# high-bit crap. We should probably find a way to properly recode these
1461# instead of one-by-one. Note CGI::Simple's escapeHTML() doesn't do more than
1462# the bare minimum. :/
1463# Mainly an XHTML validation thing.
1464 $dominfo = $q->escapeHTML($dominfo);
1465 $dominfo =~ s/\xa9/\&copy;/g;
1466 $dominfo =~ s/\xae/\&reg;/g;
1467
1468 $page->param(qfor => $webvar{qfor});
1469 $page->param(dominfo => wrap('','',$dominfo));
1470 $page->param(whois_server => $whois_server);
1471 } else {
1472 $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway};
1473 }
1474
1475} elsif ($webvar{page} eq 'log') {
1476
1477##fixme put in some real log-munching stuff
1478 my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE ";
1479 my $id = $curgroup; # we do this because the group log may be called from (almost) any page,
1480 # but the others are much more limited. this is probably non-optimal.
1481
1482 if ($webvar{ltype} && $webvar{ltype} eq 'user') {
1483 $sql .= "user_id=?";
1484 $id = $webvar{id};
1485 if (!check_scope(id => $id, type => 'user')) {
1486 $page->param(errmsg => "You are not permitted to view log entries for the requested user");
1487 goto DONELOG;
1488 }
1489 $page->param(logfor => 'user '.userFullName($dbh,$id));
1490 } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') {
1491 $sql .= "domain_id=?";
1492 $id = $webvar{id};
1493 if (!check_scope(id => $id, type => 'domain')) {
1494 $page->param(errmsg => "You are not permitted to view log entries for the requested domain");
1495 goto DONELOG;
1496 }
1497 $page->param(logfor => 'domain '.domainName($dbh,$id));
1498 } else {
1499 # Default to listing curgroup log
1500 $sql .= "group_id=?";
1501 $page->param(logfor => 'group '.groupName($dbh,$id));
1502 # note that scope limitations are applied via the change-group check;
1503 # group log is always for the "current" group
1504 }
1505 my $sth = $dbh->prepare($sql);
1506 $sth->execute($id);
1507 my @logbits;
1508 while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) {
1509 my %row;
1510 $row{userfname} = $name;
1511 $row{userid} = $uid;
1512 $row{useremail} = $email;
1513 $row{logentry} = $entry;
1514 ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/);
1515 push @logbits, \%row;
1516 }
1517 $page->param(logentries => \@logbits);
1518
1519 # scope check fail target
1520 DONELOG: ;
1521
1522} # end $webvar{page} dance
1523
1524
1525# start output here so we can redirect pages.
1526print "Content-type: text/html\n\n", $header->output;
1527
1528##common bits
1529if ($webvar{page} ne 'login' && $webvar{page} ne 'badpage') {
1530 $page->param(username => $session->param("username"));
1531
1532 $page->param(group => $curgroup);
1533 $page->param(groupname => groupName($dbh,$curgroup));
1534 $page->param(logingrp => groupName($dbh,$logingroup));
1535 $page->param(logingrp_num => $logingroup);
1536
1537 $page->param(maydefrec => $permissions{admin});
1538 $page->param(mayimport => $permissions{admin} || $permissions{domain_create});
1539 $page->param(maybulk => $permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
1540
1541 $page->param(chggrps => ($permissions{admin} || $permissions{group_create} || $permissions{group_edit} || $permissions{group_delete}));
1542
1543 # group tree. should go elsewhere, probably
1544 my $tmpgrplist = fill_grptree($logingroup,$curgroup);
1545 $page->param(grptree => $tmpgrplist);
1546 $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean
1547 $page->param(inlogingrp => $curgroup == $logingroup);
1548
1549# fill in the URL-to-self
1550 $page->param(whereami => $uri_self);
1551}
1552
1553if (@debugbits) {
1554 print "<pre>\n";
1555 foreach (@debugbits) { print; }
1556 print "</pre>\n";
1557}
1558
1559# spit it out
1560print $page->output;
1561
1562if ($debugenv) {
1563 print "<div id=\"debug\">webvar keys: <pre>\n";
1564 foreach my $key (keys %webvar) {
1565 print "key: $key\tval: $webvar{$key}\n";
1566 }
1567 print "</pre>\nsession:\n<pre>\n";
1568 my $sesdata = $session->dataref();
1569 foreach my $key (keys %$sesdata) {
1570 print "key: $key\tval: ".$sesdata->{$key}."\n";
1571 }
1572 print "</pre>\nENV:\n<pre>\n";
1573 foreach my $key (keys %ENV) {
1574 print "key: $key\tval: $ENV{$key}\n";
1575 }
1576 print "</pre></div>\n";
1577}
1578
1579print $footer->output;
1580
1581# as per the docs, Just In Case
1582$session->flush();
1583
1584exit 0;
1585
1586
1587sub fill_grptree {
1588 my $root = shift;
1589 my $cur = shift;
1590 my $indent = shift || ' ';
1591
1592 my @childlist;
1593
1594 my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl');
1595 getChildren($dbh,$root,\@childlist,'immediate');
1596 return if $#childlist == -1;
1597 my @grouplist;
1598 foreach (@childlist) {
1599 my %row;
1600 $row{grpname} = groupName($dbh,$_);
1601 $row{grpnum} = $_;
1602 $row{whereami} = $uri_self;
1603 $row{curgrp} = ($_ == $cur);
1604 $row{expanded} = isParent($dbh, $_, 'group', $cur, 'group');
1605 $row{expanded} = 1 if $_ == $cur;
1606 $row{subs} = fill_grptree($_,$cur,$indent.' ');
1607 $row{indent} = $indent;
1608 push @grouplist, \%row;
1609 }
1610 $grptree->param(indent => $indent);
1611 $grptree->param(treelvl => \@grouplist);
1612 return $grptree->output;
1613}
1614
1615sub changepage {
1616 my %params = @_; # think this works the way I want...
1617
1618 # cross-site scripting fixup. instead of passing error messages by URL/form
1619 # variable, put them in the session where the nasty user can't meddle.
1620 # these are done here since it's far simpler to pass them in from wherever
1621 # than set them locally everywhere.
1622 foreach my $sessme ('resultmsg','warnmsg','errmsg') {
1623 if ($params{$sessme}) {
1624 $session->param($sessme, $params{$sessme});
1625 delete $params{$sessme};
1626 }
1627 }
1628
1629 # handle user check
1630 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid";
1631 foreach (keys %params) {
1632 $newurl .= "&$_=".$q->url_encode($params{$_});
1633 }
1634
1635 # Just In Case
1636 $session->flush();
1637
1638 print "Status: 302\nLocation: $newurl\n\n";
1639 exit;
1640} # end changepage
1641
1642sub fillsoa {
1643 my $def = shift;
1644 my $id = shift;
1645 my $domname = ($def eq 'y' ? '' : "DOMAIN");
1646
1647 $page->param(defrec => $def);
1648
1649# i had a good reason to do this when I wrote it...
1650# $page->param(domain => $domname);
1651# $page->param(group => $DNSDB::group);
1652 $page->param(isgrp => 1) if $def eq 'y';
1653 $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) );
1654
1655# defaults
1656 $page->param(defcontact => $DNSDB::def{contact});
1657 $page->param(defns => $DNSDB::def{prins});
1658 $page->param(defsoattl => $DNSDB::def{soattl});
1659 $page->param(defrefresh => $DNSDB::def{refresh});
1660 $page->param(defretry => $DNSDB::def{retry});
1661 $page->param(defexpire => $DNSDB::def{expire});
1662 $page->param(defminttl => $DNSDB::def{minttl});
1663
1664 # there are probably better ways to do this. TMTOWTDI.
1665 my %soa = getSOA($dbh,$def,$id);
1666
1667 $page->param(id => $id);
1668 $page->param(recid => $soa{recid});
1669 $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins}));
1670 $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact}));
1671 $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh}));
1672 $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry}));
1673 $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire}));
1674 $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl}));
1675 $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl}));
1676}
1677
1678sub showdomain {
1679 my $def = shift;
1680 my $id = shift;
1681
1682 # get the SOA first
1683 my %soa = getSOA($dbh,$def,$id);
1684
1685 $page->param(contact => $soa{contact});
1686 $page->param(prins => $soa{prins});
1687 $page->param(refresh => $soa{refresh});
1688 $page->param(retry => $soa{retry});
1689 $page->param(expire => $soa{expire});
1690 $page->param(minttl => $soa{minttl});
1691 $page->param(ttl => $soa{ttl});
1692
1693 my $foo2 = getDomRecs($dbh,$def,$id,$perpage,$webvar{offset},$sortby,$sortorder,$filter);
1694
1695 my $row = 0;
1696 foreach my $rec (@$foo2) {
1697 $rec->{type} = $typemap{$rec->{type}};
1698 $rec->{row} = $row % 2;
1699 $rec->{defrec} = $def;
1700 $rec->{sid} = $webvar{sid};
1701 $rec->{id} = $id;
1702 $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV');
1703 $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV');
1704 $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV');
1705 $row++;
1706# ACLs
1707 $rec->{record_edit} = ($permissions{admin} || $permissions{record_edit});
1708 $rec->{record_delete} = ($permissions{admin} || $permissions{record_delete});
1709 }
1710 $page->param(reclist => $foo2);
1711}
1712
1713# fill in record type list on add/update/edit record template
1714sub fill_rectypes {
1715 my $type = shift || $reverse_typemap{A};
1716 my $soaflag = shift || 0;
1717
1718 my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder");
1719 $sth->execute;
1720 my @typelist;
1721 while (my ($rval,$rname) = $sth->fetchrow_array()) {
1722 my %row = ( recval => $rval, recname => $rname );
1723 $row{tselect} = 1 if $rval == $type;
1724 push @typelist, \%row;
1725 }
1726 if ($soaflag) {
1727 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
1728 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
1729 push @typelist, \%row;
1730 }
1731 $page->param(typelist => \@typelist);
1732} # fill_rectypes
1733
1734sub fill_recdata {
1735 fill_rectypes($webvar{type});
1736
1737# le sigh. we may get called with many empty %webvar keys
1738 no warnings qw( uninitialized );
1739
1740##todo: allow BIND-style bare names, ASS-U-ME that the name is within the domain?
1741# prefill <domain> or DOMAIN in "Host" space for new records
1742 my $domroot = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid}));
1743 $page->param(name => $domroot);
1744 $page->param(address => $webvar{address});
1745 $page->param(distance => $webvar{distance})
1746 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV});
1747 $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV};
1748 $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV};
1749# retrieve the right ttl instead of falling (way) back to the hardcoded system default
1750 my %soa = getSOA($dbh,$webvar{defrec},$webvar{parentid});
1751 $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $soa{minttl}));
1752}
1753
1754sub fill_actypelist {
1755 my $curtype = shift || 'u';
1756
1757 my @actypes;
1758
1759 my %row1 = (actypeval => 'u', actypename => 'user');
1760 $row1{typesel} = 1 if $curtype eq 'u';
1761 push @actypes, \%row1;
1762
1763 my %row2 = (actypeval => 'S', actypename => 'superuser');
1764 $row2{typesel} = 1 if $curtype eq 'S';
1765 push @actypes, \%row2;
1766
1767 $page->param(actypelist => \@actypes);
1768}
1769
1770sub fill_clonemelist {
1771 my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup");
1772 $sth->execute;
1773
1774 # shut up some warnings, but don't stomp on caller's state
1775 local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc});
1776
1777 my @clonesrc;
1778 while (my ($username,$uid) = $sth->fetchrow_array) {
1779 my %row = (
1780 username => $username,
1781 uid => $uid,
1782 selected => ($webvar{clonesrc} == $uid ? 1 : 0)
1783 );
1784 push @clonesrc, \%row;
1785 }
1786 $page->param(clonesrc => \@clonesrc);
1787}
1788
1789sub fill_fpnla {
1790 my $count = shift;
1791 if ($offset eq 'all') {
1792 $page->param(perpage => $perpage);
1793# uhm....
1794 } else {
1795 # all these bits only have sensible behaviour if offset is numeric. err, probably.
1796 if ($count > $perpage) {
1797 # if there are more results than the default, always show the "all" link
1798 $page->param(navall => 1);
1799
1800 if ($offset > 0) {
1801 $page->param(navfirst => 1);
1802 $page->param(navprev => 1);
1803 $page->param(prevoffs => $offset-1);
1804 }
1805
1806 # show "next" and "last" links if we're not on the last page of results
1807 if ( (($offset+1) * $perpage - $count) < 0 ) {
1808 $page->param(navnext => 1);
1809 $page->param(nextoffs => $offset+1);
1810 $page->param(navlast => 1);
1811 $page->param(lastoffs => int (($count-1)/$perpage));
1812 }
1813 } else {
1814 $page->param(onepage => 1);
1815 }
1816 }
1817} # end fill_fpnla()
1818
1819sub fill_pgcount {
1820 my $pgcount = shift;
1821 my $pgtype = shift;
1822 my $parent = shift;
1823
1824 # Fix display/UI bug where if you are not on the first page of the list, and
1825 # you add a search term or click one of the "starts with" links, you end up
1826 # on a page showing nothing.
1827 # For bonus points, this reverts to the original offset on clicking the "All" link (mostly)
1828 if ($offset ne 'all') {
1829 $offset-- while ($offset * $perpage) >= $pgcount;
1830 }
1831
1832 $page->param(ntot => $pgcount);
1833 $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1));
1834 $page->param(npglast => ($offset eq 'all' ? $pgcount :
1835 ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) )
1836 ));
1837 $page->param(pgtype => $pgtype);
1838 $page->param(parent => $parent);
1839 $page->param(filter => $filter);
1840} # end fill_pgcount()
1841
1842sub listdomains {
1843
1844# ACLs
1845 $page->param(domain_create => ($permissions{admin} || $permissions{domain_create}) );
1846 $page->param(domain_edit => ($permissions{admin} || $permissions{domain_edit}) );
1847 $page->param(domain_delete => ($permissions{admin} || $permissions{domain_delete}) );
1848
1849 my @childgroups;
1850 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1851 my $childlist = join(',',@childgroups);
1852
1853 my $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1854 ($startwith ? " AND domain ~* ?" : '').
1855 ($filter ? " AND domain ~* ?" : '');
1856 my $sth = $dbh->prepare($sql);
1857 $sth->execute(@filterargs);
1858 my ($count) = $sth->fetchrow_array;
1859
1860# fill page count and first-previous-next-last-all bits
1861 fill_pgcount($count,"domains",groupName($dbh,$curgroup));
1862 fill_fpnla($count);
1863
1864# sort/order
1865 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1866 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1867
1868 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1869 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1870
1871# set up the headers
1872 my @cols = ('domain', 'status', 'group');
1873 my %colheads = (domain => 'Domain', status => 'Status', group => 'Group');
1874 fill_colheads($sortby, $sortorder, \@cols, \%colheads);
1875
1876 # hack! hack! pthbttt. have to rethink the status column storage,
1877 # or inactive comes "before" active. *sigh*
1878 $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status';
1879
1880# waffle, waffle - keep state on these as well as sortby, sortorder?
1881 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1882
1883 $page->param(filter => $filter) if $filter;
1884 $page->param(searchsubs => $searchsubs) if $searchsubs;
1885
1886##fixme
1887##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
1888##fixme
1889
1890 $page->param(group => $curgroup);
1891 my @domlist;
1892 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1893 " INNER JOIN groups ON domains.group_id=groups.group_id".
1894 " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1895 ($startwith ? " AND domain ~* ?" : '').
1896 ($filter ? " AND domain ~* ?" : '').
1897 " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $sortby).
1898 " $sortorder ".($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1899 $sth = $dbh->prepare($sql);
1900 $sth->execute(@filterargs);
1901 my $rownum = 0;
1902 while (my @data = $sth->fetchrow_array) {
1903 my %row;
1904 $row{domainid} = $data[0];
1905 $row{domain} = $data[1];
1906 $row{status} = ($data[2] ? 'Active' : 'Inactive');
1907 $row{group} = $data[3];
1908 $row{bg} = ($rownum++)%2;
1909 $row{mkactive} = !$data[2];
1910 $row{sid} = $sid;
1911 $row{offset} = $offset;
1912# ACLs
1913 $row{domain_edit} = ($permissions{admin} || $permissions{domain_edit});
1914 $row{domain_delete} = ($permissions{admin} || $permissions{domain_delete});
1915 push @domlist, \%row;
1916 }
1917 $page->param(domtable => \@domlist);
1918} # end listdomains()
1919
1920
1921sub listgroups {
1922
1923# security check - does the user have permission to view this entity?
1924 if (!(grep /^$curgroup$/, @viewablegroups)) {
1925 # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere.
1926 $session->param('curgroup',$logingroup);
1927 $page->param(errmsg => "You are not permitted to view the requested group");
1928 $curgroup = $logingroup;
1929 }
1930
1931 my @childgroups;
1932 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1933 my $childlist = join(',',@childgroups);
1934
1935 my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1936 ($startwith ? " AND group_name ~* ?" : '').
1937 ($filter ? " AND group_name ~* ?" : '');
1938 my $sth = $dbh->prepare($sql);
1939 $sth->execute(@filterargs);
1940 my ($count) = ($sth->fetchrow_array);
1941
1942# fill page count and first-previous-next-last-all bits
1943 fill_pgcount($count,"groups",'');
1944 fill_fpnla($count);
1945
1946 $page->param(gid => $curgroup);
1947
1948 $sortby = 'group';
1949# sort/order
1950 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1951 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1952
1953 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1954 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1955
1956# set up the headers
1957 my @cols = ('group','parent','nusers','ndomains');
1958 my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains');
1959 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1960
1961# waffle, waffle - keep state on these as well as sortby, sortorder?
1962 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1963
1964 $page->param(filter => $filter) if $filter;
1965 $page->param(searchsubs => $searchsubs) if $searchsubs;
1966
1967# munge sortby for columns in database
1968 $sortby = 'g.group_name' if $sortby eq 'group';
1969 $sortby = 'g2.group_name' if $sortby eq 'parent';
1970
1971 my @grouplist;
1972 $sql = "SELECT g.group_id, g.group_name, g2.group_name, ".
1973 "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ".
1974 "FROM groups g ".
1975 "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ".
1976 "LEFT OUTER JOIN users u ON u.group_id=g.group_id ".
1977 "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ".
1978 "WHERE g.parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').") ".
1979 ($startwith ? " AND g.group_name ~* ?" : '').
1980 ($filter ? " AND g.group_name ~* ?" : '').
1981 " GROUP BY g.group_id, g.group_name, g2.group_name ".
1982 " ORDER BY $sortby $sortorder ".
1983 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1984 $sth = $dbh->prepare($sql);
1985 $sth->execute(@filterargs);
1986
1987 my $rownum = 0;
1988 while (my @data = $sth->fetchrow_array) {
1989 my %row;
1990 $row{groupid} = $data[0];
1991 $row{groupname} = $data[1];
1992 $row{pgroup} = $data[2];
1993 $row{nusers} = $data[3];
1994 $row{ndomains} = $data[4];
1995 $row{bg} = ($rownum++)%2;
1996 $row{sid} = $sid;
1997 $row{edgrp} = ($permissions{admin} || $permissions{group_edit});
1998 $row{delgrp} = ($permissions{admin} || $permissions{group_delete});
1999 push @grouplist, \%row;
2000 }
2001 $page->param(grouptable => \@grouplist);
2002} # end listgroups()
2003
2004
2005sub fill_grouplist {
2006 my $template_var = shift;
2007 my $cur = shift || $curgroup;
2008
2009 my @childgroups;
2010 getChildren($dbh, $logingroup, \@childgroups, 'all');
2011 my $childlist = join(',',@childgroups);
2012
2013##fixme: need to reorder list so that we can display a pseudotree in group dropdowns
2014
2015 # weesa gonna discard parent_group_id for now
2016 my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ".
2017 "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
2018 "ORDER BY group_id");
2019 $sth->execute;
2020 my @grouplist;
2021 while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) {
2022 my %row;
2023 $row{groupname} = $groupname;
2024 $row{groupval} = $groupid;
2025##fixme: need magic
2026## ... WTF?
2027# $row{defgroup} = '';
2028 $row{groupactive} = 1 if $groupid == $cur;
2029 push @grouplist, \%row;
2030 }
2031
2032 $page->param("$template_var" => \@grouplist);
2033
2034} # end fill_grouplist()
2035
2036
2037sub list_users {
2038
2039 my @childgroups;
2040 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
2041 my $childlist = join(',',@childgroups);
2042
2043 my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2044 ($startwith ? " AND username ~* ?" : '').
2045 ($filter ? " AND username ~* ?" : '');
2046 my $sth = $dbh->prepare($sql);
2047 $sth->execute(@filterargs);
2048 my ($count) = ($sth->fetchrow_array);
2049
2050# fill page count and first-previous-next-last-all bits
2051 fill_pgcount($count,"users",'');
2052 fill_fpnla($count);
2053
2054 $sortby = 'user';
2055# sort/order
2056 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
2057 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
2058
2059 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
2060 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
2061
2062# set up the headers
2063 my @cols = ('user','fname','type','group','status');
2064 my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status');
2065 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
2066
2067# waffle, waffle - keep state on these as well as sortby, sortorder?
2068 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
2069
2070 $page->param(filter => $filter) if $filter;
2071 $page->param(searchsubs => $searchsubs) if $searchsubs;
2072
2073# munge sortby for columns in database
2074 $sortby = 'u.username' if $sortby eq 'user';
2075 $sortby = 'u.type' if $sortby eq 'type';
2076 $sortby = 'g.group_name' if $sortby eq 'group';
2077 $sortby = 'u.status' if $sortby eq 'status';
2078
2079 my @userlist;
2080 $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
2081 "FROM users u ".
2082 "INNER JOIN groups g ON u.group_id=g.group_id ".
2083 "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2084 ($startwith ? " AND u.username ~* ?" : '').
2085 ($filter ? " AND u.username ~* ?" : '').
2086 " ORDER BY $sortby $sortorder ".
2087 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
2088
2089 $sth = $dbh->prepare($sql);
2090 $sth->execute(@filterargs);
2091
2092 my $rownum = 0;
2093 while (my @data = $sth->fetchrow_array) {
2094 no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name
2095 my %row;
2096 $row{userid} = $data[0];
2097 $row{username} = $data[1];
2098 $row{userfull} = $data[2];
2099 $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user");
2100 $row{usergroup} = $data[4];
2101 $row{active} = $data[5];
2102 $row{bg} = ($rownum++)%2;
2103 $row{sid} = $sid;
2104 $row{eduser} = ($permissions{admin} || $permissions{user_edit});
2105 $row{deluser} = ($permissions{admin} || $permissions{user_delete});
2106 push @userlist, \%row;
2107 }
2108 $page->param(usertable => \@userlist);
2109} # end list_users()
2110
2111
2112# Generate all of the glop necessary to add or not the appropriate marker/flag for
2113# the sort order and column in domain, user, group, and record lists
2114# Takes an array ref and hash ref
2115sub fill_colheads {
2116 my $sortby = shift;
2117 my $sortorder = shift;
2118 my $cols = shift;
2119 my $colnames = shift;
2120 my $custom = shift;
2121
2122 my @headings;
2123
2124 foreach my $col (@$cols) {
2125 my %coldata;
2126 $coldata{firstcol} = 1 if $col eq $cols->[0];
2127 $coldata{sid} = $sid;
2128 $coldata{page} = $webvar{page};
2129 $coldata{offset} = $webvar{offset} if $webvar{offset};
2130 $coldata{sortby} = $col;
2131 $coldata{colname} = $colnames->{$col};
2132 if ($col eq $sortby) {
2133 $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC');
2134 $coldata{sortorder} = $sortorder;
2135 } else {
2136 $coldata{order} = 'ASC';
2137 }
2138 if ($custom) {
2139 foreach my $ckey (keys %$custom) {
2140 $coldata{$ckey} = $custom->{$ckey};
2141 }
2142 }
2143 push @headings, \%coldata;
2144 }
2145
2146 $page->param(colheads => \@headings);
2147
2148} # end fill_colheads()
2149
2150
2151sub logaction {
2152 my $domid = shift;
2153 my $username = shift;
2154 my $groupid = shift;
2155 my $entry = shift;
2156
2157##fixme: push SQL into DNSDB.pm
2158##fixme: add bits to retrieve group/domain name info to retain after entity is deleted?
2159 my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?");
2160 $sth->execute($username);
2161 my ($user_id, $fullname) = $sth->fetchrow_array;
2162
2163 $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) ".
2164 "VALUES (?,?,?,?,?,?)") or warn $dbh->errstr;
2165 $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry) or warn $sth->errstr;
2166} # end logaction()
2167
2168
2169##fixme: generalize to return appropriate id on all cases (ie, use $partype)
2170sub parentID {
2171 my $id = shift;
2172 my $idtype = shift;
2173 my $partype = shift;
2174 my $defrec = shift || '';
2175
2176 my $sql = '';
2177
2178 if ($idtype eq 'dom') {
2179 return $id if $defrec eq 'y'; # "domain" + default records, we're really looking at a group.
2180 $sql = "SELECT group_id FROM domains WHERE domain_id=?";
2181 } elsif ($idtype eq 'rec') {
2182 if ($defrec eq 'y') {
2183 $sql = "SELECT group_id FROM default_records WHERE record_id=?";
2184 } else {
2185 $sql = "SELECT d.group_id FROM domains d".
2186 " INNER JOIN records r ON d.domain_id=r.domain_id".
2187 " WHERE r.record_id=?";
2188 }
2189 } elsif ($idtype eq 'group') {
2190 $sql = "SELECT parent_group_id FROM groups WHERE group_id=?";
2191 } elsif ($idtype eq 'user') {
2192 $sql = "SELECT group_id FROM users WHERE user_id=?";
2193 } else {
2194 return "FOO", "BAR"; # can't get here.... we think.
2195 }
2196 my $sth = $dbh->prepare($sql);
2197 $sth->execute($id);
2198 my ($retid) = $sth->fetchrow_array;
2199 return $retid if $retid;
2200 # ahh! fall of the edge of the world if things went sideways
2201 ##fixme: really need to do a little more error handling, I think
2202} # end parentID()
2203
2204
2205# we have to do this in a variety of places; let's make it consistent
2206sub fill_permissions {
2207 my $template = shift; # may need to do several sets on a single page
2208 my $permset = shift; # hashref to permissions on object
2209 my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block
2210
2211 foreach (@permtypes) {
2212 $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_}));
2213 $template->param($_ => $permset->{$_});
2214 }
2215}
2216
2217# so simple when defined as a sub instead of inline. O_o
2218sub check_scope {
2219 my %args = @_;
2220 my $entity = $args{id} || 0; # prevent the shooting of feet with SQL "... intcolumn = '' ..."
2221 my $entype = $args{type} || '';
2222
2223 if ($entype eq 'group') {
2224 return 1 if grep /^$entity$/, @viewablegroups;
2225 } else {
2226 foreach (@viewablegroups) {
2227 return 1 if isParent($dbh, $_, 'group', $entity, $entype);
2228 }
2229 }
2230}
Note: See TracBrowser for help on using the repository browser.