source: trunk/dns.cgi@ 229

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

/trunk

Missed a couple of fragments from first-pass reverse zone integration on addRec()
See #26

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