source: trunk/dns.cgi@ 197

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

/trunk

More log behaviour tweaking

  • fix broken detail-logging of MX/SRV records on record add
  • add flag to control failure logging
  • fix broken user fullname grabber in _log

Tweak config loading with a few new options

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