#!/usr/bin/perl -w -T # dns/cgi-bin/dns.cgi ### # SVN revision info # $Date: 2011-04-01 22:01:14 +0000 (Fri, 01 Apr 2011) $ # SVN revision $Rev: 88 $ # Last update by $Author: kdeugau $ ### # Copyright (C) 2008-2011 - Kris Deugau use strict; use warnings; use CGI::Carp qw (fatalsToBrowser); use CGI::Simple; use HTML::Template; use CGI::Session; use Crypt::PasswdMD5; use Net::DNS; use DBI; use Data::Dumper; use lib '.'; # custom modules use DNSDB qw(:ALL); my @debugbits; # temp, to be spit out near the end of processing my $debugenv = 1; # Let's do these templates right... my $templatedir = "templates"; my $sessiondir = "session"; # Set up the CGI object... my $q = new CGI::Simple; # ... and get query-string params as well as POST params if necessary $q->parse_query_string; # This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about... my %webvar = $q->Vars; # persistent stuff needed on most/all pages my $sid = ($webvar{sid} ? $webvar{sid} : undef); my $session = new CGI::Session("driver:File", $sid, {Directory => $sessiondir}) or die CGI::Session->errstr(); #$sid = $session->id() if !$sid; if (!$sid) { # init stuff. can probably axe this down to just above if'n'when user manipulation happens $sid = $session->id(); # need to know the "upper" group the user can deal with; may as well # stick this in the session rather than calling out to the DB every time. $session->param('logingroup',1); $session->param('curgroup',1); # yes, we *do* need to track this too. er, probably. $session->param('domlistsortby','domain'); $session->param('domlistorder','ASC'); $session->param('useradminsortby','user'); $session->param('useradminorder','ASC'); $session->param('grpmansortby','group'); $session->param('grpmanorder','ASC'); $session->param('reclistsortby','host'); $session->param('reclistorder','ASC'); # $session->param('filter','login'); # $session->param('startwith','login'); # $session->param('searchsubs','login'); } my $logingroup = ($session->param('logingroup') ? $session->param('logingroup') : 1); my $curgroup = ($session->param('curgroup') ? $session->param('curgroup') : $logingroup); my $group = ($webvar{group} ? $webvar{group} : 1); # per-page startwith, filter, searchsubs $session->param($webvar{page}.'startwith', $webvar{startwith}) if defined($webvar{startwith}); $session->param($webvar{page}.'filter', $webvar{filter}) if defined($webvar{filter}); $webvar{searchsubs} =~ s/^n ?// if $webvar{searchsubs}; $session->param($webvar{page}.'searchsubs', $webvar{searchsubs}) if defined($webvar{searchsubs}); # decide which page to spit out... # also set $webvar{page} before we try to use it. $webvar{page} = 'login' if !$webvar{page}; my $startwith = $session->param($webvar{page}.'startwith'); my $filter = $session->param($webvar{page}.'filter'); my $searchsubs = $session->param($webvar{page}.'searchsubs'); # nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet my $header = HTML::Template->new(filename => "$templatedir/header.tmpl"); my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl"); # default #my $perpage = 15; my $perpage = 3; my $offset = ($webvar{offset} ? $webvar{offset} : 0); # NB: these must match the field name and SQL ascend/descend syntax respectively my $sortby = "domain"; my $sortorder = "ASC"; my ($dbh,$msg) = connectDB("dnsdb","dnsdb","secret","newdbhost"); #my $dbh = DBI->connect("DBI:mysql:database=vegadns","vegadns","secret", # { AutoCommit => 0 }) or die $DBI::errstr; ##fixme. PLEASE! print $msg if !$dbh; # fiddle hardcoded "defaults" as per system/user (?) prefs initGlobals($dbh); # handle login redirect if ($webvar{action}) { if ($webvar{action} eq 'login') { # Snag ACL/permissions here too my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?"); $sth->execute($webvar{username}); my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array; $webvar{loginfailed} = 1 if !defined($uid); if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) { $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1); } else { $webvar{loginfailed} = 1 if $pass ne $webvar{password}; } # set session bits $session->param('logingroup',$gid); $session->param('curgroup',$gid); $session->param('uid',$uid); $session->param('username',$webvar{username}); changepage(page => "domlist") if !defined($webvar{loginfailed}); } elsif ($webvar{action} eq 'logout') { # delete the session $session->delete(); $session->flush(); my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}"; $newurl =~ s|/[^/]+$|/|; print "Status: 302\nLocation: $newurl\n\n"; exit; } elsif ($webvar{action} eq 'chgroup') { # fiddle session-stored group data # magic incantation to... uhhh... $session->param('curgroup', $webvar{group}); $curgroup = ($webvar{group} ? $webvar{group} : $session->param('curgroup')); } } # handle global webvar{action}s initPermissions($dbh,$session->param('uid')); ## Default page is a login page #my $page; # to be initialized as an HTML::Template entity sooner or later #if (!$webvar{page}) { # $page = HTML::Template->new(filename => "$templatedir/login.tmpl"); #} else { #} my $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl"); $page->param(sid => $sid); if ($webvar{page} eq 'login') { $page->param(loginfailed => 1) if $webvar{loginfailed}; ##fixme: set up session init to actually *check* for session timeout $page->param(timeout => 1) if $webvar{sesstimeout}; } elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') { # hmm. seeing problems in some possibly-not-so-corner cases. # this currently only handles "domain on", "domain off" if (defined($webvar{action})) { my $stat = domStatus($dbh,$webvar{id},$webvar{action}); logaction($webvar{id}, $session->param("username"), parentID($webvar{id}, 'dom', 'group'), "Changed ".domainName($dbh, $webvar{id})." state to ".($stat ? 'active' : 'inactive')); } $page->param(curpage => $webvar{page}); if ($webvar{del_failed}) { $page->param(del_failed => 1); $page->param(errmsg => $webvar{errmsg}); } listdomains(); } elsif ($webvar{page} eq 'newdomain') { # hmm. nothing to do here? # - group list is filled by the same bit that fills the group list in the menu if ($webvar{add_failed}) { $page->param(add_failed => 1); $page->param(errmsg => $webvar{errmsg}); $page->param(domain => $webvar{domain}); } } elsif ($webvar{page} eq 'adddomain') { my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0)); if ($code eq 'OK') { logaction($msg, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}"); changepage(page => "reclist", id => $msg); } else { logaction(0, $session->param("username"), $webvar{group}, "Failed adding domain $webvar{domain} ($msg)"); changepage(page => "newdomain", add_failed => 1, domain => $webvar{domain}, errmsg => $msg); } } elsif ($webvar{page} eq 'deldom') { $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); $page->param(domain => domainName($dbh,$webvar{id})); } elsif ($webvar{del} eq 'ok') { my $pargroup = parentID($webvar{id}, 'dom', 'group'); my $dom = domainName($dbh, $webvar{id}); my ($code,$msg) = delDomain($dbh, $webvar{id}); if ($code ne 'OK') { # need to find failure mode logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $dom ($msg)"); changepage(page => "domlist", del_failed => 1, errmsg => $msg); } else { logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $dom"); changepage(page => "domlist"); } } else { # cancelled. whee! changepage(page => "domlist"); } } elsif ($webvar{page} eq 'reclist') { # Handle record list for both default records (per-group) and live domain records $page->param(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); $page->param(curpage => $webvar{page}); my $sth = $dbh->prepare("SELECT count(*) FROM ". ($webvar{defrec} eq 'y' ? 'default_' : '')."records ". "WHERE ".($webvar{defrec} eq 'y' ? 'group' : 'domain')."_id=? ". "AND NOT type=$reverse_typemap{SOA}"); $sth->execute($webvar{id}); my ($count) = ($sth->fetchrow_array); # $sortby = 'host'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order'); # set up the headers my @cols = ('host', 'type', 'val', 'distance', 'weight', 'port', 'ttl'); my %colheads = (host => 'Name', type => 'Type', val => 'Address', distance => 'Distance', weight => 'Weight', port => 'Port', ttl => 'TTL'); my %custom = (id => $webvar{id}, defrec => $webvar{defrec}); fill_colheads($sortby, $sortorder, \@cols, \%colheads, \%custom); # fill the page-count and first-previous-next-last-all details fill_pgcount($count,"records",domainName($dbh,$webvar{id})); fill_fpnla($count); # should put some params on this sub... $page->param(defrec => $webvar{defrec}); if ($webvar{defrec} eq 'y') { showdomain('y',$curgroup); } else { showdomain('n',$webvar{id}); $page->param(logdom => 1); } if ($webvar{del_failed}) { $page->param(del_failed => 1); $page->param(errmsg => $webvar{errmsg}); } } elsif ($webvar{page} eq 'record') { if ($webvar{recact} eq 'new') { $page->param(todo => "Add record"); $page->param(recact => "add"); $page->param(parentid => $webvar{parentid}); $page->param(defrec => $webvar{defrec}); fill_recdata(); } elsif ($webvar{recact} eq 'add') { my @recargs = ($dbh,$webvar{defrec},$webvar{parentid},$webvar{name},$webvar{type},$webvar{address},$webvar{ttl}); if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) { push @recargs, $webvar{distance}; if ($webvar{type} == $reverse_typemap{SRV}) { push @recargs, $webvar{weight}; push @recargs, $webvar{port}; } } my ($code,$msg) = addRec(@recargs); if ($code eq 'OK') { if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Added default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Added record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } else { $page->param(failed => 1); $page->param(errmsg => $msg); $page->param(wastrying => "adding"); $page->param(todo => "Add record"); $page->param(recact => "add"); $page->param(parentid => $webvar{parentid}); $page->param(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); fill_recdata(); # populate the form... er, mostly. if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Failed adding default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Failed adding record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)"); } } } elsif ($webvar{recact} eq 'edit') { $page->param(todo => "Update record"); $page->param(recact => "update"); $page->param(parentid => $webvar{parentid}); $page->param(id => $webvar{id}); $page->param(defrec => $webvar{defrec}); ##fixme: SQL does not belong! my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM ". ($webvar{defrec} eq 'y' ? 'default_' : '')."records WHERE record_id=?"); $sth->execute($webvar{id}); my ($host,$type,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array; $page->param(name => $host); $page->param(address => $val); $page->param(distance => $distance); $page->param(weight => $weight); $page->param(port => $port); $page->param(ttl => $ttl); fill_rectypes($type); } elsif ($webvar{recact} eq 'update') { my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{id}, $webvar{name},$webvar{type},$webvar{address},$webvar{ttl}, $webvar{distance},$webvar{weight},$webvar{port}); if ($code eq 'OK') { ##fixme: need more magic to get proper group - if domain was fiddled # from search-subgroups listing, may not be "current" group # SELECT d.group_id FROM domains d INNER JOIN records r ON d.domain_id=r.domain_id WHERE r.record_id=? # $sth->execute($webvar{id}); ##log if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Updated default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{id}, 'rec', 'group'), "Updated record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } else { $page->param(failed => 1); $page->param(errmsg => $msg); $page->param(wastrying => "updating"); $page->param(todo => "Update record"); $page->param(recact => "update"); $page->param(parentid => $webvar{parentid}); $page->param(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); fill_recdata(); if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Failed updating default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Failed updating record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)"); } } } if ($webvar{defrec} eq 'y') { $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid})); } else { $page->param(parentid => $webvar{parentid}); $page->param(dohere => domainName($dbh,$webvar{parentid})); } } elsif ($webvar{page} eq 'delrec') { $page->param(id => $webvar{id}); $page->param(defrec => $webvar{defrec}); $page->param(parentid => $webvar{parentid}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); my %rec = getRecLine($dbh,$webvar{defrec},$webvar{id}); $page->param(host => $rec{host}); $page->param(ftype => $typemap{$rec{type}}); $page->param(recval => $rec{val}); } elsif ($webvar{del} eq 'ok') { # get rec data before we try to delete it my %rec = getRecLine($dbh,$webvar{defrec},$webvar{id}); my ($code,$msg) = delRec($dbh,$webvar{defrec},$webvar{id}); if ($code ne 'OK') { ## need to find failure mode if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $rec{parid}, "Failed deleting default record '$rec{host} $typemap{$rec{type}} $rec{val}', TTL $rec{ttl} ($msg)"); } else { logaction($rec{parid}, $session->param("username"), parentID($rec{parid}, 'dom', 'group'), "Failed deleting record '$rec{host} $typemap{$rec{type}} $rec{val}', TTL $rec{ttl} ($msg)"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, del_failed => 1, errmsg => $msg); $page->param(del_failed => 1); $page->param(errmsg => $msg); showdomain($webvar{defrec}, $webvar{parentid}); } else { if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $rec{parid}, "Deleted default record '$rec{host} $typemap{$rec{type}} $rec{val}', TTL $rec{ttl}"); } else { logaction($rec{parid}, $session->param("username"), parentID($rec{parid}, 'dom', 'group'), "Deleted record '$rec{host} $typemap{$rec{type}} $rec{val}', TTL $rec{ttl}"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } } else { changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } } elsif ($webvar{page} eq 'editsoa') { fillsoa($webvar{defrec},$webvar{id}); } elsif ($webvar{page} eq 'updatesoa') { my $sth; my $sql = ''; # no domain ID, so we're editing the default SOA for a group (we don't care which one here) # plus a bit of magic to update the appropriate table $sql = "update ".($webvar{defrec} eq 'y' ? "default_records" : "records"). " set host='$webvar{prins}:$webvar{contact}',". " val='$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}',". " ttl=$webvar{ttl} where record_id=$webvar{recid}"; $sth = $dbh->prepare($sql); $sth->execute; if ($sth->err) { $page->param(update_failed => 1); $page->param(msg => $DBI::errstr); fillsoa($webvar{defrec},$webvar{id}); } else { ##fixme! need to set group ID properly here # SELECT group_id FROM domains WHERE domain_id=? # $sth->execute($webvar{id}); ##log logaction(0, $session->param("username"), $webvar{group}, "Updated SOA (ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},". " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl}"); changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec}); # $page->param(update_failed => 0); # showdomain('y',1); } } elsif ($webvar{page} eq 'grpman') { listgroups(); $page->param(curpage => $webvar{page}); } elsif ($webvar{page} eq 'newgrp') { # do.. uhh.. stuff.. if we have no webvar{action} if ($webvar{action} && $webvar{action} eq 'add') { my %newperms; foreach (@permtypes) { $newperms{$_} = 0; $newperms{$_} = 1 if $webvar{$_} eq 'on'; } # not gonna provide the 4th param: template-or-clone flag, just yet my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms); if ($code eq 'OK') { logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}"); changepage(page => "grpman"); } # no point in doing extra work fill_permissions($page, \%newperms); $page->param(add_failed => 1); $page->param(errmsg => $msg); $page->param(newgroup => $webvar{newgroup}); fill_grouplist('pargroup',$webvar{pargroup}); } else { fill_grouplist('pargroup',$curgroup); # fill default permissions with immediate parent's current ones my %parperms; getPermissions($dbh, 'group', $curgroup, \%parperms); fill_permissions($page, \%parperms); } } elsif ($webvar{page} eq 'delgrp') { $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); # $page->param(groupname => groupName($dbh,$webvar{id})); # print some neato things? # } else { # #whether actually deleting or cancelling we redirect to the group list, default format } elsif ($webvar{del} eq 'ok') { my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it... my ($code,$msg) = delGroup($dbh, $webvar{id}); if ($code ne 'OK') { # need to find failure mode $page->param(del_failed => 1); $page->param(errmsg => $msg); $page->param(curpage => $webvar{page}); listgroups(); ##fixme: log } else { ##fixme: need to clean up log when deleting a major container logaction(0, $session->param("username"), $webvar{curgroup}, "Deleted group $deleteme"); # success. go back to the domain list, do not pass "GO" changepage(page => "grpman"); } } else { # cancelled. whee! changepage(page => "grpman"); } $page->param(delgroupname => groupName($dbh, $webvar{id})); } elsif ($webvar{page} eq 'edgroup') { if ($webvar{action} eq 'updperms') { # extra safety check; make sure user can't construct a URL to bypass ACLs my %curperms; getPermissions($dbh, 'group', $webvar{gid}, \%curperms); my %chperms; foreach (@permtypes) { $webvar{$_} = 0 if !defined($webvar{$_}); $webvar{$_} = 1 if $webvar{$_} eq 'on'; $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_}; } my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms); if ($code eq 'OK') { logaction(0, $session->param("username"), $webvar{gid}, "Changed default permissions in group $webvar{gid}"); changepage(page => "grpman"); } # no point in doing extra work fill_permissions($page, \%chperms); $page->param(errmsg => $msg); } $page->param(gid => $webvar{gid}); $page->param(grpmeddle => groupName($dbh, $webvar{gid})); my %grpperms; getPermissions($dbh, 'group', $webvar{gid}, \%grpperms); fill_permissions($page, \%grpperms); } elsif ($webvar{page} eq 'useradmin') { if (defined($webvar{action})) { userStatus($dbh,$webvar{id},$webvar{action}); } $page->param(curpage => $webvar{page}); list_users(); } elsif ($webvar{page} eq 'user') { #fill_actypelist($webvar{accttype}); fill_clonemelist(); my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl"); my %noaccess; fill_permissions($grppermlist, \%grpperms, \%noaccess); $grppermlist->param(info => 1); $page->param(grpperms => $grppermlist->output); $page->param(is_admin => $permissions{admin}); $webvar{action} = '' if !$webvar{action}; if ($webvar{action} eq 'add' or $webvar{action} eq 'update') { $page->param(add => 1) if $webvar{action} eq 'add'; my ($code,$msg); my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits my %newperms; # we're going to prefill the existing permissions, so we can change them. getPermissions($dbh, 'user', $webvar{uid}, \%newperms); if ($webvar{pass1} ne $webvar{pass2}) { $code = 'FAIL'; $msg = "Passwords don't match"; } else { # assemble a permission string - far simpler than trying to pass an # indeterminate set of permission flags individually # But first, we have to see if the user can add any particular # permissions; otherwise we have a priviledge escalation. Whee. if (!$permissions{admin}) { my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); my $ret = comparePermissions(\%permissions, \%grpperms); if ($ret ne '<' && $ret ne '!') { # User's permissions are not a superset or equivalent to group. Can't inherit # (and include access user doesn't currently have), so we force custom. $webvar{perms_type} = 'custom'; $alterperms = 1; } } my $permstring; if ($webvar{perms_type} eq 'custom') { $permstring = 'C:'; foreach (@permtypes) { if ($permissions{admin} || $permissions{$_}) { $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on'; $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0); } } $page->param(perm_custom => 1); } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') { $permstring = "c:$webvar{clonesrc}"; getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms); $page->param(perm_clone => 1); } else { $permstring = 'i'; } if ($webvar{action} eq 'add') { ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1}, ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring, $webvar{fname}, $webvar{lname}, $webvar{phone}); } else { # User update is icky. I'd really like to do this in one atomic # operation, but that would duplicate a **lot** of code in DNSDB.pm # Allowing for changing group, but not coding web support just yet. ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1}, ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $webvar{fname}, $webvar{lname}, $webvar{phone}); if ($code eq 'OK') { ##fixme - need to actually get a correct permission set to pass in here, # also a flag to revert custom permissions to inherited ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i')); } } } if ($code eq 'OK') { ##fixme: log doesn't log. WTF? O_o logaction(0, $session->param("username"), $webvar{group}, ($webvar{action} eq 'add' ? 'Added' : 'Updated')." uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})"); if ($alterperms) { changepage(page => "useradmin", warnmsg => "You can only grant permissions you hold. $webvar{uname} ". ($webvar{action} eq 'add' ? 'added' : 'updated')." with reduced access."); } else { changepage(page => "useradmin"); } # add/update failed: } else { $page->param(add_failed => 1); $page->param(action => $webvar{action}); $page->param(set_permgroup => 1); if ($webvar{perms_type} eq 'inherit') { # set permission class radio $page->param(perm_inherit => 1); } elsif ($webvar{perms_type} eq 'clone') { $page->param(perm_clone => 1); } else { $page->param(perm_custom => 1); } $page->param(uname => $webvar{uname}); $page->param(fname => $webvar{fname}); $page->param(lname => $webvar{lname}); $page->param(pass1 => $webvar{pass1}); $page->param(pass2 => $webvar{pass2}); $page->param(errmsg => $msg); fill_permissions($page, \%newperms); fill_actypelist($webvar{accttype}); fill_clonemelist(); ##fixme: log } } elsif ($webvar{action} eq 'edit') { $page->param(set_permgroup => 1); $page->param(action => 'update'); $page->param(uid => $webvar{user}); fill_clonemelist(); my $userinfo = getUserData($dbh,$webvar{user}); fill_actypelist($userinfo->{type}); # not using this yet, but adding it now means we can *much* more easily do so later. $page->param(gid => $webvar{group_id}); my %curperms; getPermissions($dbh, 'user', $webvar{user}, \%curperms); fill_permissions($page, \%curperms); $page->param(uname => $userinfo->{username}); $page->param(fname => $userinfo->{firstname}); $page->param(lname => $userinfo->{lastname}); $page->param(set_permgroup => 1); if ($userinfo->{inherit_perm}) { $page->param(perm_inherit => 1); } else { $page->param(perm_custom => 1); } ##work # } elsif ($webvar{action} eq 'update') { } else { # default is "new" $page->param(add => 1); $page->param(action => 'add'); fill_permissions($page, \%grpperms); fill_actypelist(); } } elsif ($webvar{page} eq 'newuser') { # foo? fill_actypelist(); fill_clonemelist(); my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); fill_permissions($page, \%grpperms); my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl"); my %noaccess; fill_permissions($grppermlist, \%grpperms, \%noaccess); $grppermlist->param(info => 1); $page->param(grpperms => $grppermlist->output); #} elsif ($webvar{page} eq 'adduser') { # # my ($code,$msg); # # if ($webvar{pass1} ne $webvar{pass2}) { # $code = 'FAIL'; # $msg = "Passwords don't match"; # } else { ## assemble a permission string - far simpler than trying to pass an ## indeterminate set of permission flags individually #my $permstring; #if ($webvar{perms_type} eq 'custom') { # $permstring = 'C:,g:,u:,d:,r:'; # $page->param(perm_custom => 1); #} elsif ($webvar{perms_type} eq 'clone') { # $permstring = 'c:'; # $page->param(perm_clone => 1); #} else { # $permstring = 'i'; ## $page->param(perm_inherit => 1); #} # ($code,$msg) = addUser($dbh,$webvar{uname}, $webvar{group}, $webvar{pass1}, # ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, # $webvar{fname}, $webvar{lname}, $webvar{phone}); # } # ## hokay, a bit of magic to decide which page we hit. # if ($code eq 'OK') { ###log # logaction(0, $session->param("username"), $webvar{group}, # "Added user $webvar{uname} ($webvar{fname} $webvar{lname})"); # changepage(page => "useradmin"); # } else { ## oddity - apparently, xhtml 1.0 strict swallows username as an HTML::Template var. O_o # $page->param(add_failed => 1); # $page->param(uname => $webvar{uname}); # $page->param(fname => $webvar{fname}); # $page->param(lname => $webvar{lname}); # $page->param(pass1 => $webvar{pass1}); # $page->param(pass2 => $webvar{pass2}); # $page->param(errmsg => $msg); # fill_actypelist($webvar{accttype}); # fill_clonemelist(); # } # ## $page->param(add_failed => 1); # #} elsif ($webvar{page} eq 'deluser') { # # $page->param(id => $webvar{id}); # # first pass = confirm y/n (sorta) # if (!defined($webvar{del})) { # $page->param(del_getconf => 1); # $page->param(user => userFullName($dbh,$webvar{id})); # } elsif ($webvar{del} eq 'ok') { ###fixme: find group id user is in (for logging) *before* we delete the user # my ($code,$msg) = delUser($dbh, $webvar{id}); # if ($code ne 'OK') { ## need to find failure mode # $page->param(del_failed => 1); # $page->param(errmsg => $msg); # list_users($curgroup); # } else { # # success. go back to the user list, do not pass "GO" ###log # logaction(0, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}"); # changepage(page => "useradmin"); # } # } else { # # cancelled. whee! # changepage(page => "useradmin"); # } # #} elsif ($webvar{page} eq 'edituser') { } elsif ($webvar{page} eq 'dnsq') { $page->param(qfor => $webvar{qfor}) if $webvar{qfor}; fill_rectypes($webvar{type} ? $webvar{type} : '', 1); $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse}; $page->param(resolver => $webvar{resolver}) if $webvar{resolver}; if ($webvar{qfor}) { my $resolv = Net::DNS::Resolver->new; $resolv->tcp_timeout(5); # make me adjustable! $resolv->udp_timeout(5); # make me adjustable! $resolv->recurse(0) if $webvar{nrecurse}; $resolv->nameservers($webvar{resolver}) if $webvar{resolver}; my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}}); if ($query) { $page->param(showresults => 1); my @answer; foreach my $rr ($query->answer) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s); $row{host} = $host; $row{ftype} = $type; $row{rdata} = ($type eq 'SOA' ? "
$data
" : $data); push @answer, \%row; } $page->param(answer => \@answer); my @additional; foreach my $rr ($query->additional) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/); $row{host} = $host; $row{ftype} = $type; $row{rdata} = $data; push @additional, \%row; } $page->param(additional => \@additional); my @authority; foreach my $rr ($query->authority) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/); $row{host} = $host; $row{ftype} = $type; $row{rdata} = $data; push @authority, \%row; } $page->param(authority => \@authority); $page->param(usedresolver => $resolv->answerfrom); $page->param(frtype => $typemap{$webvar{type}}); } else { $page->param(errmsg => $resolv->errorstring); } } ## done DNS query } elsif ($webvar{page} eq 'axfr') { # don't need this while we've got the dropdown in the menu. hmm. #fill_grouplist; $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom}; $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa}; $page->param(rwns => $webvar{rwns}) if $webvar{rwns}; $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww. $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms}; ##fixme: check group too? if ($webvar{doit} eq 'y' && !$webvar{ifrom}) { $page->param(errmsg => "Need to set host to import from"); } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) { $page->param(errmsg => "Need domains to import"); } else { my @domlist = split /\s+/, $webvar{importdoms}; my @results; my $rnum = 0; foreach my $domain (@domlist) { my %row; my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group}, $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns}); ##fixme: log $row{domok} = $msg if $code eq 'OK'; if ($code eq 'WARN') { $msg =~ s|\n|
|g; $row{domwarn} = $msg; } if ($code eq 'FAIL') { $msg =~ s|\n|
|g; $row{domerr} = $msg; } # do stuff! DNSDB::importAXFR($webvar{ifrom}, $webvar{rwsoa}, $webvar{rwns}, $domain, ) $row{domain} = $domain; # $row{row} = $rnum++; push @results, \%row; } $page->param(axfrresults => \@results); } } elsif ($webvar{page} eq 'whoisq') { if ($webvar{qfor}) { use Net::Whois::Raw; use Text::Wrap; # caching useful? #$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/"; #$Net::Whois::Raw::CACHE_TIME = 60; my ($dominfo, $whois_server) = whois($webvar{qfor}); ##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data # le sigh. idjits spit out data without linefeeds... $Text::Wrap::columns = 88; # &%$@%@# high-bit crap. We should probably find a way to properly recode these instead of one-by-one. # Mainly an XHTML validation thing. $dominfo =~ s/\xa9/\©/g; $dominfo =~ s/\xae/\®/g; $page->param(qfor => $webvar{qfor}); $page->param(dominfo => wrap('','',$dominfo)); $page->param(whois_server => $whois_server); } else { $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway}; } } elsif ($webvar{page} eq 'log') { ##fixme put in some real log-munching stuff ##fixme need to add bits to *create* log entries... my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE "; my $id = $curgroup; # we do this because the group log may be called from (almost) any page, # but the others are much more limited. this is probably non-optimal. if ($webvar{ltype} && $webvar{ltype} eq 'user') { $sql .= "user_id=?"; $id = $webvar{id}; $page->param(logfor => 'user '.userFullName($dbh,$id)); } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') { $sql .= "domain_id=?"; $id = $webvar{id}; $page->param(logfor => 'domain '.domainName($dbh,$id)); } else { # Default to listing curgroup log $sql .= "group_id=?"; $page->param(logfor => 'group '.groupName($dbh,$id)); } my $sth = $dbh->prepare($sql); $sth->execute($id); my @logbits; while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) { my %row; $row{userfname} = $name; $row{userid} = $uid; $row{useremail} = $email; $row{logentry} = $entry; ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/); push @logbits, \%row; } $page->param(logentries => \@logbits); } # end $webvar{page} dance # start output here so we can redirect pages. print "Content-type: text/html\n\n", $header->output; ##common bits if ($webvar{page} ne 'login') { $page->param(username => $session->param("username")); $page->param(group => $curgroup); $page->param(groupname => groupName($dbh,$curgroup)); $page->param(logingrp => groupName($dbh,$logingroup)); # group tree. should go elsewhere, probably my $tmpgrplist = fill_grptree($logingroup,$curgroup); $page->param(grptree => $tmpgrplist); $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean $page->param(inlogingrp => $curgroup == $logingroup); # stuff for menu group change. nb: this is icky. fill_grouplist("grouplist"); ## set up "URL to self" # @#$%@%@#% XHTML - & in a URL must be escaped. >:( my $tmp_ruri = $ENV{REQUEST_URI}; $tmp_ruri =~ s/\&([a-z])/\&\;$1/g; # le sigh. and we need to strip any previous action $tmp_ruri =~ s/\&action=[^&]+//g; # and search filter options. these get stored in the session, but discarded # as soon as you switch to a different page. ##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits no warnings qw(uninitialized); $tmp_ruri =~ s/\&startwith=[a-z09-]*(\&)?/$1/g; $tmp_ruri =~ s/\&searchsubs=[a-z09-]*(\&)?/$1/g; $tmp_ruri =~ s/\&filter=[a-z09-]*(\&)?/$1/g; use warnings qw(uninitialized); # fill in the URL-to-self $page->param(whereami => $tmp_ruri); } print "
\n";
foreach (@debugbits) { print; }
print "
\n"; # spit it out print $page->output; if ($debugenv) { print "
webvar keys:
\n";
  foreach my $key (keys %webvar) {
    print "key: $key\tval: $webvar{$key}\n";
  }
  print "
\nsession:\n
\n";
  my $sesdata = $session->dataref();
  foreach my $key (keys %$sesdata) {
    print "key: $key\tval: ".$sesdata->{$key}."\n";
  }
  print "
\nENV:\n
\n";
  foreach my $key (keys %ENV) {
    print "key: $key\tval: $ENV{$key}\n";
  }
  print "
\n"; } print $footer->output; # as per the docs, Just In Case $session->flush(); exit 0; sub fill_grptree { my $root = shift; my $cur = shift; my $indent = shift || ' '; my @childlist; my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl'); getChildren($dbh,$root,\@childlist,'immediate'); return if $#childlist == -1; my @grouplist; foreach (@childlist) { my %row; $row{grpname} = groupName($dbh,$_); # for all that HTML::Template is supposed to keep the HTML out of the Perl, this is so much more compact... $row{grpdisp} = ($_ == $cur ? "$row{grpname}" : $row{grpname}); $row{subs} = fill_grptree($_,$cur,$indent.' '); $row{indent} = $indent; push @grouplist, \%row; } $grptree->param(indent => $indent); $grptree->param(treelvl => \@grouplist); return $grptree->output; } sub changepage { my %params = @_; # think this works the way I want... # handle user check my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid"; foreach (keys %params) { $newurl .= "&$_=$params{$_}"; } # Just In Case $session->flush(); print "Status: 302\nLocation: $newurl\n\n"; exit; } # end changepage sub fillsoa { my $def = shift; my $id = shift; my $domname = ($def eq 'y' ? '' : "DOMAIN"); $page->param(defrec => $def); # i had a good reason to do this when I wrote it... # $page->param(domain => $domname); # $page->param(group => $DNSDB::group); $page->param(isgrp => 1) if $def eq 'y'; $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) ); # defaults $page->param(defcontact => $DNSDB::def{contact}); $page->param(defns => $DNSDB::def{prins}); $page->param(defsoattl => $DNSDB::def{soattl}); $page->param(defrefresh => $DNSDB::def{refresh}); $page->param(defretry => $DNSDB::def{retry}); $page->param(defexpire => $DNSDB::def{expire}); $page->param(defminttl => $DNSDB::def{minttl}); # there are probably better ways to do this. TMTOWTDI. my %soa = getSOA($dbh,$def,$id); $page->param(id => $id); $page->param(recid => $soa{recid}); $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins})); $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact})); $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh})); $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry})); $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire})); $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl})); $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl})); } sub showdomain { my $def = shift; my $id = shift; # get the SOA first my %soa = getSOA($dbh,$def,$id); $page->param(recid => $soa{recid}); $page->param(contact => $soa{contact}); $page->param(prins => $soa{prins}); $page->param(refresh => $soa{refresh}); $page->param(retry => $soa{retry}); $page->param(expire => $soa{expire}); $page->param(minttl => $soa{minttl}); $page->param(ttl => $soa{ttl}); $startwith = $session->param($webvar{page}.'startwith'); $filter = $session->param($webvar{page}.'filter'); my $foo2 = getDomRecs($dbh,$def,$id,$perpage,$webvar{offset},$sortby,$sortorder); my $row = 0; foreach my $rec (@$foo2) { $rec->{type} = $typemap{$rec->{type}}; $rec->{row} = $row % 2; $rec->{defrec} = $def; $rec->{sid} = $webvar{sid}; $rec->{id} = $id; $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV'); $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV'); $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV'); $row++; } $page->param(reclist => $foo2); } # fill in record type list on add/update/edit record template sub fill_rectypes { my $type = shift || $reverse_typemap{A}; my $soaflag = shift || 0; my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder"); $sth->execute; my @typelist; while (my ($rval,$rname) = $sth->fetchrow_array()) { my %row = ( recval => $rval, recname => $rname ); $row{tselect} = 1 if $rval == $type; push @typelist, \%row; } if ($soaflag) { my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' ); $row{tselect} = 1 if $reverse_typemap{SOA} == $type; push @typelist, \%row; } $page->param(typelist => \@typelist); } # fill_rectypes sub fill_recdata { fill_rectypes($webvar{type}); $page->param(name => $webvar{name}); $page->param(address => $webvar{address}); $page->param(distance => $webvar{distance}) if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}); $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV}; $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV}; $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $DNSDB::def{minttl})); } sub fill_actypelist { my $curtype = shift || 'u'; my @actypes; my %row1 = (actypeval => 'u', actypename => 'user'); $row1{typesel} = 1 if $curtype eq 'u'; push @actypes, \%row1; my %row2 = (actypeval => 'S', actypename => 'superuser'); $row2{typesel} = 1 if $curtype eq 'S'; push @actypes, \%row2; $page->param(actypelist => \@actypes); } sub fill_clonemelist { my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup"); $sth->execute; # shut up some warnings, but don't stomp on caller's state local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc}); my @clonesrc; while (my ($username,$uid) = $sth->fetchrow_array) { my %row = ( username => $username, uid => $uid, selected => ($webvar{clonesrc} == $uid ? 1 : 0) ); push @clonesrc, \%row; } $page->param(clonesrc => \@clonesrc); } sub fill_fpnla { my $count = shift; ##fixme if ($offset eq 'all') { $page->param(perpage => $perpage); # uhm.... } else { # all these bits only have sensible behaviour if offset is numeric. err, probably. if ($count > $perpage) { # if there are more results than the default, always show the "all" link $page->param(navall => 1); if ($offset > 0) { $page->param(navfirst => 1); $page->param(navprev => 1); $page->param(prevoffs => $offset-1); } # show "next" and "last" links if we're not on the last page of results if ( (($offset+1) * $perpage - $count) < 0 ) { $page->param(navnext => 1); $page->param(nextoffs => $offset+1); $page->param(navlast => 1); $page->param(lastoffs => int (($count-1)/$perpage)); } } else { $page->param(onepage => 1); } } } # end fill_fpnla() sub fill_pgcount { my $pgcount = shift; my $pgtype = shift; my $parent = shift; $page->param(ntot => $pgcount); $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1)); $page->param(npglast => ($offset eq 'all' ? $pgcount : ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) ) )); $page->param(pgtype => $pgtype); $page->param(parent => $parent); } # end fill_pgcount() sub listdomains { $startwith = $session->param($webvar{page}.'startwith'); $filter = $session->param($webvar{page}.'filter'); $searchsubs = $session->param($webvar{page}.'searchsubs'); ##fixme: $logingroup or $curgroup? my @childgroups; getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND domain ~* '^[$startwith]'" : ''). ($filter ? " AND domain ~* '$filter'" : ''); my $sth = $dbh->prepare($sql); $sth->execute; my ($count) = $sth->fetchrow_array; # fill page count and first-previous-next-last-all bits ##fixme - hardcoded group bit fill_pgcount($count,"domains",groupName($dbh,$curgroup)); fill_fpnla($count); # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order'); # set up the headers my @cols = ('domain', 'status', 'group'); my %colheads = (domain => 'Domain', status => 'Status', group => 'Group'); fill_colheads($sortby, $sortorder, \@cols, \%colheads); # $page->param(sortorder => $sortorder); # hack! hack! pthbttt. have to rethink the status column storage, # or inactive comes "before" active. *sigh* $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status'; # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; ##fixme ##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm ##fixme $page->param(group => $curgroup); my @domlist; $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains". " INNER JOIN groups ON domains.group_id=groups.group_id". " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ##fixme: don't do variable subs in SQL, use placeholders and params in ->execute() ($startwith ? " AND domain ~* '^[$startwith]'" : ''). ($filter ? " AND domain ~* '$filter'" : ''). " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $sortby). " $sortorder ".($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute; my $rownum = 0; while (my @data = $sth->fetchrow_array) { my %row; $row{domainid} = $data[0]; $row{domain} = $data[1]; $row{status} = ($data[2] ? 'Active' : 'Inactive'); $row{group} = $data[3]; $row{bg} = ($rownum++)%2; # $row{mkactive} = ($data[2] eq 'inactive' ? 1 : 0); $row{mkactive} = !$data[2]; $row{sid} = $sid; $row{offset} = $offset; ##fixme: need to clean up status indicator/usage/inversion push @domlist, \%row; } $page->param(domtable => \@domlist); } # end listdomains() sub listgroups { my @childgroups; getChildren($dbh, $logingroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND group_name ~* '^[$startwith]'" : ''). ($filter ? " AND group_name ~* '$filter'" : ''); my $sth = $dbh->prepare($sql); $sth->execute; my ($count) = ($sth->fetchrow_array); # fill page count and first-previous-next-last-all bits ##fixme - hardcoded group bit fill_pgcount($count,"groups",''); fill_fpnla($count); $page->param(gid => $curgroup); # $sortby = 'group'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order'); # set up the headers my @cols = ('group','parent','nusers','ndomains'); my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains'); fill_colheads($sortby, $sortorder, \@cols, \%colnames); # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; # munge sortby for columns in database $sortby = 'g.group_name' if $sortby eq 'group'; $sortby = 'g2.group_name' if $sortby eq 'parent'; my @grouplist; $sth = $dbh->prepare("SELECT g.group_id, g.group_name, g2.group_name, ". "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ". "FROM groups g ". "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ". "LEFT OUTER JOIN users u ON u.group_id=g.group_id ". "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ". "WHERE g.parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').") ". ##fixme: don't do variable subs in SQL, use placeholders and params in ->execute() ($startwith ? " AND g.group_name ~* '^[$startwith]'" : ''). ($filter ? " AND g.group_name ~* '$filter'" : ''). " GROUP BY g.group_id, g.group_name, g2.group_name ". " ORDER BY $sortby $sortorder ". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage)); $sth->execute; my $rownum = 0; while (my @data = $sth->fetchrow_array) { my %row; $row{groupid} = $data[0]; $row{groupname} = $data[1]; $row{pgroup} = $data[2]; $row{nusers} = $data[3]; $row{ndomains} = $data[4]; $row{bg} = ($rownum++)%2; $row{sid} = $sid; push @grouplist, \%row; } $page->param(grouptable => \@grouplist); } # end listgroups() sub fill_grouplist { my $template_var = shift; my $cur = shift || $curgroup; my @childgroups; getChildren($dbh, $logingroup, \@childgroups, 'all'); my $childlist = join(',',@childgroups); # weesa gonna discard parent_group_id for now my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ". "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")". "ORDER BY group_id"); $sth->execute; my @grouplist; while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) { my %row; $row{groupname} = $groupname; $row{groupval} = $groupid; ##fixme: need magic # $row{defgroup} = ''; $row{groupactive} = 1 if $groupid == $cur; push @grouplist, \%row; } $page->param("$template_var" => \@grouplist); } # end fill_grouplist() sub list_users { my @childgroups; getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND username ~* '^[$startwith]'" : ''). ($filter ? " AND username ~* '$filter'" : ''); my $sth = $dbh->prepare($sql); $sth->execute; my ($count) = ($sth->fetchrow_array); # fill page count and first-previous-next-last-all bits ##fixme - hardcoded group bit fill_pgcount($count,"users",''); fill_fpnla($count); # $sortby = 'user'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order'); # set up the headers my @cols = ('user','fname','type','group','status'); my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status'); fill_colheads($sortby, $sortorder, \@cols, \%colnames); # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; # munge sortby for columns in database $sortby = 'u.username' if $sortby eq 'user'; $sortby = 'u.type' if $sortby eq 'type'; $sortby = 'g.group_name' if $sortby eq 'group'; $sortby = 'u.status' if $sortby eq 'status'; my @userlist; $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ". "FROM users u ". "INNER JOIN groups g ON u.group_id=g.group_id ". "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ##fixme: don't do variable subs in SQL, use placeholders and params in ->execute() ($startwith ? " AND u.username ~* '^[$startwith]'" : ''). ($filter ? " AND u.username ~* '$filter'" : ''). " ORDER BY $sortby $sortorder ". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute; my $rownum = 0; while (my @data = $sth->fetchrow_array) { no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name my %row; $row{userid} = $data[0]; $row{username} = $data[1]; $row{userfull} = $data[2]; $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user"); $row{usergroup} = $data[4]; $row{active} = $data[5]; $row{bg} = ($rownum++)%2; $row{sid} = $sid; push @userlist, \%row; } $page->param(usertable => \@userlist); } # end list_users() # Generate all of the glop necessary to add or not the appropriate marker/flag for # the sort order and column in domain, user, group, and record lists # Takes an array ref and hash ref sub fill_colheads { my $sortby = shift; my $sortorder = shift; my $cols = shift; my $colnames = shift; my $custom = shift; my @headings; foreach my $col (@$cols) { my %coldata; $coldata{firstcol} = 1 if $col eq $cols->[0]; $coldata{sid} = $sid; $coldata{page} = $webvar{page}; $coldata{offset} = $webvar{offset} if $webvar{offset}; $coldata{sortby} = $col; $coldata{colname} = $colnames->{$col}; if ($col eq $sortby) { $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC'); $coldata{sortorder} = $sortorder; } else { $coldata{order} = 'ASC'; } if ($custom) { foreach my $ckey (keys %$custom) { $coldata{$ckey} = $custom->{$ckey}; } } push @headings, \%coldata; } $page->param(colheads => \@headings); } # end fill_colheads() sub logaction { my $domid = shift; my $username = shift; my $groupid = shift; my $entry = shift; ##fixme: ooohhh, nasty. what if we get a failure *here*? PTHBTT! my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?"); $sth->execute($username); my ($user_id, $fullname) = $sth->fetchrow_array; $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) ". "VALUES (?,?,?,?,?,?)"); $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry); } # end logaction() ##fixme: generalize to return appropriate id on all cases (ie, use $partype) sub parentID { my $id = shift; my $idtype = shift; my $partype = shift; my $defrec = shift || ''; my $sql = ''; if ($idtype eq 'dom') { return $id if $defrec eq 'y'; # "domain" + default records, we're really looking at a group. $sql = "SELECT group_id FROM domains WHERE domain_id=?"; } elsif ($idtype eq 'rec') { if ($defrec eq 'y') { $sql = "SELECT group_id FROM default_records WHERE record_id=?"; } else { return $sql = "SELECT d.group_id FROM domains d". " INNER JOIN records r ON d.domain_id=r.domain_id". " WHERE r.record_id=?"; } } elsif ($idtype eq 'group') { $sql = "SELECT parent_group_id FROM groups WHERE group_id=?"; } elsif ($idtype eq 'user') { $sql = "SELECT group_id FROM users WHERE user_id=?"; } else { return "FOO", "BAR"; # can't get here.... we think. } my $sth = $dbh->prepare($sql); $sth->execute($id); my ($retid) = $sth->fetchrow_array; return $retid if $retid; # ahh! fall of the edge of the world if things went sideways ##fixme: really need to do a little more error handling, I think } # end parentID() # we have to do this in a variety of places; let's make it consistent sub fill_permissions { my $template = shift; # may need to do several sets on a single page my $permset = shift; # hashref to permissions on object my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block foreach (@permtypes) { $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_})); $template->param($_ => $permset->{$_}); } }