source: trunk/dns.cgi@ 67

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

/trunk

checkpoint
Add user ACL handling nearing function
Add user/edit user pages merged; they're next to identical anyway
Group list images tweaked with proper "alpha channel", CSS fiddled again

  • final arrangement will probably be a couple of small triangles; pointing right for an expandable group, down for an expanded one

Option to add user to a different group removed

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