source: trunk/dns.cgi@ 90

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

/trunk

Checkpoint

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