source: trunk/dns.cgi@ 235

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

/trunk

Validation for addRec() now functional with %validators hash
Several more tweaks and cleanups in A, AAAA, PTR, and A/AAAA+PTR records
dns.cgi now reports WARN conditions on add record
Minor typos in reclist.tmpl and record.tmpl fixed

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