source: branches/stable/dns.cgi@ 366

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

/branches/stable

Hand-port login fix from r316, bump release version numbers

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