source: trunk/dns.cgi@ 112

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

/trunk

Mostly complete functionality of bulk group move

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