source: trunk/dns.cgi@ 143

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

/trunk

Working on user-permission ACLs. Links now show or not as appropriate

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