source: trunk/dns.cgi@ 225

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

/trunk

Move some SQL into DNSDB.pm (see #1):
fill_rectypes is now getTypelist, and updated for reverse zones
and the custom DNS record types
Also apply a couple of small nitpick fixes in formatting and spelling

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