source: branches/stable/dns.cgi@ 275

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

/branches/stable

Merge /trunk r262 forward for release. Merge was clean.

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