source: trunk/dns.cgi@ 159

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

/trunk

Prevent out-of-domain records from being added by appending the domain

if it's not already there. Append DOMAIN for group default records.

Remove some stale ##fixme/todo comments
Remove a stray bare "return" causing record updates to not get logged

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