source: trunk/dns.cgi@ 207

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

/trunk

Fix overloaded-$webvar{action}-related buglet - changing the default
group can cause the page to mutate due to template/page overloading.
Reported by Reid Sutherland on the "Edit user" page, when clicking
a group to change the default group.

Group edit and bulk domain change pages tweaked although the impact
is limited to changing the starting data, not the page operation.

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