source: trunk/dns.cgi@ 146

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

/trunk

Completed ACL checks on deleting a user
Present a "success" message on deleting a user rather than just
silently dropping you back to the useradmin page

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