source: trunk/dns.cgi@ 58

Last change on this file since 58 was 57, checked in by Kris Deugau, 15 years ago

/trunk

Checkpoint, cleanup and normalization (still, again)

  • fiddle searchsubs handling so it really goes away if you uncheck it. maybe. With a perfect browser. In the light of a full harvest moon while 13 virgins do the chicken dance on top of five maypoles with ....
  • Collect global $webvar{action} actions into one logical segment
  • Shuffle $webvar{page} segments to be close to logically similar blocks
  • Get logging stubbed and mostly fleshed out
  • Fix fumbled group selection in various lists
  • Remove a stale template
  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 42.8 KB
Line 
1#!/usr/bin/perl -w -T
2# dns/cgi-bin/dns.cgi
3###
4# SVN revision info
5# $Date: 2010-01-13 22:46:21 +0000 (Wed, 13 Jan 2010) $
6# SVN revision $Rev: 57 $
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 = 0;
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 $webvar{startwith};
71$session->param($webvar{page}.'filter', $webvar{filter}) if $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
79push @debugbits, "foo<br>\n" if defined($webvar{searchsubs});
80
81# nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet
82
83my $header = HTML::Template->new(filename => "$templatedir/header.tmpl");
84my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl");
85
86# default
87#my $perpage = 15;
88my $perpage = 3;
89my $offset = ($webvar{offset} ? $webvar{offset} : 0);
90
91# NB: these must match the field name and SQL ascend/descend syntax respectively
92my $sortby = "domain";
93my $sortorder = "ASC";
94
95my ($dbh,$msg) = connectDB("dnsdb","dnsdb","secret","dbhost");
96#my $dbh = DBI->connect("DBI:mysql:database=vegadns","vegadns","secret",
97# { AutoCommit => 0 }) or die $DBI::errstr;
98
99##fixme. PLEASE! <G>
100print $msg if !$dbh;
101
102# fiddle hardcoded "defaults" as per system/user (?) prefs
103initGlobals($dbh);
104
105# handle login redirect
106if ($webvar{action}) {
107 if ($webvar{action} eq 'login') {
108 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
109 $sth->execute($webvar{username});
110 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
111 $webvar{loginfailed} = 1 if !defined($uid);
112
113 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
114 $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1);
115 } else {
116 $webvar{loginfailed} = 1 if $pass ne $webvar{password};
117 }
118
119 # set session bits
120 $session->param('logingroup',$gid);
121 $session->param('curgroup',$gid);
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
143
144## Default page is a login page
145#my $page; # to be initialized as an HTML::Template entity sooner or later
146
147
148# decide which page to spit out...
149$webvar{page} = 'login' if !$webvar{page};
150#if (!$webvar{page}) {
151# $page = HTML::Template->new(filename => "$templatedir/login.tmpl");
152#} else {
153#}
154
155my $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl");
156
157$page->param(sid => $sid);
158
159if ($webvar{page} eq 'login') {
160
161 $page->param(loginfailed => 1) if $webvar{loginfailed};
162##fixme: set up session init to actually *check* for session timeout
163 $page->param(timeout => 1) if $webvar{sesstimeout};
164
165} elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') {
166
167# hmm. seeing problems in some possibly-not-so-corner cases.
168# this currently only handles "domain on", "domain off"
169 if (defined($webvar{action})) {
170 domStatus($dbh,$webvar{id},$webvar{action});
171 }
172
173 $page->param(curpage => $webvar{page});
174
175 listdomains();
176
177} elsif ($webvar{page} eq 'newdomain') {
178
179 # hmm. nothing to do here?
180 # - group list is filled by the same bit that fills the group list in the menu
181
182} elsif ($webvar{page} eq 'adddomain') {
183
184 my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0));
185
186 if ($code eq 'OK') {
187 logaction($msg, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}");
188 changepage(page => "reclist", id => $msg);
189 } else {
190 changepage(page => "newdomain", add_failed => 1, domain => $webvar{domain}, errmsg => $msg);
191 }
192
193} elsif ($webvar{page} eq 'deldom') {
194
195 $page->param(id => $webvar{id});
196 # first pass = confirm y/n (sorta)
197 if (!defined($webvar{del})) {
198 $page->param(del_getconf => 1);
199 $page->param(domain => domainName($dbh,$webvar{id}));
200# print some neato things?
201
202# } else {
203# #whether actually deleting or cancelling we redirect to the domain list, default format
204
205 } elsif ($webvar{del} eq 'ok') {
206 my $pargroup = parentID($webvar{id}, 'dom', 'group');
207 my ($code,$msg) = delDomain($dbh, $webvar{id});
208 if ($code ne 'OK') {
209# need to find failure mode
210 $page->param(del_failed => 1);
211 $page->param(errmsg => $msg);
212 listdomains($curgroup);
213 } else {
214##fixme: need domain to put in log message
215 logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $webvar{domain}");
216 changepage(page => "domlist");
217 }
218 } else {
219 # cancelled. whee!
220 changepage(page => "domlist");
221 }
222
223} elsif ($webvar{page} eq 'reclist') {
224
225 # Handle record list for both default records (per-group) and live domain records
226
227 $page->param(defrec => $webvar{defrec});
228 $page->param(id => $webvar{id});
229 $page->param(curpage => $webvar{page});
230
231# select count(*) from (default_)?records where (group|domain)_id=?
232 my $sth = $dbh->prepare("SELECT count(*) FROM ".
233 ($webvar{defrec} eq 'y' ? 'default_' : '')."records ".
234 "WHERE ".($webvar{defrec} eq 'y' ? 'group' : 'domain')."_id=? ".
235 "AND NOT type=$reverse_typemap{SOA}");
236 $sth->execute($webvar{id});
237 my ($count) = ($sth->fetchrow_array);
238
239# fill the page-count and first-previous-next-last-all details
240 fill_pgcount($count,"records",domainName($dbh,$webvar{id}));
241 fill_fpnla($count); # should put some params on this sub...
242
243 $page->param(defrec => $webvar{defrec});
244 if ($webvar{defrec} eq 'y') {
245##fixme: hardcoded group
246 showdomain('y',$curgroup);
247 } else {
248 showdomain('n',$webvar{id});
249 }
250
251} elsif ($webvar{page} eq 'record') {
252
253 if ($webvar{recact} eq 'new') {
254
255 $page->param(todo => "Add record to");
256 $page->param(recact => "add");
257 fill_rectypes();
258
259 } elsif ($webvar{recact} eq 'add') {
260
261 my @recargs = ($dbh,$webvar{defrec},$webvar{parentid},$webvar{name},$webvar{type},$webvar{address},$webvar{ttl});
262 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) {
263 push @recargs, $webvar{distance};
264 if ($webvar{type} == $reverse_typemap{SRV}) {
265 push @recargs, $webvar{weight};
266 push @recargs, $webvar{port};
267 }
268 }
269 my ($code,$msg) = addRec(@recargs);
270
271 if ($code eq 'OK') {
272##fixme: need more magic to get proper group - if domain was fiddled
273# from search-subgroups listing, may not be "current" group
274
275# SELECT group_id FROM domains WHERE domain_id=?;
276# sth->execute($webvar{parentid});
277##log
278 if ($webvar{defrec} eq 'y') {
279 logaction(0, $session->param("username"), $webvar{parentid},
280 "Added default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
281 } else {
282 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'),
283 "Added record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl}");
284 }
285 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
286 } else {
287
288 $page->param(failed => 1);
289 $page->param(errmsg => $msg);
290 $page->param(wastrying => "adding");
291 $page->param(todo => "Add record to");
292 $page->param(recact => "add");
293 $page->param(parentid => $webvar{parentid});
294 $page->param(defrec => $webvar{defrec});
295 $page->param(id => $webvar{id});
296 fill_recdata(); # populate the form... er, mostly.
297 }
298
299 } elsif ($webvar{recact} eq 'edit') {
300
301 $page->param(todo => "Update record");
302 $page->param(recact => "update");
303 $page->param(parentid => $webvar{parentid});
304 $page->param(id => $webvar{id});
305 $page->param(defrec => $webvar{defrec});
306##fixme: SQL does not belong!
307 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM ".
308 ($webvar{defrec} eq 'y' ? 'default_' : '')."records WHERE record_id=?");
309 $sth->execute($webvar{id});
310 my ($host,$type,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array;
311 $page->param(name => $host);
312 $page->param(address => $val);
313 $page->param(distance => $distance);
314 $page->param(weight => $weight);
315 $page->param(port => $port);
316 $page->param(ttl => $ttl);
317 fill_rectypes($type);
318
319 } elsif ($webvar{recact} eq 'update') {
320
321 my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{id},
322 $webvar{name},$webvar{type},$webvar{address},$webvar{ttl},
323 $webvar{distance},$webvar{weight},$webvar{port});
324
325 if ($code eq 'OK') {
326##fixme: need more magic to get proper group - if domain was fiddled
327# from search-subgroups listing, may not be "current" group
328
329# SELECT d.group_id FROM domains d INNER JOIN records r ON d.domain_id=r.domain_id WHERE r.record_id=?
330# $sth->execute($webvar{id});
331##log
332 if ($webvar{defrec} eq 'y') {
333 logaction(0, $session->param("username"), $webvar{parentid},
334 "Updated default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
335 } else {
336 logaction($webvar{parentid}, $session->param("username"), parentID($webvar{id}, 'rec', 'group'),
337 "Updated record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}");
338 }
339 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
340 } else {
341 $page->param(failed => 1);
342 $page->param(errmsg => $msg);
343 $page->param(wastrying => "updating");
344 $page->param(todo => "Update record");
345 $page->param(recact => "update");
346 $page->param(parentid => $webvar{parentid});
347 $page->param(defrec => $webvar{defrec});
348 $page->param(id => $webvar{id});
349 fill_recdata();
350 }
351 }
352
353 if ($webvar{defrec} eq 'y') {
354 $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid}));
355 } else {
356 $page->param(parentid => $webvar{parentid});
357# $page->param(id => $webvar{id});
358 $page->param(dohere => domainName($dbh,$webvar{parentid}));
359 }
360
361} elsif ($webvar{page} eq 'delrec') {
362
363 $page->param(id => $webvar{id});
364 $page->param(defrec => $webvar{defrec});
365 $page->param(parentid => $webvar{parentid});
366 # first pass = confirm y/n (sorta)
367 if (!defined($webvar{del})) {
368 $page->param(del_getconf => 1);
369 my %rec = getRecLine($dbh,$webvar{defrec},$webvar{id});
370 $page->param(host => $rec{host});
371 $page->param(ftype => $typemap{$rec{type}});
372 $page->param(recval => $rec{val});
373 } elsif ($webvar{del} eq 'ok') {
374# get groupid of deleted record before we try to delete it
375 my $pargrp = parentID($webvar{id}, 'rec', 'group', $webvar{defrec});
376 my ($code,$msg) = delRec($dbh,$webvar{defrec},$webvar{id});
377 if ($code ne 'OK') {
378## need to find failure mode
379 #logaction(
380 $page->param(del_failed => 1);
381 $page->param(errmsg => $msg);
382 showdomain($webvar{defrec}, $webvar{parentid});
383 } else {
384##log
385 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
386 }
387 } else {
388 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec});
389 }
390
391} elsif ($webvar{page} eq 'editsoa') {
392
393 fillsoa($webvar{defrec},$webvar{id});
394
395} elsif ($webvar{page} eq 'updatesoa') {
396
397 my $sth;
398 my $sql = '';
399 # no domain ID, so we're editing the default SOA for a group (we don't care which one here)
400 # plus a bit of magic to update the appropriate table
401 $sql = "update ".($webvar{defrec} eq 'y' ? "default_records" : "records").
402 " set host='$webvar{prins}:$webvar{contact}',".
403 " val='$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}',".
404 " ttl=$webvar{ttl} where record_id=$webvar{recid}";
405 $sth = $dbh->prepare($sql);
406 $sth->execute;
407
408 if ($sth->err) {
409 $page->param(update_failed => 1);
410 $page->param(msg => $DBI::errstr);
411 fillsoa($webvar{defrec},$webvar{id});
412 } else {
413
414##fixme! need to set group ID properly here
415# SELECT group_id FROM domains WHERE domain_id=?
416# $sth->execute($webvar{id});
417##log
418 logaction(0, $session->param("username"), $webvar{group},
419 "Updated SOA (ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},".
420 " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl}");
421 changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec});
422# $page->param(update_failed => 0);
423# showdomain('y',1);
424 }
425
426} elsif ($webvar{page} eq 'grpman') {
427
428 listgroups();
429 $page->param(curpage => $webvar{page});
430
431} elsif ($webvar{page} eq 'newgrp') {
432
433 # do.. uhh.. stuff.. if we have no webvar{action}
434 if ($webvar{action} && $webvar{action} eq 'add') {
435 # not gonna provide the 4th param: template-or-clone flag, just yet
436 my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup});
437 if ($code eq 'OK') {
438 logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}");
439 changepage(page => "grpman");
440 }
441 $page->param(add_failed => 1);
442 $page->param(errmsg => $msg);
443 $page->param(newgroup => $webvar{newgroup});
444 fill_grouplist('pargroup',$webvar{pargroup});
445 } else {
446# $page->param
447 fill_grouplist('pargroup',$curgroup);
448
449 }
450
451} elsif ($webvar{page} eq 'delgrp') {
452
453 $page->param(id => $webvar{id});
454 # first pass = confirm y/n (sorta)
455 if (!defined($webvar{del})) {
456 $page->param(del_getconf => 1);
457# $page->param(groupname => groupName($dbh,$webvar{id}));
458# print some neato things?
459
460# } else {
461# #whether actually deleting or cancelling we redirect to the group list, default format
462
463 } elsif ($webvar{del} eq 'ok') {
464 my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it...
465 my ($code,$msg) = delGroup($dbh, $webvar{id});
466 if ($code ne 'OK') {
467# need to find failure mode
468 $page->param(del_failed => 1);
469 $page->param(errmsg => $msg);
470 $page->param(curpage => $webvar{page});
471 listgroups();
472 } else {
473##fixme: need to clean up log when deleting a major container
474 logaction(0, $session->param("username"), $webvar{curgroup}, "Deleted group $deleteme");
475 # success. go back to the domain list, do not pass "GO"
476 changepage(page => "grpman");
477 }
478 } else {
479 # cancelled. whee!
480 changepage(page => "grpman");
481 }
482 $page->param(delgroupname => groupName($dbh, $webvar{id}));
483
484} elsif ($webvar{page} eq 'useradmin') {
485
486 if (defined($webvar{action})) {
487 userStatus($dbh,$webvar{id},$webvar{action});
488 }
489
490 $page->param(curpage => $webvar{page});
491
492 list_users();
493
494} elsif ($webvar{page} eq 'newuser') {
495
496 # foo?
497 fill_actypelist();
498
499} elsif ($webvar{page} eq 'adduser') {
500
501 my ($code,$msg);
502
503 if ($webvar{pass1} ne $webvar{pass2}) {
504 $code = 'FAIL';
505 $msg = "Passwords don't match";
506 } else {
507 ($code,$msg) = addUser($dbh,$webvar{uname}, $webvar{group}, $webvar{pass1},
508 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
509 $webvar{fname}, $webvar{lname}, $webvar{phone});
510 }
511
512# hokay, a bit of magic to decide which page we hit.
513 if ($code eq 'OK') {
514##log
515 logaction(0, $session->param("username"), $webvar{group},
516 "Added user $webvar{uname} ($webvar{fname} $webvar{lname})");
517 changepage(page => "useradmin");
518 } else {
519# oddity - apparently, xhtml 1.0 strict swallows username as an HTML::Template var. O_o
520 $page->param(add_failed => 1);
521 $page->param(uname => $webvar{uname});
522 $page->param(fname => $webvar{fname});
523 $page->param(lname => $webvar{lname});
524 $page->param(pass1 => $webvar{pass1});
525 $page->param(pass2 => $webvar{pass2});
526 $page->param(errmsg => $msg);
527 fill_actypelist();
528 }
529
530# $page->param(add_failed => 1);
531
532} elsif ($webvar{page} eq 'deluser') {
533
534 $page->param(id => $webvar{id});
535 # first pass = confirm y/n (sorta)
536 if (!defined($webvar{del})) {
537 $page->param(del_getconf => 1);
538 $page->param(user => userFullName($dbh,$webvar{id}));
539 } elsif ($webvar{del} eq 'ok') {
540##fixme: find group id user is in (for logging) *before* we delete the user
541 my ($code,$msg) = delUser($dbh, $webvar{id});
542 if ($code ne 'OK') {
543# need to find failure mode
544 $page->param(del_failed => 1);
545 $page->param(errmsg => $msg);
546 list_users($curgroup);
547 } else {
548 # success. go back to the domain list, do not pass "GO"
549##log
550 logaction(0, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}");
551 changepage(page => "useradmin");
552 }
553 } else {
554 # cancelled. whee!
555 changepage(page => "useradmin");
556 }
557
558} elsif ($webvar{page} eq 'dnsq') {
559
560 $page->param(qfor => $webvar{qfor}) if $webvar{qfor};
561 fill_rectypes($webvar{type} ? $webvar{type} : '', 1);
562 $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse};
563 $page->param(resolver => $webvar{resolver}) if $webvar{resolver};
564
565 if ($webvar{qfor}) {
566 my $resolv = Net::DNS::Resolver->new;
567 $resolv->tcp_timeout(5); # make me adjustable!
568 $resolv->udp_timeout(5); # make me adjustable!
569 $resolv->recurse(0) if $webvar{nrecurse};
570 $resolv->nameservers($webvar{resolver}) if $webvar{resolver};
571 my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}});
572 if ($query) {
573
574 $page->param(showresults => 1);
575
576 my @answer;
577 foreach my $rr ($query->answer) {
578# next unless $rr->type eq "A" or $rr->type eq 'NS';
579 my %row;
580 my ($host,$ttl,$class,$type,$data) =
581 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s);
582 $row{host} = $host;
583 $row{ftype} = $type;
584 $row{rdata} = ($type eq 'SOA' ? "<pre>$data</pre>" : $data);
585 push @answer, \%row;
586 }
587 $page->param(answer => \@answer);
588
589 my @additional;
590 foreach my $rr ($query->additional) {
591# next unless $rr->type eq "A" or $rr->type eq 'NS';
592 my %row;
593 my ($host,$ttl,$class,$type,$data) =
594 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
595 $row{host} = $host;
596 $row{ftype} = $type;
597 $row{rdata} = $data;
598 push @additional, \%row;
599 }
600 $page->param(additional => \@additional);
601
602 my @authority;
603 foreach my $rr ($query->authority) {
604# next unless $rr->type eq "A" or $rr->type eq 'NS';
605 my %row;
606 my ($host,$ttl,$class,$type,$data) =
607 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
608 $row{host} = $host;
609 $row{ftype} = $type;
610 $row{rdata} = $data;
611 push @authority, \%row;
612 }
613 $page->param(authority => \@authority);
614
615 $page->param(usedresolver => $resolv->answerfrom);
616 $page->param(frtype => $typemap{$webvar{type}});
617
618 } else {
619 $page->param(errmsg => $resolv->errorstring);
620 }
621 }
622 ## done DNS query
623
624} elsif ($webvar{page} eq 'axfr') {
625
626 # don't need this while we've got the dropdown in the menu. hmm.
627 #fill_grouplist;
628
629 $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom};
630 $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa};
631 $page->param(rwns => $webvar{rwns}) if $webvar{rwns};
632 $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww.
633 $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms};
634
635##fixme: check group too?
636 if ($webvar{doit} eq 'y' && !$webvar{ifrom}) {
637 $page->param(errmsg => "Need to set host to import from");
638 } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) {
639 $page->param(errmsg => "Need domains to import");
640 } else {
641 my @domlist = split /\s+/, $webvar{importdoms};
642 my @results;
643my $rnum = 0;
644 foreach my $domain (@domlist) {
645 my %row;
646 my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group},
647 $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns});
648 $row{domok} = $msg if $code eq 'OK';
649 if ($code eq 'WARN') {
650 $msg =~ s|\n|<br />|g;
651 $row{domwarn} = $msg;
652 }
653 if ($code eq 'FAIL') {
654 $msg =~ s|\n|<br />|g;
655 $row{domerr} = $msg;
656 }
657 # do stuff! DNSDB::importAXFR($webvar{ifrom}, $webvar{rwsoa}, $webvar{rwns}, $domain, <flags>)
658 $row{domain} = $domain;
659# $row{row} = $rnum++;
660 push @results, \%row;
661 }
662 $page->param(axfrresults => \@results);
663 }
664
665} elsif ($webvar{page} eq 'whoisq') {
666
667 if ($webvar{qfor}) {
668 use Net::Whois::Raw;
669 use Text::Wrap;
670
671# caching useful?
672#$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/";
673#$Net::Whois::Raw::CACHE_TIME = 60;
674
675 my ($dominfo, $whois_server) = whois($webvar{qfor});
676##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data
677
678 # le sigh. idjits spit out data without linefeeds...
679 $Text::Wrap::columns = 88;
680
681# &%$@%@# high-bit crap. We should probably find a way to properly recode these instead of one-by-one.
682# Mainly an XHTML validation thing.
683 $dominfo =~ s/\xa9/\&copy;/g;
684 $dominfo =~ s/\xae/\&reg;/g;
685
686 $page->param(qfor => $webvar{qfor});
687 $page->param(dominfo => wrap('','',$dominfo));
688 $page->param(whois_server => $whois_server);
689 } else {
690 $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway};
691 }
692
693} elsif ($webvar{page} eq 'log') {
694
695##fixme put in some real log-munching stuff
696##fixme need to add bits to *create* log entries...
697 my $sth = $dbh->prepare("SELECT * FROM log");
698 $sth->execute;
699 my @logbits;
700 while (my @data = $sth->fetchrow_array) {
701 my %row;
702# (1,1,1,'test@test','Test','frobbed the whatsit',now());
703 $row{userfname} = $data[4];
704 $row{userid} = $data[1];
705 $row{useremail} = $data[3];
706 $row{logentry} = $data[5];
707 $row{logtime} = $data[6];
708 push @logbits, \%row;
709 }
710 $page->param(logentries => \@logbits);
711
712}
713
714
715# start output here so we can redirect pages.
716print "Content-type: text/html\n\n", $header->output;
717
718##common bits
719if ($webvar{page} ne 'login') {
720 $page->param(username => $session->param("username"));
721
722 $page->param(group => $curgroup);
723 $page->param(groupname => groupName($dbh,$curgroup));
724 $page->param(logingrp => groupName($dbh,$logingroup));
725
726 # group tree. should go elsewhere, probably
727 my $tmpgrplist = fill_grptree($logingroup,$curgroup);
728 $page->param(grptree => $tmpgrplist);
729
730 $page->param(inlogingrp => $curgroup == $logingroup);
731
732 # stuff for menu group change. nb: this is icky.
733 fill_grouplist("grouplist");
734
735## set up "URL to self"
736# @#$%@%@#% XHTML - & in a URL must be escaped. >:(
737 my $tmp_ruri = $ENV{REQUEST_URI};
738 $tmp_ruri =~ s/\&([a-z])/\&amp\;$1/g;
739
740# le sigh. and we need to strip any previous action
741 $tmp_ruri =~ s/\&amp;action=[^&]+//g;
742
743# and search filter options. these get stored in the session, but discarded
744# as soon as you switch to a different page.
745##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits
746 no warnings qw(uninitialized);
747 $tmp_ruri =~ s/\&amp;startwith=[a-z09-]*(\&)?/$1/g;
748 $tmp_ruri =~ s/\&amp;searchsubs=[a-z09-]*(\&)?/$1/g;
749 $tmp_ruri =~ s/\&amp;filter=[a-z09-]*(\&)?/$1/g;
750 use warnings qw(uninitialized);
751
752# fill in the URL-to-self
753 $page->param(whereami => $tmp_ruri);
754}
755
756foreach (@debugbits) { print; }
757
758# spit it out
759print $page->output;
760
761if ($debugenv) {
762 print "<div id=\"debug\">webvar keys: <pre>\n";
763 foreach my $key (keys %webvar) {
764 print "key: $key\tval: $webvar{$key}\n";
765 }
766 print "</pre>\nsession:\n<pre>\n";
767 my $sesdata = $session->dataref();
768 foreach my $key (keys %$sesdata) {
769 print "key: $key\tval: ".$sesdata->{$key}."\n";
770 }
771 print "</pre>\nENV:\n<pre>\n";
772 foreach my $key (keys %ENV) {
773 print "key: $key\tval: $ENV{$key}\n";
774 }
775 print "</pre></div>\n";
776}
777
778print $footer->output;
779
780# as per the docs, Just In Case
781$session->flush();
782
783exit 0;
784
785
786sub fill_grptree {
787 my $root = shift;
788 my $cur = shift;
789
790 my @childlist;
791
792 my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl');
793 getChildren($dbh,$root,\@childlist,'immediate');
794 return if $#childlist == -1;
795 my @grouplist;
796 foreach (@childlist) {
797 my %row;
798 $row{grpname} = groupName($dbh,$_);
799 $row{grpname} = "<b>$row{grpname}</b>" if $_ == $cur;
800 $row{subs} = fill_grptree($_,$cur);
801 push @grouplist, \%row;
802 }
803 $grptree->param(treelvl => \@grouplist);
804 return $grptree->output;
805}
806
807sub changepage {
808 my %params = @_; # think this works the way I want...
809
810 # handle user check
811 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid";
812 foreach (keys %params) {
813 $newurl .= "&$_=$params{$_}";
814 }
815
816 # Just In Case
817 $session->flush();
818
819 print "Status: 302\nLocation: $newurl\n\n";
820 exit;
821} # end changepage
822
823sub fillsoa {
824 my $def = shift;
825 my $id = shift;
826 my $domname = ($def eq 'y' ? '' : "DOMAIN");
827
828 $page->param(defrec => $def);
829
830# i had a good reason to do this when I wrote it...
831# $page->param(domain => $domname);
832# $page->param(group => $DNSDB::group);
833 $page->param(isgrp => 1) if $def eq 'y';
834 $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) );
835
836# defaults
837 $page->param(defcontact => $DNSDB::def{contact});
838 $page->param(defns => $DNSDB::def{prins});
839 $page->param(defsoattl => $DNSDB::def{soattl});
840 $page->param(defrefresh => $DNSDB::def{refresh});
841 $page->param(defretry => $DNSDB::def{retry});
842 $page->param(defexpire => $DNSDB::def{expire});
843 $page->param(defminttl => $DNSDB::def{minttl});
844
845 # there are probably better ways to do this. TMTOWTDI.
846 my %soa = getSOA($dbh,$def,$id);
847
848 $page->param(id => $id);
849 $page->param(recid => $soa{recid});
850 $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins}));
851 $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact}));
852 $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh}));
853 $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry}));
854 $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire}));
855 $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl}));
856 $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl}));
857}
858
859sub showdomain {
860 my $def = shift;
861 my $id = shift;
862
863 # get the SOA first
864 my %soa = getSOA($dbh,$def,$id);
865
866 $page->param(recid => $soa{recid});
867 $page->param(contact => $soa{contact});
868 $page->param(prins => $soa{prins});
869 $page->param(refresh => $soa{refresh});
870 $page->param(retry => $soa{retry});
871 $page->param(expire => $soa{expire});
872 $page->param(minttl => $soa{minttl});
873 $page->param(ttl => $soa{ttl});
874
875# my @foo2 = getDomRecs($dbh,'def',1);
876 my $foo2 = getDomRecs($dbh,$def,$id,$perpage,$webvar{offset});
877
878 my $row = 0;
879 foreach my $rec (@$foo2) {
880 $rec->{type} = $typemap{$rec->{type}};
881 $rec->{row} = $row % 2;
882 $rec->{defrec} = $webvar{defrec};
883 $rec->{sid} = $webvar{sid};
884 $rec->{id} = $id;
885 $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV');
886 $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV');
887 $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV');
888 $row++;
889 }
890 $page->param(reclist => $foo2);
891}
892
893# fill in record type list on add/update/edit record template
894sub fill_rectypes {
895 my $type = shift || $reverse_typemap{A};
896 my $soaflag = shift || 0;
897
898 my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder");
899 $sth->execute;
900 my @typelist;
901 while (my ($rval,$rname) = $sth->fetchrow_array()) {
902 my %row = ( recval => $rval, recname => $rname );
903 $row{tselect} = 1 if $rval == $type;
904 push @typelist, \%row;
905 }
906 if ($soaflag) {
907 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
908 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
909 push @typelist, \%row;
910 }
911 $page->param(typelist => \@typelist);
912} # fill_rectypes
913
914sub fill_recdata {
915 fill_rectypes($webvar{type});
916
917 $page->param(name => $webvar{name});
918 $page->param(address => $webvar{address});
919 $page->param(distance => $webvar{distance})
920 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV});
921 $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV};
922 $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV};
923 $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $DNSDB::def{minttl}));
924}
925
926sub fill_actypelist {
927 my @actypes;
928
929 my %row1 = (actypeval => 'u', actypename => 'user');
930 $row1{typesel} = 1 if $webvar{accttype} eq 'u';
931 push @actypes, \%row1;
932
933 my %row2 = (actypeval => 'S', actypename => 'superuser');
934 $row2{typesel} = 1 if $webvar{accttype} eq 'S';
935 push @actypes, \%row2;
936
937 $page->param(actypelist => \@actypes);
938}
939
940sub fill_fpnla {
941 my $count = shift;
942##fixme
943 if ($offset eq 'all') {
944# uhm....
945 } else {
946 # all these bits only have sensible behaviour if offset is numeric. err, probably.
947 if ($count > $perpage) {
948 # if there are more results than the default, always show the "all" link
949 $page->param(navall => 1);
950
951 if ($offset > 0) {
952 $page->param(navfirst => 1);
953 $page->param(navprev => 1);
954 $page->param(prevoffs => $offset-1);
955 }
956
957 # show "next" and "last" links if we're not on the last page of results
958 if ( (($offset+1) * $perpage - $count) < 0 ) {
959 $page->param(navnext => 1);
960 $page->param(nextoffs => $offset+1);
961 $page->param(navlast => 1);
962 $page->param(lastoffs => int (($count-1)/$perpage));
963 }
964 }
965 }
966} # end fill_fpnla()
967
968sub fill_pgcount {
969 my $pgcount = shift;
970 my $pgtype = shift;
971 my $parent = shift;
972
973 $page->param(ntot => $pgcount);
974 $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1));
975 $page->param(npglast => ($offset eq 'all' ? $pgcount :
976 ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) )
977 ));
978 $page->param(pgtype => $pgtype);
979 $page->param(parent => $parent);
980} # end fill_pgcount()
981
982sub listdomains {
983
984##fixme: $logingroup or $curgroup?
985 my @childgroups;
986 #getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
987 my $childlist = join(',',@childgroups);
988
989 my $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
990 ($startwith ? " AND domain ~* '^[$startwith]'" : '').
991 ($filter ? " AND domain ~* '$filter'" : '');
992 my $sth = $dbh->prepare($sql);
993 $sth->execute;
994 my ($count) = $sth->fetchrow_array;
995
996# fill page count and first-previous-next-last-all bits
997##fixme - hardcoded group bit
998 fill_pgcount($count,"domains",groupName($dbh,$curgroup));
999 fill_fpnla($count);
1000
1001# sort/order
1002 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1003 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1004
1005 $sortby = $session->param($webvar{page}.'sortby');
1006 $sortorder = $session->param($webvar{page}.'order');
1007
1008# set up the headers
1009 my @cols = ('domain', 'status', 'group');
1010 my %colheads = (domain => 'Domain', status => 'Status', group => 'Group');
1011 fill_colheads($sortby, $sortorder, \@cols, \%colheads);
1012
1013# $page->param(sortorder => $sortorder);
1014 # hack! hack! pthbttt. have to rethink the status column storage,
1015 # or inactive comes "before" active. *sigh*
1016 $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status';
1017
1018# waffle, waffle - keep state on these as well as sortby, sortorder?
1019 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1020
1021 $page->param(filter => $filter) if $filter;
1022 $page->param(searchsubs => $searchsubs) if $searchsubs;
1023
1024##fixme
1025##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
1026##fixme
1027
1028 $page->param(group => $curgroup);
1029 my @domlist;
1030 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1031 " INNER JOIN groups ON domains.group_id=groups.group_id".
1032 " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1033##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1034 ($startwith ? " AND domain ~* '^[$startwith]'" : '').
1035 ($filter ? " AND domain ~* '$filter'" : '').
1036 " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $sortby).
1037 " $sortorder ".($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1038 $sth = $dbh->prepare($sql);
1039 $sth->execute;
1040 my $rownum = 0;
1041 while (my @data = $sth->fetchrow_array) {
1042 my %row;
1043 $row{domainid} = $data[0];
1044 $row{domain} = $data[1];
1045 $row{status} = ($data[2] ? 'Active' : 'Inactive');
1046 $row{group} = $data[3];
1047 $row{bg} = ($rownum++)%2;
1048# $row{mkactive} = ($data[2] eq 'inactive' ? 1 : 0);
1049 $row{mkactive} = !$data[2];
1050 $row{sid} = $sid;
1051 $row{offset} = $offset;
1052##fixme: need to clean up status indicator/usage/inversion
1053 push @domlist, \%row;
1054 }
1055 $page->param(domtable => \@domlist);
1056} # end listdomains()
1057
1058sub listgroups {
1059
1060 my @childgroups;
1061 getChildren($dbh, $logingroup, \@childgroups, 'all') if $searchsubs;
1062 my $childlist = join(',',@childgroups);
1063
1064 my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
1065 ($startwith ? " AND group_name ~* '^[$startwith]'" : '').
1066 ($filter ? " AND group_name ~* '$filter'" : '');
1067 my $sth = $dbh->prepare($sql);
1068
1069 $sth->execute;
1070 my ($count) = ($sth->fetchrow_array);
1071# fill page count and first-previous-next-last-all bits
1072##fixme - hardcoded group bit
1073 fill_pgcount($count,"groups",'');
1074 fill_fpnla($count);
1075
1076# $sortby = 'group';
1077# sort/order
1078 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1079 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1080
1081 $sortby = $session->param($webvar{page}.'sortby');
1082 $sortorder = $session->param($webvar{page}.'order');
1083
1084# set up the headers
1085 my @cols = ('group','parent','nusers','ndomains');
1086 my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains');
1087 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1088
1089# waffle, waffle - keep state on these as well as sortby, sortorder?
1090 $page->param("start$webvar{startwith}" => 1) if $webvar{startwith} && $webvar{startwith} =~ /^[a-z]$/;
1091
1092 $page->param(filter => $filter) if $filter;
1093 $page->param(searchsubs => $searchsubs) if $searchsubs;
1094
1095# munge sortby for columns in database
1096 $sortby = 'g.group_name' if $sortby eq 'group';
1097 $sortby = 'g2.group_name' if $sortby eq 'parent';
1098
1099 my @grouplist;
1100 $sth = $dbh->prepare("SELECT g.group_id, g.group_name, g2.group_name, ".
1101 "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ".
1102 "FROM groups g ".
1103 "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ".
1104 "LEFT OUTER JOIN users u ON u.group_id=g.group_id ".
1105 "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ".
1106 "WHERE g.parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').") ".
1107##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1108 ($startwith ? " AND g.group_name ~* '^[$startwith]'" : '').
1109 ($filter ? " AND g.group_name ~* '$filter'" : '').
1110 " GROUP BY g.group_id, g.group_name, g2.group_name ".
1111 " ORDER BY $sortby $sortorder ".
1112 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage));
1113 $sth->execute;
1114
1115 my $rownum = 0;
1116 while (my @data = $sth->fetchrow_array) {
1117 my %row;
1118 $row{groupid} = $data[0];
1119 $row{groupname} = $data[1];
1120 $row{pgroup} = $data[2];
1121 $row{nusers} = $data[3];
1122 $row{ndomains} = $data[4];
1123 $row{bg} = ($rownum++)%2;
1124 $row{sid} = $sid;
1125 push @grouplist, \%row;
1126 }
1127 $page->param(grouptable => \@grouplist);
1128} # end listgroups()
1129
1130sub fill_grouplist {
1131 my $template_var = shift;
1132 my $cur = shift || $curgroup;
1133
1134 my @childgroups;
1135 getChildren($dbh, $logingroup, \@childgroups, 'all');
1136 my $childlist = join(',',@childgroups);
1137
1138 # weesa gonna discard parent_group_id for now
1139 my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ".
1140 "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
1141 "ORDER BY group_id");
1142 $sth->execute;
1143 my @grouplist;
1144 while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) {
1145 my %row;
1146 $row{groupname} = $groupname;
1147 $row{groupval} = $groupid;
1148##fixme: need magic
1149# $row{defgroup} = '';
1150 $row{groupactive} = 1 if $groupid == $cur;
1151 push @grouplist, \%row;
1152 }
1153
1154 $page->param("$template_var" => \@grouplist);
1155
1156} # end fill_grouplist()
1157
1158sub list_users {
1159
1160 my @childgroups;
1161 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1162 my $childlist = join(',',@childgroups);
1163
1164 my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1165 ($startwith ? " AND username ~* '^[$startwith]'" : '').
1166 ($filter ? " AND username ~* '$filter'" : '');
1167 my $sth = $dbh->prepare($sql);
1168 $sth->execute;
1169 my ($count) = ($sth->fetchrow_array);
1170
1171# fill page count and first-previous-next-last-all bits
1172##fixme - hardcoded group bit
1173 fill_pgcount($count,"users",'');
1174 fill_fpnla($count);
1175
1176# $sortby = 'user';
1177# sort/order
1178 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1179 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1180
1181 $sortby = $session->param($webvar{page}.'sortby');
1182 $sortorder = $session->param($webvar{page}.'order');
1183
1184# set up the headers
1185 my @cols = ('user','fname','type','group','status');
1186 my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status');
1187 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1188
1189# waffle, waffle - keep state on these as well as sortby, sortorder?
1190 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^[a-z]$/;
1191
1192 $page->param(filter => $filter) if $filter;
1193 $page->param(searchsubs => $searchsubs) if $searchsubs;
1194
1195# munge sortby for columns in database
1196 $sortby = 'u.username' if $sortby eq 'user';
1197 $sortby = 'u.type' if $sortby eq 'type';
1198 $sortby = 'g.group_name' if $sortby eq 'group';
1199 $sortby = 'u.status' if $sortby eq 'status';
1200
1201 my @userlist;
1202 $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
1203 "FROM users u ".
1204 "INNER JOIN groups g ON u.group_id=g.group_id ".
1205 "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1206##fixme: don't do variable subs in SQL, use placeholders and params in ->execute()
1207 ($startwith ? " AND u.username ~* '^[$startwith]'" : '').
1208 ($filter ? " AND u.username ~* '$filter'" : '').
1209 " ORDER BY $sortby $sortorder ".
1210 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1211
1212 $sth = $dbh->prepare($sql);
1213 $sth->execute;
1214
1215 my $rownum = 0;
1216 while (my @data = $sth->fetchrow_array) {
1217 no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name
1218 my %row;
1219 $row{userid} = $data[0];
1220 $row{username} = $data[1];
1221 $row{userfull} = $data[2];
1222 $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user");
1223 $row{usergroup} = $data[4];
1224 $row{active} = $data[5];
1225 $row{bg} = ($rownum++)%2;
1226 $row{sid} = $sid;
1227 push @userlist, \%row;
1228 }
1229 $page->param(usertable => \@userlist);
1230} # end list_users()
1231
1232# Generate all of the glop necessary to add or not the appropriate marker/flag for
1233# the sort order and column in domain, user, group, and record lists
1234# Takes an array ref and hash ref
1235sub fill_colheads {
1236 my $sortby = shift;
1237 my $sortorder = shift;
1238 my $cols = shift;
1239 my $colnames = shift;
1240
1241 my @headings;
1242
1243 foreach my $col (@$cols) {
1244 my %coldata;
1245 $coldata{firstcol} = 1 if $col eq $cols->[0];
1246 $coldata{sid} = $sid;
1247 $coldata{page} = $webvar{page};
1248 $coldata{offset} = $webvar{offset} if $webvar{offset};
1249 $coldata{sortby} = $col;
1250 $coldata{colname} = $colnames->{$col};
1251 if ($col eq $sortby) {
1252 $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC');
1253 $coldata{sortorder} = $sortorder;
1254 } else {
1255 $coldata{order} = 'ASC';
1256 }
1257 push @headings, \%coldata;
1258 }
1259
1260 $page->param(colheads => \@headings);
1261
1262} # end fill_colheads()
1263
1264sub logaction {
1265 my ($domid,$username,$groupid,$entry) = shift;
1266
1267 my $sth = dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?");
1268 $sth->execute($username);
1269 my ($user_id, $fullname) = $sth->fetchrow_array;
1270
1271 $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) ".
1272 "VALUES (?,?,?,?,?,?)");
1273 $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry);
1274
1275} # end logaction()
1276
1277#sub parentID($dbh, $id, $idtype, $partype[, $defrec])
1278sub parentID {
1279 my $id = shift;
1280 my $idtype = shift;
1281 my $partype = shift;
1282 my $defrec = shift || '';
1283
1284 my $sql = '';
1285
1286 if ($idtype eq 'dom') {
1287 return $id if $defrec eq 'y';
1288 $sql = "SELECT group_id FROM domains WHERE domain_id=?";
1289 } elsif ($idtype eq 'rec') {
1290 if ($defrec && $defrec eq 'y') {
1291 } else {
1292 return
1293 $sql = "SELECT d.group_id FROM domains d".
1294 " INNER JOIN records r ON d.domain_id=r.domain_id".
1295 " WHERE r.record_id=?";
1296 }
1297 } elsif ($idtype eq 'group') {
1298 $sql = "SELECT parent_group_id FROM groups WHERE group_id=?";
1299 } elsif ($idtype eq 'user') {
1300 $sql = "SELECT group_id FROM users WHERE user_id=?";
1301 } else {
1302 return "FOO", "BAR"; # can't get here.... we think.
1303 }
1304}
Note: See TracBrowser for help on using the repository browser.