source: trunk/dns.cgi@ 243

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

/trunk

Fixing up delRec() and caller to handle reverse records. See #26.

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