source: trunk/dns.cgi@ 239

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

/trunk

Checkpoint; domain/reverse zone list almost complete. See #26.
Still need to do active/inactive

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