source: trunk/dns.cgi@ 214

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

/trunk

Fix lurking bug of sorts where the session ID and page could get lost
on some links. Observed to affect the WHOIS and DNS query *results*
pages, on the group tree - but not on the initial query page.

May have theoretically affected other pages, although some of them
bypass the bug due to use of changepage() with the 302 redirect

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