source: trunk/dns.cgi@ 127

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

/trunk

UI cleanup: Remove dropdown group list from sidebar now that
the nifty collapsing group tree works

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