source: trunk/dns.cgi@ 148

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

/trunk

UI tweak for group update

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