source: trunk/dns.cgi@ 253

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

/trunk

Fix %webvar data propagation bug on record page - always set
defrec, revrec, and fwdzone

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