source: trunk/dns.cgi@ 93

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

/trunk

Remove a couple of ##fixme notes
Log more info on user delete
Extend special-char replacement a little in WHOIS output
Comment a bit on some ##fixme's

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