source: trunk/dns.cgi@ 237

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

/trunk

Checkpoint - almost finished updating domain list code to handle
reverse zones as well (see #26).
Still needs some UI polish in the template (flags to convert
"domain" to "reverse zone"), and possibly bringing some of the
HTML::Template-feeding bits for the actual list back out of the
DNSDB.pm sub after pushing the SQL in there (see #1).

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