source: trunk/dns.cgi@ 91

Last change on this file since 91 was 91, checked in by Kris Deugau, 14 years ago

/trunk

SQL tabledef update:

  • Tweak log table definition to cope with looooong entries (mainly from AXFR warnings)

DNSDB.pm:

  • Add domainID and getRecCount subs in DNSDB
  • Return more user-friendly error on attempting to add a domain with no name
  • Nitpick-tweak DB calls and SQL formatting in domainName()
  • Replace placeholderish OK message in importAXFR()

dns.cgi:

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