source: branches/stable/dns.cgi@ 450

Last change on this file since 450 was 438, checked in by Kris Deugau, 12 years ago

/branches/stable

*sigh* Another fine brown-paper-bag commit.

  • $webvar{forcettl}/{newttl} passing truncated due to not watching what needed to be trimmed from the merge
  • TTL override needed to reach the actual insert processing; this was already reworked on /trunk due to other changes

And just for good measure, bump the patch version for release.

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