source: trunk/dns.cgi@ 82

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

/trunk

Forgot to include dns.cgi change to include current-group gid

in link to edit current group

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