source: trunk/dns.cgi@ 212

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

/trunk

The lets-call-it-a-release commit, for sure this time!
Fill in some lingering details in the UI - company name in the
header, version on the login and footer, identify *what* you're
logging in to on the login page.

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