source: trunk/dns.cgi@ 153

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

/trunk

Start adding scope checks so that users can't casually access
data they have no way of linking to legitimately

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