#!/usr/bin/perl
###############################################################################
# Copyright 2006-2012, Way to the Web Limited
# URL: http://www.configserver.com
# Email: sales@waytotheweb.com
###############################################################################
# start main
use lib '/etc/csf';
use Net::CIDR::Lite;
use LWP::UserAgent;

$ipscidr6 = Net::CIDR::Lite->new;
$ipv4reg = $ipv6reg = qr/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/;
if ($config{IPV6}) {$ipv6reg = qr/((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?/}

&loadconfig;

$chart = 1;
if ($config{ST_ENABLE}) {
	eval ('use GD::Graph::bars;');
	if ($@) {$chart = 0}
	eval ('use GD::Graph::pie;');
	if ($@) {$chart = 0}
	eval ('use GD::Graph::lines;');
	if ($@) {$chart = 0}
}

my $csfjs = <<EOF;
<script language="JavaScript">
var isNav4, isNav6, isIE4;
setBrowser();

function setBrowser()
{
    if (navigator.appVersion.charAt(0) == "4")
    {
        if (navigator.appName.indexOf("Explorer") >= 0)
        {
            isIE4 = true;
        }
        else
        {
            isNav4 = true;
        }
    }
    else if (navigator.appVersion.charAt(0) > "4")
    {
        isNav6 = true;
    }
}

function getStyleBySelector( selector )
{
    if (!isNav6)
    {
        return null;
    }
    var sheetList = document.styleSheets;
    var ruleList;
    var i, j;

    /* look through stylesheets in reverse order that
       they appear in the document */
    for (i=sheetList.length-1; i >= 0; i--)
    {
        ruleList = sheetList[i].cssRules;
        for (j=0; j<ruleList.length; j++)
        {
            if (ruleList[j].type == CSSRule.STYLE_RULE &&
                ruleList[j].selectorText == selector)
            {
                return ruleList[j].style;
            }   
        }
    }
    return null;
}

function getIdProperty( id, property )
{
    if (isNav6)
    {
        var styleObject = document.getElementById( id );
        if (styleObject != null)
        {
            styleObject = styleObject.style;
            if (styleObject[property])
            {
                return styleObject[ property ];
            }
        }
        styleObject = getStyleBySelector( "#" + id );
        return (styleObject != null) ?
            styleObject[property] :
            null;
    }
    else if (isNav4)
    {
        return document[id][property];
    }
    else
    {
        return document.all[id].style[property];
    }
}

function setIdProperty( id, property, value )
{
    if (isNav6)
    {
        var styleObject = document.getElementById( id );
        if (styleObject != null)
        {
            styleObject = styleObject.style;
            styleObject[ property ] = value;
        }
        
    }
    else if (isNav4)
    {
        document[id][property] = value;
    }
    else if (isIE4)
    {
         document.all[id].style[property] = value;
    }
}

function showMenu( divNum )
{
    if (getIdProperty( "s" + divNum, "display") != "block" )
    {
        setIdProperty("s" + divNum, "display", "block");
        document.images["i" + divNum].src = "$images/minus.png";
    }
    else
    {
        setIdProperty("s" + divNum, "display", "none");
        document.images["i" + divNum].src = "$images/plus.png";
    }
}

function expandO( ec ,totNum )
{
    for (j=1; j<totNum + 1; j++)
    {
            if (ec == "expand")
            {
                setIdProperty("s" + j, "display", "block");
                document.images["i" + j].src = "$images/minus.png";
            }
            else
            {
                setIdProperty("s" + j, "display", "none");
                document.images["i" + j].src = "$images/plus.png";
            }
    }
}
</script>
EOF

if ($FORM{action} eq "lfdstatus") {
	print "<p>Show lfd status...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("/etc/init.d/lfd status");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "ms_list") {
	&modsec;
}
elsif ($FORM{action} eq "chart") {
	&chart;
}
elsif ($FORM{action} eq "systemstats") {
	&systemstats($FORM{graph});
}
elsif ($FORM{action} eq "ms_config") {
	sysopen (IN, "/usr/local/apache/conf/$FORM{template}", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='savems_config'>\n";
	print "<input type='hidden' name='template' value='$FORM{template}'>\n";
	print "<fieldset><legend><b>Edit $FORM{template}</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='80' rows='40' style='font-family: Courier New, Courier; font-size: 12px' wrap='off'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\&/\&amp\;/g;
		$line =~ s/>/\&gt\;/g;
		$line =~ s/</\&lt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "savems_config") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/usr/local/apache/conf/$FORM{template}", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr><th align='left'>ModSecurity save $FORM{template}</th></tr>";
	print "<tr bgcolor='#F4F4EA'><td>You should restart Apache having changed this file</td></tr>\n";
	print "</table>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "lfdstart") {
	print "<p>Starting lfd...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("/etc/init.d/lfd start");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "lfdrestart") {
	if ($config{DIRECTADMIN} or $config{THIS_UI}) {
		print "<p>Signal lfd to <i>restart</i>...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		sysopen (OUT, "/etc/csf/lfd.restart",, O_WRONLY | O_CREAT) or die "Unable to open file: $!";
		close (OUT);
	} else {
		print "<p>Restarting lfd...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		&printcmd("/etc/init.d/lfd restart");
	}
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "lfdstop") {
	print "<p>Stopping lfd...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("/etc/init.d/lfd stop");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "status") {
	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr><td><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -l");
	if ($config{IPV6}) {print "\n\nip6tables:\n\n"; &printcmd("perl /etc/csf/csf.pl -l6")}
	print "</pre></td></tr></table>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "start") {
	print "<p>Starting csf...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -sf");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "restart") {
	print "<p>Restarting csf...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -sf");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "restartq") {
	print "<p>Restarting csf via lfd...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -q");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "temp") {
	my $class = '#F4F4EA';
	print "<table align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='FFFFFF' style='border:1px solid #990000'\n";
	print "<tr><th>&nbsp;</th><th>A/D</th><th>IP address</th><th>Port</th><th>Dir</th><th>Time To Live</th><th>Comment</th></tr>\n";
	my @deny;
	if (! -z "/etc/csf/csf.tempban") {
		open (IN, "</etc/csf/csf.tempban") or die $!;
		@deny = <IN>;
		chomp @deny;
		close (IN);
	}
	foreach my $line (@deny) {
		if ($line eq "") {next}
		my ($time,$ip,$port,$inout,$timeout,$message) = split(/\|/,$line);
		$time = $timeout - (time - $time);
		if ($port eq "") {$port = "*"}
		if ($inout eq "") {$inout = " *"}
		if ($time < 1) {
			$time = "<1";
		} else {
			my $days = int($time/(24*60*60));
			my $hours = ($time/(60*60))%24;
			my $mins = ($time/60)%60;
			my $secs = $time%60;
			$days = $days < 1 ? '' : $days .'d ';
			$hours = $hours < 1 ? '' : $hours .'h ';
			$mins = $mins < 1 ? '' : $mins . 'm ';
			$time = $days . $hours . $mins . $secs . 's'; 
		}
		print "<tr bgcolor='$class'><td>&nbsp;<a href='$script?action=temprm&ip=$ip'><img src='$images/delete.png' border='0' alt='Unblock $ip?'></a>&nbsp;<a href='$script?action=temptoperm&ip=$ip'><img src='$images/perm.png' border='0' alt='Permanently $ip?'></a>&nbsp;</td><td>DENY</td><td>$ip</td><td>$port</td><td>$inout</td><td>$time</td><td>$message</td></tr>\n";
		if ($class eq '#FFFFFF') {$class = '#F4F4EA'} else {$class = '#FFFFFF'}
	}
	my @allow;
	if (! -z "/etc/csf/csf.tempallow") {
		open (IN, "</etc/csf/csf.tempallow") or die $!;
		@allow = <IN>;
		chomp @allow;
		close (IN);
	}
	foreach my $line (@allow) {
		if ($line eq "") {next}
		my ($time,$ip,$port,$inout,$timeout,$message) = split(/\|/,$line);
		$time = $timeout - (time - $time);
		if ($port eq "") {$port = "*"}
		if ($inout eq "") {$inout = " *"}
		if ($time < 1) {
			$time = "<1";
		} else {
			my $days = int($time/(24*60*60));
			my $hours = ($time/(60*60))%24;
			my $mins = ($time/60)%60;
			my $secs = $time%60;
			$days = $days < 1 ? '' : $days .'d ';
			$hours = $hours < 1 ? '' : $hours .'h ';
			$mins = $mins < 1 ? '' : $mins . 'm ';
			$time = $days . $hours . $mins . $secs . 's'; 
		}
		print "<tr bgcolor='$class'><td>&nbsp;<a href='$script?action=temprm&ip=$ip'><img src='$images/delete.png' border='0' alt='Unblock $ip?'></a>&nbsp;</td><td>ALLOW</td><td>$ip</td><td>$port</td><td>$inout</td><td>$time</td><td>$message</td></tr>\n";
		if ($class eq '#FFFFFF') {$class = '#F4F4EA'} else {$class = '#FFFFFF'}
	}
	print "</table>\n";
	if (@deny or @allow) {
		print "<p align='center'>Flush all temporary IP entries <a href='$script?action=temprm&ip=all'><img src='$images/delete.png' border='0' alt='Unblock All IPs?' valign='middle'></a></p>\n";
		print "<p align='center'>Key: <img src='$images/delete.png' border='0' alt='Unblock'>=Unblock IP, <img valign='middle' src='$images/perm.png' border='0' alt='Permanently Block'>=Permanently Block IP</p>\n";
	} else {
		print "<p align='center'>There are no temporary IP entries</p>\n";
	}
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "temprm") {
	print "<p>Removing temporary ban for $FORM{ip}:</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	if ($FORM{ip} eq "all") {
		&printcmd("perl /etc/csf/csf.pl -tf");
	} else {
		&printcmd("perl /etc/csf/csf.pl -tr $FORM{ip}");
	}
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='temp'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "temptoperm") {
	print "<p>Permanent ban for $FORM{ip}:</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -tr $FORM{ip} ; perl /etc/csf/csf.pl -d $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='temp'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "tempdeny") {
	if ($FORM{dur} eq "minutes") {$FORM{timeout} = $FORM{timeout} * 60}
	if ($FORM{dur} eq "hours") {$FORM{timeout} = $FORM{timeout} * 60 * 60}
	if ($FORM{dur} eq "days") {$FORM{timeout} = $FORM{timeout} * 60 * 60 * 24}
	print "<p>Temporarily $FORM{do}ing $FORM{ip} for $FORM{timeout} seconds:</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	if ($FORM{do} eq "block") {
		&printcmd("perl /etc/csf/csf.pl -td $FORM{ip} $FORM{timeout}");
	} else {
		&printcmd("perl /etc/csf/csf.pl -ta $FORM{ip} $FORM{timeout}");
	}
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "stop") {
	print "<p>Stopping csf...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -f");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "disable") {
	print "<p>Disabling csf...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -x");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "enable") {
	if ($config{DIRECTADMIN} or $config{THIS_UI}) {
		print "<p>Due to restrictions in DirectAdmin you must login to the root shell to enable csf using:\n<p><b>csf -e</b>\n";
	} else {
		print "<p>Enabling csf...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		&printcmd("perl /etc/csf/csf.pl -e");
		print "</pre>";
	}
	print "</p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "tail") {
	print "<p>Displaying the last $FORM{lines} lines of /var/log/lfd.log...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("tail -$FORM{lines} /var/log/lfd.log");
	print "</pre></p>\n";
	if ($FORM{refresh}) {
print <<EOF;
<script language="JavaScript">

//Refresh page script- By Brett Taylor (glutnix\@yahoo.com.au)
//Modified by Dynamic Drive for NS4, NS6+
//Visit http://www.dynamicdrive.com for this script

//configure refresh interval (in seconds)
var countDownInterval=5;
//configure width of displayed text, in px (applicable only in NS4)
var c_reloadwidth=200
var page_url = "$script?action=tail&lines=$FORM{lines}&refresh=$FORM{refresh}";
</script>


<ilayer id="c_reload" width=&{c_reloadwidth}; ><layer id="c_reload2" width=&{c_reloadwidth}; left=0 top=0></layer></ilayer>

<script>

var countDownTime=countDownInterval+1;
function countDown(){
countDownTime--;
if (countDownTime <0){
countDownTime=countDownInterval;
clearTimeout(counter);
window.location.href=page_url;
return
}
if (document.all) //if IE 4+
document.all.countDownText.innerText = countDownTime+" ";
else if (document.getElementById) //else if NS6+
document.getElementById("countDownText").innerHTML=countDownTime+" "
else if (document.layers){ //CHANGE TEXT BELOW TO YOUR OWN
document.c_reload.document.c_reload2.document.write('This page will <b><u><a href="javascript:window.location.href=page_url">refresh</a></u></b> in <b id="countDownText">'+countDownTime+' </b> seconds')
document.c_reload.document.c_reload2.document.close()
}
counter=setTimeout("countDown()", 1000);
}

function startit(){
if (document.all||document.getElementById) //CHANGE TEXT BELOW TO YOUR OWN
document.write('This page will <b><u><a href="javascript:window.location.href=page_url">refresh</a></u></b> in <b id="countDownText">'+countDownTime+' </b> seconds')
countDown()
}

if (document.all||document.getElementById)
startit()
else
window.onload=startit

</script>
EOF
	}
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "readme") {
	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr><td><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	open (IN, "</etc/csf/readme.txt") or die $!;
	my @readme = <IN>;
	close (IN);
	chomp @readme;

	foreach my $line (@readme) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</pre></td></tr></table>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "servercheck") {
	do "/etc/csf/servercheck.pm";

	open (IN, "</etc/cron.d/csfcron.sh");
	flock (IN, LOCK_SH);
	my @data = <IN>;
	close (IN);
	chomp @data;
	my $optionselected = "never";
	my $email;
	if (my @ls = grep {$_ =~ /csf \-m/} @data) {
		if ($ls[0] =~ /\@(\w+)\s+root\s+\/usr\/sbin\/csf -m (.*)/) {$optionselected = $1; $email = $2}
	}
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='serverchecksave'>\n";
	print "Generate and email this report <select name='freq'>\n";
	foreach my $option ("never","hourly","daily","weekly","monthly") {
		if ($option eq $optionselected) {print "<option selected>$option</option>\n"} else {print "<option>$option</option>\n"}
	}
	print "</select> to the email address <input type='text' name='email' value='$email'> <input type='submit' value='Schedule'></form>";

	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='servercheck'><input type='hidden' name='verbose' value='1'><input type='submit' value='Run Again and Display All Comments'></form>";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='servercheck'><input type='submit' value='Run Again'></form>";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "serverchecksave") {
	my $extra = "";
	unless ($FORM{email}) {$FORM{freq} = "never"; $extra = "(no email address supplied)";}
	sysopen (CRON, "/etc/cron.d/csfcron.sh", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (CRON, LOCK_EX);
	my @data = <CRON>;
	chomp @data;
	seek (CRON, 0, 0);
	truncate (CRON, 0);
	my $done = 0;
	foreach my $line (@data) {
		if ($line =~ /csf \-m/) {
			if ($FORM{freq} and ($FORM{freq} ne "never") and !$done) {
				print CRON "\@$FORM{freq} root /usr/sbin/csf -m $FORM{email}\n";
				$done = 1;
			}
		} else {
			print CRON "$line\n";
		}
	}
	if (!$done and ($FORM{freq} ne "never")) {
			print CRON "\@$FORM{freq} root /usr/sbin/csf -m $FORM{email}\n";
	}
	close (CRON);

	if ($FORM{freq} and $FORM{freq} ne "never") {
		print "<p>Report scheduled to be emailed to $FORM{email} $FORM{freq}\n";
	} else {
		print "<p>Report schedule cancelled $extra\n";
	}
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='servercheck'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "restartboth") {
	print "<p>Restarting csf...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -sf");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	if ($config{DIRECTADMIN} or $config{THIS_UI}) {
		print "<p>Signal lfd to <i>restart</i>...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		sysopen (OUT, "/etc/csf/lfd.restart",, O_WRONLY | O_CREAT) or die "Unable to open file: $!";
		close (OUT);
	} else {
		print "<p>Restarting lfd...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		&printcmd("/etc/init.d/lfd restart");
	}
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "remapf") {
	print "<p>Removing APF/BFD...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("sh /etc/csf/remove_apf_bfd.sh");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p><b>Note: You should check the root cron and /etc/crontab to ensure that there are no apf or bfd related cron jobs remaining</b></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "qallow") {
	print "<p>Allowing $FORM{ip}...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -a $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "qdeny") {
	print "<p>Blocking $FORM{ip}...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -d $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "qignore") {
	print "<p>Ignoring $FORM{ip}...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	open (OUT, ">>", "/etc/csf/csf.ignore");
	print OUT "$FORM{ip}\n";
	close (OUT);
	print "</p>\n<p>...<b>Done</b>.</p>\n";
	if ($config{DIRECTADMIN} or $config{THIS_UI}) {
		print "<p>Signal lfd to <i>restart</i>...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		sysopen (OUT, "/etc/csf/lfd.restart",, O_WRONLY | O_CREAT) or die "Unable to open file: $!";
		close (OUT);
	} else {
		print "<p>Restarting lfd...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		&printcmd("/etc/init.d/lfd restart");
	}
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "kill") {
	print "<p>Unblock $FORM{ip}, trying permanent blocks...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -dr $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p>Unblock $FORM{ip}, trying temporary blocks...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -tr $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "grep") {
	print "<p>Searching for $FORM{ip}...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	my ($childin, $childout);
	my $pid = open3($childin, $childout, $childout, "perl /etc/csf/csf.pl -g $FORM{ip}");
	my $unblock;
	while (<$childout>) {
		my $line = $_;
#csf.deny: 183.5.152.252 # lfd: (ftpd) Failed FTP login from 183.5.152.252 (CN/China/-): 3 in the last 300 secs - Wed Apr 18 21:31:29 201
#Temporary Blocks: IP:183.5.152.251 Port: Dir:in TTL:3600 (Manually added)

		if ($line =~ /^csf.deny:\s(\S+)\s*/) {$unblock = 1}
		if ($line =~ /^Temporary Blocks: IP:(\S+)\s*/) {$unblock = 1}
		print $_;
	}
	waitpid ($pid, 0);
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	if ($unblock) {print "<p>Unblock $FORM{ip}: <a href='$script?action=kill&ip=$FORM{ip}'><img src='$images/delete.png' border='0' alt='Unblock $ip?'></a></p>\n"}
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "callow") {
	print "<p>Cluster Allow $FORM{ip}...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -ca $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "cdeny") {
	print "<p>Cluster Deny $FORM{ip}...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -cd $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "crm") {
	print "<p>Cluster Remove $FORM{ip}...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -cr $FORM{ip}");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "cping") {
	print "<p>Cluster PING...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -cp");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "cconfig") {
	print "<p>Cluster configuration option...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -cc '$FORM{option} $FORM{value}'");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "crestart") {
	print "<p>Cluster restart csf and lfd...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl --crestart");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "allow") {
	sysopen (IN, "/etc/csf/csf.allow", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='saveallow'>\n";
	print "<fieldset><legend><b>Edit csf.allow</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "saveallow") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/csf.allow", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved. You should restart csf and lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='restartboth'><input type='submit' value='Restart csf+lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "redirect") {
	sysopen (IN, "/etc/csf/csf.redirect", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='saveredirect'>\n";
	print "<fieldset><legend><b>Edit csf.redirect</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "saveredirect") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/csf.redirect", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved. You should restart csf and lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='restartboth'><input type='submit' value='Restart csf+lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "reseller") {
	sysopen (IN, "/etc/csf/csf.resellers", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='savereseller'>\n";
	print "<fieldset><legend><b>Edit csf.resellers</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "savereseller") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/csf.resellers", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "dirwatch") {
	sysopen (IN, "/etc/csf/csf.dirwatch", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='savedirwatch'>\n";
	print "<fieldset><legend><b>Edit csf.dirwatch</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "savedirwatch") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/csf.dirwatch", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved. You should restart lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='lfdrestart'><input type='submit' value='Restart lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "dyndns") {
	sysopen (IN, "/etc/csf/csf.dyndns", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='savedyndns'>\n";
	print "<fieldset><legend><b>Edit csf.dyndns</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "savedyndns") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/csf.dyndns", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved. You should restart lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='lfdrestart'><input type='submit' value='Restart lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "logfiles") {
	sysopen (IN, "/etc/csf/csf.logfiles", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='savelogfiles'>\n";
	print "<fieldset><legend><b>Edit csf.logfiles</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "savelogfiles") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/csf.logfiles", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved. You should restart lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='lfdrestart'><input type='submit' value='Restart lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "deny") {
	sysopen (IN, "/etc/csf/csf.deny", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='savedeny'>\n";
	print "<fieldset><legend><b>Edit csf.deny</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "savedeny") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/csf.deny", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved. You should restart csf and lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='restartboth'><input type='submit' value='Restart csf+lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "templates") {
	sysopen (IN, "/etc/csf/$FORM{template}", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='savetemplates'>\n";
	print "<input type='hidden' name='template' value='$FORM{template}'>\n";
	print "<fieldset><legend><b>Edit $FORM{template}</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px' wrap='off'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "savetemplates") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/$FORM{template}", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "ignorefiles") {
	sysopen (IN, "/etc/csf/$FORM{ignorefile}", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;
	my $max = 80;
	foreach my $line (@confdata) {if (length($line) > $max) {$max = length($line) + 1}}

	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='saveignorefiles'>\n";
	print "<input type='hidden' name='ignorefile' value='$FORM{ignorefile}'>\n";
	print "<fieldset><legend><b>Edit $FORM{ignorefile}</b></legend>\n";
	print "<table style='border: 1px #990000 solid' align='center'>\n";
	print "<tr><td><textarea name='formdata' cols='$max' rows='40' style='font-family: Courier New, Courier; font-size: 12px' wrap='off'>\n";
	foreach my $line (@confdata) {
		$line =~ s/\</\&lt\;/g;
		$line =~ s/\>/\&gt\;/g;
		print $line."\n";
	}
	print "</textarea></td></tr></table></fieldset>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "saveignorefiles") {
	$FORM{formdata} =~ s/\r//g;
	sysopen (OUT, "/etc/csf/$FORM{ignorefile}", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	if ($FORM{formdata} !~ /\n$/) {$FORM{formdata} .= "\n"}
	print OUT $FORM{formdata};
	close (OUT);

	print "<p>Changes saved. You should restart lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='lfdrestart'><input type='submit' value='Restart lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "conf") {
	sysopen (IN, "/etc/csf/csf.conf", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;

	print "<fieldset><legend><b>Edit ConfigServer Firewall</b></legend>\n";
	open (IN, "<", "/etc/csf/csf.div");
	my @divdata = <IN>;
	close (IN);
	print @divdata;
	print "<div id='paginatediv2' class='paginationstyle' align='center'></div>\n";
	print "<form action='$script' method='post'>\n";
	print "<input type='hidden' name='action' value='saveconf'>\n";
	print "<table align='center' style='background: white; border: 1px #990000 solid; color:black; font-family: Courier New, Courier; font-size: 12px' width='95%'>\n<tr><td>\n";
	my $first = 1;
	my @divnames;
	foreach my $line (@confdata) {
		if (($line !~ /^\#/) and ($line =~ /=/)) {
			my ($start,$end) = split (/=/,$line);
			my $name = $start;
			$name =~ s/\s/\_/g;
			if ($end =~ /\"(.*)\"/) {$end = $1}
			my $size = length($end) + 4;
			my $bgcolor = "white";
			my ($status,$range,$default) = &sanity($start,$end);
			my $showrange = "";
			if ($default ne "") {
				$showrange = " Default: $default [$range]";
				if ($end ne $default) {$bgcolor = "#F4F4EA"}
			}
			if ($status) {$bgcolor = "red"; $showrange = " Recommended range: $range (Default: $default)"}
			print "<div style='background:$bgcolor;padding:2px'><b>$start</b> = <input type='text' name='$name' value='$end' size='$size'>$showrange</div>\n";
		} else {
			if ($line =~ /^\# SECTION:(.*)/) {
				push @divnames, $1;
				unless ($first) {print "</div>\n"}
				print "<div class='virtualpage hidepiece'>";
				print "$line<br />\n";
				$first = 0;
				next;
			}
			$line =~ s/</&lt;/g;
			$line =~ s/>/&gt;/g;
			$line =~ s/\n/<br \/>\n/g;
			print "$line<br />\n";
		}
	}
	print "</div></td></tr></table>\n";
	print "<div id='paginatediv' class='paginationstyle' align='center'>\n<a href='javascript:pagecontent.showall()'>Show All</a> <a href='#' rel='previous'>Prev</a> <select style='width: 250px'></select> <a href='#' rel='next'>Next</a>\n</div>\n";
	print "</fieldset>\n";
	print <<EOD;
<script type="text/javascript">

var pagecontent=new virtualpaginate({
 piececlass: "virtualpage", //class of container for each piece of content
 piececontainer: "div", //container element type (ie: "div", "p" etc)
 pieces_per_page: 1, //Pieces of content to show per page (1=1 piece, 2=2 pieces etc)
 defaultpage: 0, //Default page selected (0=1st page, 1=2nd page etc). Persistence if enabled overrides this setting.
 wraparound: false,
 persist: false //Remember last viewed page and recall it when user returns within a browser session?
})
EOD
	print "pagecontent.buildpagination(['paginatediv','paginatediv2'],[";
	foreach my $line (@divnames) {print "'$line',"}
	print "''])\npagecontent.showall();\n</script>\n";
	print "<p align='center'><input type='submit' value='Change'></p>\n";
	print "</form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "saveconf") {
	sysopen (IN, "/etc/csf/csf.conf", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;

	sysopen (OUT, "/etc/csf/csf.conf", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	for (my $x = 0; $x < @confdata;$x++) {
		if (($confdata[$x] !~ /^\#/) and ($confdata[$x] =~ /=/)) {
			my ($start,$end) = split (/=/,$confdata[$x]);
			my $name = $start;
			my $sanity_name = $start;
			$name =~ s/\s/\_/g;
			$sanity_name =~ s/\s//g;
			print OUT "$start= \"$FORM{$name}\"\n";
			my ($status,$range, $default) = &sanity($sanity_name,$FORM{$name});
			if ($status) {print "<br>WARNING: $sanity_name sanity check. $sanity_name = $FORM{$name}. Recommended range: $range (Default: $default)\n"}
		} else {
			print OUT "$confdata[$x]\n";
		}
	}
	close (OUT);

	print "<p>Changes saved. You should restart both csf and lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='restartboth'><input type='submit' value='Restart csf+lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "viewlogs") {
	if (-e "/etc/csf/stats/iptables_log") {
		sysopen (IN, "/etc/csf/stats/iptables_log", O_RDWR | O_CREAT) or die "Unable to open file: $!";
		flock (IN, LOCK_SH);
		my @iptables = <IN>;
		close (IN);
		chomp @iptables;
		@iptables = reverse @iptables;
		my $from;
		my $to;
		my $divcnt = 0;
		my $expcnt = @iptables;
		my $class = '#F4F4EA';

		if ($iptables[0] =~ /\|(\S+\s+\d+\s+\S+)/) {$from = $1}
		if ($iptables[-1] =~ /\|(\S+\s+\d+\s+\S+)/) {$to = $1}

		print "<p align='center'><big>Last $config{ST_IPTABLES} iptables logs*, latest:<b>$from</b> oldest:<b>$to</b></big></p>\n";

		print "<style type='text/css'>\n<!--\n.submenu {\n    display:none;\n}\n.mhead {\n    display: block;\n}\n-->\n</style>\n$csfjs\n";
		print "<br><table align='center' cellpadding='4' cellspacing='1' width='95%' align='center' bgcolor='#990000'>\n";
		print "<tr bgcolor='#F4F4EA'><td colspan='7'>";
		print " <a href='javascript:expandO(\"expand\",$expcnt);'><img valign='absmiddle' src='$images/plus.png' name='i$divcnt' border='0' width='12' height='12'>Expand All</a>\n";
		print " <a href='javascript:expandO(\"collapse\",$expcnt);'><img valign='absmiddle' src='$images/minus.png' name='i$divcnt' border='0' width='12' height='12'>Collapse All</a>\n";
		print "</td></tr>\n";
		print "<tr bgcolor='#FFFFFF'><td><b>Time</b></td><td width='50%'><b>From</b></td><td><b>Port</b></td><td><b>I/O</b></td><td width='50%'><b>To</b></td><td><b>Port</b></td><td><b>Proto</b></td></tr>\n";
		foreach my $line (@iptables) {
			$divcnt++;
			my ($text,$log) = split(/\|/,$line);
			my ($time,$desc,$in,$out,$src,$dst,$spt,$dpt,$proto,$inout);
			if ($log =~ /IN=(\S+)/) {$in = $1}
			if ($log =~ /OUT=(\S+)/) {$out = $1}
			if ($log =~ /SRC=(\S+)/) {$src = $1}
			if ($log =~ /DST=(\S+)/) {$dst = $1}
			if ($log =~ /SPT=(\d+)/) {$spt = $1}
			if ($log =~ /DPT=(\d+)/) {$dpt = $1}
			if ($log =~ /PROTO=(\S+)/) {$proto = $1}

			if ($text ne "") {
				$text =~ s/\(/\<br\>\(/g;
				if ($in and $src) {$src = $text ; $dst .= " <br>(server)"}
				elsif ($out and $dst) {$dst = $text ; $src .= " <br>(server)"}
			}
			if ($log =~ /^(\S+\s+\d+\s+\S+)/) {$time = $1}

			$inout = "n/a";
			if ($in) {$inout = "in"}
			elsif ($out) {$inout = "out"}

			print "<tr bgcolor='$class'><td nowrap><a href='javascript:showMenu($divcnt);'><img valign='absmiddle' src='$images/plus.png' name='i$divcnt' border='0' width='12' height='12'></a> $time</td><td>$src</td><td>$spt</td><td>$inout</td><td>$dst</td><td>$dpt</td><td>$proto</td></tr>\n";

			$log =~ s/\&/\&amp\;/g;
			$log =~ s/>/\&gt\;/g;
			$log =~ s/</\&lt\;/g;
			print "<tr bgcolor='$class'><td colspan='7'><span class='submenu' id='s$divcnt'>$log</span></td></tr>\n";
			if ($class eq '#FFFFFF') {$class = '#F4F4EA'} else {$class = '#FFFFFF'}
		}
		print "</table>\n";
		print "<p>* These iptables logs taken from $config{IPTABLES_LOG} will not necessarily show all packets blocked by iptables. For example, ports listed in DROP_NOLOG or the settings for DROP_LOGGING/DROP_IP_LOGGING/DROP_ONLYRES/DROP_PF_LOGGING will affect what is logged. Additionally, there is rate limiting on all iptables log rules to prevent log file flooding</p>\n";
	} else {
		print "<p> No logs entries found<p>\n";
	}

	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "sips") {
	sysopen (IN, "/etc/csf/csf.sips", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;

	print "<form action='addon_csf.cgi' method='post'><input type='hidden' name='action' value='sipsave'><br>\n";
	print "<table align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='FFFFFF' style='border:1px solid #990000'\n";
	print "<tr bgcolor='#FFFFFF'><td><b>IP Address</b></td><td><b>Deny All Access to IP</b></td></tr>\n";
	my $class = '#F4F4EA';

	my %sips;
	open(IN,"<","/etc/csf/csf.sips");
	my @data = <IN>;
	close(IN);
	chomp @data;
	foreach my $line (@data) {
		if ($line =~ /^\d+\.\d+\.\d+\.\d+$/) {$sips{$line} = 1}
	}

	my ($childin, $childout);
	my $pid = open3($childin, $childout, $childout, $config{IFCONFIG});
	my @ifconfig = <$childout>;
	waitpid ($pid, 0);
	chomp @ifconfig;

	foreach my $line (@ifconfig) {
		if ($line =~ /inet \w*:(\d+\.\d+\.\d+\.\d+)/) {
			my $ip = $1;
			if ($ip =~ /^127\.0\.0/) {next}
			my $chk = "ip_$ip";
			$chk =~ s/\./\_/g;
			my $checked = "";
			if ($sips{$ip}) {$checked = "checked"}
			print "<tr bgcolor='$class'><td>$ip</td><td align='center'><input type='checkbox' name='$chk' $checked></td></tr>\n";
			if ($class eq '#FFFFFF') {$class = '#F4F4EA'} else {$class = '#FFFFFF'}
		}
	}

	print "<tr bgcolor='$class'><td colspan='3' align='center'><input type='submit' value='Change'></td></tr>\n";
	print "</table></form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "sipsave") {
	open(IN,"<","/etc/csf/csf.sips");
	my @data = <IN>;
	close(IN);
	chomp @data;

	open(OUT,">","/etc/csf/csf.sips");
	foreach my $line (@data) {
		if ($line =~ /^\#/) {print OUT "$line\n"} else {last}
	}
	foreach my $key (keys %FORM) {
		if ($key =~ /^ip_(.*)/) {
			my $ip = $1;
			$ip =~ s/\_/\./g;
			print OUT "$ip\n";
		}
	}
	close(OUT);

	print "<p>Changes saved. You should restart csf.</p>\n";
	print "<p align='center'><form action='addon_csf.cgi' method='post'><input type='hidden' name='action' value='restart'><input type='submit' value='Restart csf'></form></p>\n";
	print "<p align='center'><form action='addon_csf.cgi' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "quick") {
	print "<form action='$script' method='post'><input type='hidden' name='action' value='quicksave'><br>\n";

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr bgcolor='#F4F4EA'><th align='left'>Firewall Security Level</th></tr><tr><td align='left'><table width='100%' cellpadding='4' cellspacing='0' align='center' bgcolor='FFFFFF' style='border:1px solid #990000'\n";

	print "<tr bgcolor='#FFFFFF'><td><b>Setting</b> (see the Firewall Configuration for more information)</td><td align='center'><b>Current</b></td><td align='center'><b>Low</b></td><td align='center'><b>Medium</b></td><td align='center'><b>High</b></td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Block outgoing SMTP connections except for root, exim and mailman</td><td align='center'><b>$config{SMTP_BLOCK}</b></td><td align='center'>0</td><td align='center'>1</td><td align='center'>1</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Allow outgoing SMTP connections from localhost (127.0.0.1)</td><td align='center'><b>$config{SMTP_ALLOWLOCAL}</b></td><td align='center'>1</td><td align='center'>1</td><td align='center'>0</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Enable IP range blocking using the DShield Block List</td><td align='center'><b>$config{LF_DSHIELD}</b></td><td align='center'>0</td><td align='center'>86400</td><td align='center'>86400</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Enable IP range blocking using the Spamhaus DROP List</td><td align='center'><b>$config{LF_SPAMHAUS}</b></td><td align='center'>0</td><td align='center'>86400</td><td align='center'>86400</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Enable Connection Tracking</td><td align='center'><b>$config{CT_LIMIT}</b></td><td align='center'>0</td><td align='center'>400</td><td align='center'>300</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Permanently block Connection Tracking triggered IPs</td><td align='center'><b>$config{CT_PERMANENT}</b></td><td align='center'>0</td><td align='center'>0</td><td align='center'>1</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Enable Directory Watching</td><td align='center'><b>$config{LF_DIRWATCH}</b></td><td align='center'>300</td><td align='center'>120</td><td align='center'>60</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Remove suspicious files</td><td align='center'><b>$config{LF_DIRWATCH_DISABLE}</b></td><td align='center'>0</td><td align='center'>1</td><td align='center'>1</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Enable Process Tracking</td><td align='center'><b>$config{PT_LIMIT}</b></td><td align='center'>60</td><td align='center'>60</td><td align='center'>30</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Enable User Process Tracking</td><td align='center'><b>$config{PT_USERPROC}</b></td><td align='center'>0</td><td align='center'>15</td><td align='center'>8</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Enable User Process Tracking for all system accounts</td><td align='center'><b>$config{PT_ALL_USERS}</b></td><td align='center'>0</td><td align='center'>1</td><td align='center'>1</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Skip Apache Process Tracking</td><td align='center'><b>$config{PT_SKIP_HTTP}</b></td><td align='center'>1</td><td align='center'>1</td><td align='center'>0</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Ignore IPs in /etc/relayhosts (cPanel only)</td><td align='center'><b>$config{RELAYHOSTS}</b></td><td align='center'>1</td><td align='center'>0</td><td align='center'>0</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Port Scan protection</td><td align='center'><b>$config{PS_LIMIT}</b></td><td align='center'>20</td><td align='center'>10</td><td align='center'>5</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>Temporary to Permanent IP blocking</td><td align='center'><b>$config{LF_PERMBLOCK}</b></td><td align='center'>0</td><td align='center'>0</td><td align='center'>1</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td>Permanently block IPs by network class</td><td align='center'><b>$config{LF_NETBLOCK}</b></td><td align='center'>0</td><td align='center'>0</td><td align='center'>1</td></tr>\n";
	print "<tr bgcolor='#F4F4EA'><td>System Integrity Checking (md5sum checks)</td><td align='center'><b>$config{LF_INTEGRITY}</b></td><td align='center'>0</td><td align='center'>3600</td><td align='center'>3600</td></tr>\n";
	print "<tr bgcolor='#FFFFFF'><td colspan='2'><b>Select quick firewall protection level</b></td><td align='center'><input name='quickselect' type='submit' value='Low'></td><td align='center'><input name='quickselect' type='submit' value='Medium'></td><td align='center'><input name='quickselect' type='submit' value='High'></td></tr>\n";
	print "</table></td></tr></table></form>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "quicksave") {
	my %newconf;
	if ($FORM{quickselect} eq "Low") {
		$newconf{SMTP_BLOCK} = "0";
		$newconf{SMTP_ALLOWLOCAL} = "1";
		$newconf{LF_DSHIELD} = "0";
		$newconf{LF_SPAMHAUS} = "0";
		$newconf{CT_LIMIT} = "0";
		$newconf{CT_PERMANENT} = "0";
		$newconf{PT_SKIP_HTTP} = "1";
		$newconf{PT_LIMIT} = "60";
		$newconf{PT_USERPROC} = "0";
		$newconf{PT_ALL_USERS} = "0";
		$newconf{LF_DIRWATCH_DISABLE} = "0";
		$newconf{LF_DIRWATCH} = "300";
		$newconf{RELAYHOSTS} = "1";
		$newconf{SYNFLOOD} = "0";
		$newconf{PS_INTERVAL} = "0";
		$newconf{PS_LIMIT} = "10";
		$newconf{LF_PERMBLOCK} = "0";
		$newconf{LF_NETBLOCK} = "0";
		$newconf{LF_INTEGRITY} = "0";
	}
	if ($FORM{quickselect} eq "Medium") {
		$newconf{SMTP_BLOCK} = "1";
		$newconf{SMTP_ALLOWLOCAL} = "1";
		$newconf{LF_DSHIELD} = "86400";
		$newconf{LF_SPAMHAUS} = "86400";
		$newconf{CT_LIMIT} = "400";
		$newconf{CT_PERMANENT} = "0";
		$newconf{PT_SKIP_HTTP} = "1";
		$newconf{PT_LIMIT} = "60";
		$newconf{PT_USERPROC} = "15";
		$newconf{PT_ALL_USERS} = "1";
		$newconf{LF_DIRWATCH_DISABLE} = "1";
		$newconf{LF_DIRWATCH} = "120";
		$newconf{RELAYHOSTS} = "0";
		$newconf{SYNFLOOD} = "0";
		$newconf{PS_INTERVAL} = "300";
		$newconf{PS_LIMIT} = "10";
		$newconf{DROP_LOGGING} = "1";
		$newconf{LF_PERMBLOCK} = "0";
		$newconf{LF_NETBLOCK} = "0";
		$newconf{LF_INTEGRITY} = "3600";
	}
	if ($FORM{quickselect} eq "High") {
		$newconf{SMTP_BLOCK} = "1";
		$newconf{SMTP_ALLOWLOCAL} = "0";
		$newconf{LF_DSHIELD} = "86400";
		$newconf{LF_SPAMHAUS} = "86400";
		$newconf{CT_LIMIT} = "300";
		$newconf{CT_PERMANENT} = "1";
		$newconf{PT_SKIP_HTTP} = "0";
		$newconf{PT_LIMIT} = "30";
		$newconf{PT_USERPROC} = "8";
		$newconf{PT_ALL_USERS} = "1";
		$newconf{LF_DIRWATCH_DISABLE} = "1";
		$newconf{LF_DIRWATCH} = "60";
		$newconf{RELAYHOSTS} = "0";
		$newconf{SYNFLOOD} = "1";
		$newconf{PS_INTERVAL} = "300";
		$newconf{PS_LIMIT} = "5";
		$newconf{DROP_LOGGING} = "1";
		$newconf{LF_PERMBLOCK} = "1";
		$newconf{LF_NETBLOCK} = "1";
		$newconf{LF_INTEGRITY} = "3600";
	}
	
	sysopen (IN, "/etc/csf/csf.conf", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @confdata = <IN>;
	close (IN);
	chomp @confdata;

	sysopen (OUT, "/etc/csf/csf.conf", O_WRONLY | O_CREAT) or die "Unable to open file: $!";
	flock (OUT, LOCK_EX);
	seek (OUT, 0, 0);
	truncate (OUT, 0);
	for (my $x = 0; $x < @confdata;$x++) {
		if (($confdata[$x] !~ /^\#/) and ($confdata[$x] =~ /=/)) {
			my ($start,$end) = split (/\s=\s/,$confdata[$x]);
			my $name = $start;
			if (defined $newconf{$name}) {
				print OUT "$name = \"$newconf{$name}\"\n";
			} else {
				print OUT "$confdata[$x]\n";
			}
		} else {
			print OUT "$confdata[$x]\n";
		}
	}
	close (OUT);

	print "<p>$FORM{quickselect} security level settings saved. You should restart both csf and lfd.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='restartboth'><input type='submit' value='Restart csf+lfd'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "upgrade") {
	if ($config{DIRECTADMIN}) {
		print "<p>Due to restrictions in DirectAdmin you must login to the root shell to upgrade csf using:\n<p><b>csf -u</b>\n";
	}
	elsif ($config{THIS_UI}) {
		print "<p>You cannot upgrade through the UI as restarting lfd will interrupt this session. You must login to the root shell to upgrade csf using:\n<p><b>csf -u</b>\n";
	} else {
		print "<p>Upgrading csf...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
		&printcmd("perl /etc/csf/csf.pl -u");
		print "</pre></p>\n<p>...<b>Done</b>.</p>\n";

		open (IN, "</etc/csf/version.txt") or die $!;
		$myv = <IN>;
		close (IN);
		chomp $myv;
	}

	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "denyf") {
	print "<p>Removing all entries from csf.deny...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csf.pl -df");
	&printcmd("perl /etc/csf/csf.pl -tf");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";

	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{action} eq "csftest") {
	print "<p>Testing iptables...</p>\n<p><pre style='font-family: Courier New, Courier; font-size: 12px'>\n";
	&printcmd("perl /etc/csf/csftest.pl");
	print "</pre></p>\n<p>...<b>Done</b>.</p>\n";
	print "<p>You should restart csf after having run this test.</p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='hidden' name='action' value='restart'><input type='submit' value='Restart csf'></form></p>\n";
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
elsif ($FORM{mobi}) {
	print "<table align='center' border='0' width='95%' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='hidden' name='action' value='qallow'><input type='submit' value='Quick Allow'></td><td width='100%'><input name='ip' value='' size='18' style='background-color: lightgreen'></td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='hidden' name='action' value='qdeny'><input type='submit' value='Quick Deny'></td><td width='100%'><input name='ip' value='' size='18' style='background-color: pink'></td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='hidden' name='action' value='qignore'><input type='submit' value='Quick Ignore'></td><td width='100%'><input name='ip' value='' size='18' style='background-color: lightblue'></td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='mobi' value='$FORM{mobi}'><input type='hidden' name='action' value='kill'><input type='submit' value='Quick Unblock'></td><td width='100%'><input name='ip' value='' size='18'></td></form></tr>\n";
	print "</table>\n";
}
else {
	&getethdev;
	my ($childin, $childout);
	my $pid = open3($childin, $childout, $childout, "$config{IPTABLES} -L LOCALINPUT -n");
	my @iptstatus = <$childout>;
	waitpid ($pid, 0);
	chomp @iptstatus;
	$status = "Enabled and Running";

	if (-e "/etc/csf/csf.disable") {
		$status = "<b><font color='red'>Disabled and Stopped</font></b> <input type='hidden' name='action' value='enable'><input type='submit' value='Enable'>"
	}
	elsif ($config{TESTING}) {
		$status = "<b><font color='red'>Enabled but in Test Mode</font></b> - Don't forget to disable TESTING in the Firewall Configuration";
	}
	elsif ($iptstatus[0] !~ /^Chain LOCALINPUT/) {
		$status = "<b><font color='red'>Enabled but Stopped</font></b> <input type='hidden' name='action' value='start'><input type='submit' value='Start'>"
	}
	if (-e "/etc/csf/lfd.restart") {$status .= " (lfd restart request pending)"}

	my $tempcnt = 0;
	if (! -z "/etc/csf/csf.tempban") {
		sysopen (IN, "/etc/csf/csf.tempban", O_RDWR);
		flock (IN, LOCK_EX);
		my @data = <IN>;
		close (IN);
		$tempcnt = scalar @data;
	}
	my $tempbans = "(Currently: $tempcnt temp IP bans, ";
	$tempcnt = 0;
	if (! -z "/etc/csf/csf.tempallow") {
		sysopen (IN, "/etc/csf/csf.tempallow", O_RDWR);
		flock (IN, LOCK_EX);
		my @data = <IN>;
		close (IN);
		$tempcnt = scalar @data;
	}
	$tempbans .= "$tempcnt temp IP allows)";

	my $permcnt = 0;
	if (! -z "/etc/csf/csf.deny") {
		sysopen (IN, "/etc/csf/csf.deny", O_RDWR);
		flock (IN, LOCK_SH);
		while (my $line = <IN>) {
			if ($line =~ /^(\#|\n|\r)/) {next}
			$permcnt++;
		}
		close (IN);
	}
	my $permbans = "(Currently: $permcnt permanent IP bans)";

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr><form action='$script' method='post'><th align='center' colspan='2'>Firewall Status: $status</th></form></tr></table><br>\n";

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr><th align='left' colspan='2'>Server Security Information</th></tr>";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='servercheck'><input type='submit' value='Check Server Security'></td><td width='100%'>Perform a basic security, stability and settings check on the server</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='readme'><input type='submit' value='Firewall Information'></td><td width='100%'>View the csf+lfd readme.txt file</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='status'><input type='submit' value='View iptables Rules'></td><td width='100%'>Display the active iptables rules</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='tail'><input type='submit' value='View lfd Log'></td><td width='100%'>View the last <input type='text' name='lines' value='30' size='5'> lines of the Login Failure Daemon (lfd) log file and <input type='checkbox' name='refresh' value='1'> auto-refresh the log view</td></form></tr>\n";
	if ($config{ST_ENABLE}) {
		print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='viewlogs'><input type='submit' value='View iptables Log'></td><td width='100%'>View the last $config{ST_IPTABLES} iptables log lines</td></form></tr>\n";
		if ($chart) {
			print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='chart'><input type='submit' value='View lfd Statistics'></td><td width='100%'>View lfd blocking statistics</td></form></tr>\n";
			if ($config{ST_SYSTEM}) {
				print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='systemstats'><input type='submit' value='View System Statistics'></td><td width='100%'>View basic system statistics</td></form></tr>\n";
			}
		}
	}
	print "</table><br>\n";

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr bgcolor='#FFFFFF'><th align='left' colspan='2'>Upgrade</th></tr>";
	my $retry = 0;
	my $retrytime = 300;
	if (-e "/etc/csf/nocheck") {
		open (IN, "<", "/etc/csf/nocheck");
		flock (IN, LOCK_SH);
		my $time = <IN>;
		close (IN);
		chomp $time;
		$retry = time - $time;
		if ($retry > $retrytime) {unlink ("/etc/csf/nocheck")}
	}
	unless (-e "/etc/csf/nocheck") {
		my ($status, $text) = &urlget("http://www.configserver.com/free/csf/version.txt");
		my $actv = $text;
		my $up = 0;

		if ($actv ne "") {
			if ($actv =~ /^[\d\.]*$/) {
				if ($actv > $myv) {
					print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='upgrade'><input type='submit' value='Upgrade csf'></td><td width='100%'><b>A new version of csf (v$actv) is available. Upgrading will retain your settings<br><a href='http://www.configserver.com/free/csf/changelog.txt' target='_blank'>View ChangeLog</a></b></td></form></tr>\n";
				} else {
					print "<tr bgcolor='#F4F4EA'><td colspan='2'>You are running the latest version of csf. An Upgrade button will appear here if a new version becomes available</td></tr>\n";
				}
				$up = 1;
			}
		}
		unless ($up) {
			sysopen (OUT, "/etc/csf/nocheck", O_WRONLY | O_CREAT);
			flock (OUT, LOCK_EX);
			print OUT time;
			close (OUT);
			print "<tr bgcolor='#F4F4EA'><td colspan='2'>Unable to connect to http://www.configserver.com, retry in $retrytime seconds. An Upgrade button will appear here if new version is detected</td></tr>\n";
		}
	} else {
			print "<tr bgcolor='#F4F4EA'><td colspan='2'>Unable to connect to http://www.configserver.com, retry in ".($retrytime - $retry)." seconds. An Upgrade button will appear here if new version is detected</td></tr>\n";
	}
	if (-e "/etc/apf" or -e "/usr/local/bfd") {
		print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='remapf'><input type='submit' value='Remove APF/BFD'></td><td width='100%'>Remove APF/BFD from the server. You must not run both APF or BFD with csf on the same server</td></form></tr>\n";
	}
	print "</table><br>\n";

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr><th align='left' colspan='2'>csf - ConfigServer Firewall</th></tr>";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='quick'><input type='submit' value='Firewall Security Level'></td><td width='100%'>Pre-configured settings for Low, Medium or High firewall security</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='conf'><input type='submit' value='Firewall Configuration'></td><td width='100%'>Edit the configuration file for the csf firewall and lfd</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='qallow'><input type='submit' value='Quick Allow'></td><td width='100%'>Allow IP address <a href='javascript:fillfield(\"allowip\",\"$ENV{REMOTE_ADDR}\")'><img src='$images/ip.png' border='0' alt='$ENV{REMOTE_ADDR}'></a> <input name='ip' id='allowip' value='' size='18' style='background-color: lightgreen'> through the firewall and add to the allow file (csf.allow)</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='qdeny'><input type='submit' value='Quick Deny'></td><td width='100%'>Block IP address <input name='ip' value='' size='18' style='background-color: pink'> in the firewall and add to the deny file (csf.deny)</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='qignore'><input type='submit' value='Quick Ignore'></td><td width='100%'>Ignore IP address <a href='javascript:fillfield(\"ignoreip\",\"$ENV{REMOTE_ADDR}\")'><img src='$images/ip.png' border='0' alt='$ENV{REMOTE_ADDR}'></a> <input name='ip' id='ignoreip' value='' size='18' style='background-color: lightblue'> in lfd, add to the ignore file (csf.ignore) and restart lfd</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='allow'><input type='submit' value='Firewall Allow IPs'></td><td width='100%'>Edit csf.allow, the IP address allow file</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='deny'><input type='submit' value='Firewall Deny IPs'></td><td width='100%'>Edit csf.deny, the IP address deny file $permbans</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='enable'><input type='submit' value='Firewall Enable'></td><td width='100%'>Enables csf and lfd if previously Disabled</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='disable'><input type='submit' value='Firewall Disable'></td><td width='100%'>Completely disables csf and lfd</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='restart'><input type='submit' value='Firewall Restart'></td><td width='100%'>Restart the csf iptables firewall</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='restartq'><input type='submit' value='Firewall Quick Restart'></td><td width='100%'>Have lfd restart the csf iptables firewall</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='kill'><input type='submit' value='Quick Unblock'></td><td width='100%'>Remove IP address <input name='ip' value='' size='18'> from the firewall (temp and perm blocks)</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='tempdeny'><input type='submit' value='Temporary Allow/Deny'></td><td width='100%'>Temporarily <select name='do'><option>block</option><option>allow</option></select> IP address <input name='ip' value='' size='18'> for <input name='timeout' value='' size='4'> <select name='dur'><option>seconds</option><option>minutes</option><option>hours</option><option>days</option></select></td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='temp'><input type='submit' value='Temporary IP Entries'></td><td width='100%'>View/Remove the <i>temporary</i> IP entries $tempbans</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='grep'><input type='submit' value='Search for IP'></td><td width='100%'>Search iptables for IP address <input name='ip' value='' size='18'></td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='sips'><input type='submit' value='Deny Server IPs'></td><td width='100%'>Deny access to and from specific IP addresses configured on the server (csf.sips)</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='denyf'><input type='submit' value='Flush all Blocks'></td><td width='100%'>Removes and unblocks all entries in csf.deny (excluding those marked \"do not delete\") and all temporary IP entries (blocks <i>and</i> allows)</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='redirect'><input type='submit' value='Firewall Redirect'></td><td width='100%'>Redirect connections to this server to other ports/IP addresses</td></form></tr>\n";
	print "</table><br>\n";
	print "<script>function fillfield (myitem,myip) {document.getElementById(myitem).value = myip;}</script>\n";

	if ($config{CLUSTER_SENDTO}) {
		print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
		print "<tr><th align='left' colspan='2'>csf - ConfigServer lfd Cluster</th></tr>";
		print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='callow'><input type='submit' value='Cluster Allow'></td><td width='100%'>Allow IP address <input name='ip' value='' size='18' style='background-color: lightgreen'> through the Cluster and add to the allow file (csf.allow)</td></form></tr>\n";
		print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='cdeny'><input type='submit' value='Cluster Deny'></td><td width='100%'>Block IP address <input name='ip' value='' size='18' style='background-color: pink'> in the Cluster and add to the deny file (csf.deny)</td></form></tr>\n";
		print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='crm'><input type='submit' value='Cluster Remove'></td><td width='100%'>Remove IP address <input name='ip' value='' size='18' style=''> in the Cluster and remove from the deny file (csf.deny)</td></form></tr>\n";
		print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='cping'><input type='submit' value='Cluster PING'></td><td width='100%'>Ping each member of the cluster (logged in lfd.log)</td></form></tr>\n";
		if ($config{CLUSTER_CONFIG}) {
			if ($ips{$config{CLUSTER_MASTER}} or $ipscidr6->find($config{CLUSTER_MASTER}) or ($config{CLUSTER_MASTER} eq $config{CLUSTER_NAT})) {
				my $options;
				foreach my $key (sort keys %config) {$options .= "<option>$key</option>"}
				print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='cconfig'><input type='submit' value='Cluster Config'></td><td width='100%'>Change configuration option <select name='option'>$options</select> to <input name='value' value='' size='18'> in the Cluster</td></form></tr>\n";
				print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='crestart'><input type='submit' value='Cluster Restart'></td><td width='100%'>Restart csf and lfd on Cluster members</td></form></tr>\n";
			}
		}
		print "</table><br>\n";
	}

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr><th align='left' colspan='2'>lfd - Login Failure Daemon</th></tr>";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='lfdstatus'><input type='submit' value='lfd Status'></td><td width='100%'>Display lfd status</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='lfdrestart'><input type='submit' value='lfd Restart'></td><td width='100%'>Restart lfd</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td nowrap><input type='hidden' name='action' value='ignorefiles'><select name='ignorefile'>\n";
	print "<option value='csf.ignore'>csf.ignore - IP Blocking</option>\n";
	print "<option value='csf.pignore'>csf.pignore, Process Tracking</option>\n";
	print "<option value='csf.fignore'>csf.fignore, Directory Watching</option>\n";
	print "<option value='csf.signore'>csf.signore, Script Alert</option>\n";
	print "<option value='csf.rignore'>csf.rignore, Reverse DNS lookup</option>\n";
	print "<option value='csf.suignore'>csf.suignore, Superuser check</option>\n";
	print "<option value='csf.mignore'>csf.mignore, RT_LOCALRELAY</option>\n";
	print "<option value='csf.logignore'>csf.logignore, Log Scanner</option>\n";
	print "</select> <input type='submit' value='Edit'></td><td width='100%'>Edit lfd ignore file</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='dirwatch'><input type='submit' value='lfd Directory File Watching'></td><td width='100%'>Edit the Directory File Watching file (csf.dirwatch) - all listed files and directories will be watched for changes by lfd</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='dyndns'><input type='submit' value='lfd Dynamic DNS'></td><td width='100%'>Edit the Dynamic DNS file (csf.dyndns) - all listed domains will be resolved and allowed through the firewall</td></form></tr>\n";
	print "<tr bgcolor='#FFFFFF'><form action='$script' method='post'><td><input type='hidden' name='action' value='templates'><select name='template'>\n";
	foreach my $tmp ("alert.txt","tracking.txt","connectiontracking.txt","processtracking.txt","accounttracking.txt","usertracking.txt","sshalert.txt","sualert.txt","uialert.txt","cpanelalert.txt","scriptalert.txt","filealert.txt","watchalert.txt","loadalert.txt","resalert.txt","integrityalert.txt","exploitalert.txt","relayalert.txt","portscan.txt","permblock.txt","netblock.txt","queuealert.txt","logfloodalert.txt","logalert.txt") {print "<option>$tmp</option>\n"}
	print "</select> <input type='submit' value='Edit'></td><td width='100%'>Edit email alert templates. See Firewall Information for details of each file</td></form></tr>\n";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='logfiles'><input type='submit' value='lfd Log Scanner Files'></td><td width='100%'>Edit the Log Scanner file (csf.logfiles) - Scan listed log files for log lines and periodically send a report</td></form></tr>\n";
	print "</table><br>\n";

	if (-e "/usr/local/cpanel/version") {
		print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
		print "<tr bgcolor='#FFFFFF'><th align='left' colspan='2'>cPanel Resellers</th></tr>";
		print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='reseller'><input type='submit' value='Edit Reseller Privs'></td><td width='100%'>Privileges can be assigned to cPanel Reseller accounts by editing this file (csf.resellers)</td></form></tr>\n";
		print "</table><br>\n";
	}

	print "<table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>\n";
	print "<tr bgcolor='#FFFFFF'><th align='left' colspan='2'>Extra</th></tr>";
	print "<tr bgcolor='#F4F4EA'><form action='$script' method='post'><td><input type='hidden' name='action' value='csftest'><input type='submit' value='Test iptables'></td><td width='100%'>Check that iptables has the required modules to run csf</td></form></tr>\n";
	print "</table>\n";

	print <<EOF;
				<br /><table align='center' width='95%' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF' style='border:1px solid #990000'>
                <tr bgcolor='#FFFFFF'><td colspan='2'>While we are happy to provide these scripts <strong>for free</strong>,
                    we are a very small company. If you do decide to use them,
                    we'd be eternally grateful for any donation so that we can continue to develop and provide them
				</td></tr>
                  <tr bgcolor='#F4F4EA'>
                    <td width="50%" nowrap class="topunderright"><form target='_blank' action="https://www.paypal.com/cgi-bin/webscr" method="post" onsubmit="return validate_form(this)">
                        <div align="center">
                          <script>
                          function validate_form(check) {
                              check.amount.value = check.amount.value.replace(/^\\\$/g,'');
                              if(check.amount.value < 5) {
                                  alert("Please enter a \$5 minimum amount to cover administration costs");
                                  return false;
                              } else {
                                  return true;
                              }
                          }
                          </script>
                        <div align="center">
                          <input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" name="submit2" alt="Make payments with PayPal - it's fast, free and secure!">
                          <img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">                            </div>
                          <input type="hidden" name="cmd" value="_xclick">
                          <input type="hidden" name="business" value="sales\@waytotheweb.com">
                          <input type="hidden" name="item_name" value="ConfigServer Scripts Donation">
                          <input type="hidden" name="no_shipping" value="1">
                          <input type="hidden" name="no_note" value="1">
                          <input type="hidden" name="currency_code" value="USD">
                          <input type="hidden" name="tax" value="0">
                          <input type="hidden" name="lc" value="GB">
                          <input type="hidden" name="bn" value="PP-DonationsBF">
                          Amount in \$USD:<br /><input type="input" name="amount" size="3" value="\$5">
                    </form></td>
                    <td width="50%" nowrap class="topunderright"><form target='_blank' action="https://www.paypal.com/cgi-bin/webscr" method="post">
                        <div align="center">
                        <input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-butcc-subscribe.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
                        <img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1"> <br>
                        <select name="a3">
                          <option value="3.00" selected>\$3.00/month</option>
                          <option value="5.00">\$5.00/month</option>
                          <option value="10.00">\$10.00/month</option>
                          <option value="15.00">\$15.00/month</option>
                          <option value="20.00">\$20.00/month</option>
                          <option value="25.00">\$25.00/month</option>
                        </select>
                        <br>
                        (You are free to cancel at any time)
                        <input type="hidden" name="cmd" value="_xclick-subscriptions">
                        <input type="hidden" name="business" value="sales\@waytotheweb.com">
                        <input type="hidden" name="item_name" value="ConfigServer Scripts Donation Subscription">
                        <input type="hidden" name="no_shipping" value="1">
                        <input type="hidden" name="no_note" value="1">
                        <input type="hidden" name="currency_code" value="USD">
                        <input type="hidden" name="lc" value="US">
                        <input type="hidden" name="bn" value="PP-SubscriptionsBF">
                        <input type="hidden" name="p3" value="1">
                        <input type="hidden" name="t3" value="M">
                        <input type="hidden" name="src" value="1">
                        <input type="hidden" name="sra" value="1">
                        </div>
                    </form></td>
                  </tr>
                </table>
EOF
}

print "<pre style='font-family: Courier New, Courier; font-size: 12px'>csf: v$myv</pre>";
print "<p>&copy;2006-2012, <a href='http://www.configserver.com' target='_blank'>ConfigServer Services</a> (Way to the Web Limited)</p>\n";
# end main
###############################################################################
# start printcmd
sub printcmd {
	my $cmd = shift;
	my ($childin, $childout);
	my $pid = open3($childin, $childout, $childout, $cmd);
	while (<$childout>) {print $_}
	waitpid ($pid, 0);
}
# end printcmd
###############################################################################
# loadconfig
sub loadconfig {
	sysopen (IN, "/etc/csf/csf.conf", O_RDWR | O_CREAT) or die "Unable to open file: $!";
	flock (IN, LOCK_SH);
	my @config = <IN>;
	close (IN);
	chomp @config;

	foreach my $line (@config) {
		if ($line =~ /^\#/) {next}
		if ($line !~ /=/) {next}
		my ($name,$value) = split (/=/,$line);
		$name =~ s/\s//g;
		if ($value =~ /\"(.*)\"/) {
			$value = $1;
		} else {
			&error(__LINE__,"Invalid configuration line");
		}
		$config{$name} = $value;
	}
}
# end loadconfig
###############################################################################
# start sanity
sub sanity {
	my $sanity_item = shift;
	my $sanity_value = shift;

	$sanity_item =~ s/\s//g;
	$sanity_value =~ s/\s//g;
	unless (defined $sanity{TESTING}) {
		open (IN, "<", "/etc/csf/sanity.txt");
		flock (IN, LOCK_SH);
		my @data = <IN>;
		close (IN);
		chomp @data;
		foreach my $line (@data) {
			my ($name,$value, $def) = split(/\=/,$line);
			$sanity{$name} = $value;
			$sanitydefault{$name} = $def;
		}
	}

	my $insane = 0;
	if (defined $sanity{$sanity_item}) {
		$insane = 1;
		foreach my $check (split(/\|/,$sanity{$sanity_item})) {
			if ($check =~ /-/) {
				my ($from,$to) = split(/\-/,$check);
				if (($sanity_value >= $from) and ($sanity_value <= $to)) {$insane = 0}

			} else {
				if ($sanity_value eq $check) {$insane = 0}
			}
		}
		$sanity{$sanity_item} =~ s/\|/ or /g;
	}
	return ($insane,$sanity{$sanity_item},$sanitydefault{$sanity_item});
}
# end sanity
###############################################################################
# start getethdev
sub getethdev {
	my ($childin, $childout);
	my $cmdpid = open3($childin, $childout, $childout, $config{IFCONFIG});
	my @ifconfig = <$childout>;
	waitpid ($cmdpid, 0);
	chomp @ifconfig;
	foreach my $line (@ifconfig) {
		if ($line =~ /inet \w*:\s*(\S+)/) {
			my $ip = $1;
			if (&checkip($ip)) {$ips{$ip} = 1}
		}
		if ($config{IPV6} and $line =~ /inet6 \w*:\s*(\S+)/) {
			my $ip = $1;
			if (&checkip($ip)) {eval {$ipscidr6->add($ip)}}
		}
	}
}
# end getethdev
###############################################################################
# start checkip
sub checkip {
	my $line = shift;
	my $ret = 0;
	my ($ip,$cidr) = split(/\//,$line);
	if ($cidr ne "") {
		unless ($cidr =~ /^\d+$/) {return 0}
	}
	if ($ip =~ /^$ipv4reg$/) {
		$ret = 4;
		if ($cidr) {
			unless ($cidr >= 1 && $cidr <= 32) {return 0}
		}
		if ($ip eq "127.0.0.1") {return 0}
	}
	if ($config{IPV6} and $ip =~ /^$ipv6reg$/) {
		$ret = 6;
		if ($cidr) {
			unless ($cidr >= 1 && $cidr <= 128) {return 0}
		}
		$ip =~ s/://g;
		$ip =~ s/^0*//g;
		if ($ip == 1) {return 0}
	}
	return $ret;
}
# end checkip
###############################################################################
# start chart
sub chart {
	my $img;
	my $imgdir = "";
	my $imghddir = "";
	if (-e "/usr/local/cpanel/version") {$imgdir = "/"; $imghddir = ""}
	elsif (-e "/usr/local/directadmin/conf/directadmin.conf") {$imgdir = "/CMD_PLUGINS_ADMIN/csf/images/"; $imghddir = "plugins/csf/images/"}
	if ($config{THIS_UI}) {$imgdir = "$images/"; $imghddir = "/etc/csf/ui/images/"}

	sysopen (STATS,"/etc/csf/stats/lfdmain", O_RDWR | O_CREAT);
	flock (STATS, LOCK_SH);
	my @stats = <STATS>;
	chomp @stats;
	close (STATS);

	if (@stats) {
		my $time = time;
		my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);

		# Blocks by lfd in the last 24 hours
		my $cnt = $hour + 1;
		if ($cnt > 23) {$cnt = 0}
		my (@h,@p,@t,@hp,@cp);
		my %triggers;
		for (my $hours = 0; $hours < 24;$hours++) {
			push @h,$cnt;
			my ($permdate,$permcount,$tempdate,$tempcount) = split(/\,/,$stats[$cnt]);
			if ($time - $permdate > (24 * 60 * 60)) {$permdate = 0; $permcount = 0}
			if ($time - $tempdate > (24 * 60 * 60)) {$tempdate = 0; $tempcount = 0}
			push @p,$permcount;
			push @t,$tempcount;
			my @line = split(/\,/,$stats[$cnt]);
			for (my $loop = 4; $loop < @line; $loop+=2) {
				if ($time - $line[$loop] > (24 * 60 * 60)) {next}
				my ($triggerstat,$triggercount) = split(/\:/,$line[$loop+1]);
				$triggers{$triggerstat} += $triggercount;
			}
			$cnt++;
			if ($cnt > 23) {$cnt = 0}
		}
		my @data = ([@h],[@p],[@t]);
		my $hour_graph = GD::Graph::bars->new(750,350);
		$hour_graph->set( dclrs => [ qw(yellow dred) ] );
		$hour_graph->set(
			x_label => 'Hour',
			y_label => 'Total Blocks',
			long_ticks => 1,
			tick_length => 0,
			x_ticks => 0, 
			title => 'Blocks by lfd in the last 24 hours',
			cumulate => 1,
			borderclrs => $hour_graph->{dclrs},
			bar_spacing => 4,
			shadow_depth => 1,
			transparent => 0,
			x_label_position => 1/2,
		);
		$hour_graph->set_legend( qw(Permanent Temporary));
		$hour_graph->plot(\@data);
		$img = $imghddir."lfd_hour.gif";
		open(OUT, ">$img");
		binmode OUT;
		print OUT $hour_graph->gd->gif();
		close OUT;

		foreach my $key (keys %triggers) {
			push @hp, "$key ($triggers{$key})";
			push @cp, $triggers{$key};
		}
		my @piedata = ([@hp],[@cp]);
		$hour_pie_graph = new GD::Graph::pie( 400, 300 ); 
		$hour_pie_graph->set(
		title => 'Block triggers in the last 24 hours',
		label => 'Trigger in csf.conf',
		axislabelclr => 'black',
		pie_height => 36,
		l_margin => 15,
		r_margin => 15,
		start_angle => 235,
		transparent => 0,
		);
		$hour_pie_graph->plot(\@piedata); 
		$img = $imghddir."lfd_pie_hour.gif";
		open(OUT, ">$img");
		binmode OUT;
		print OUT $hour_pie_graph->gd->gif();
		close OUT;


		# Blocks by lfd in the last 30 Days
		my $maxdays = 30;
		my ($hsec,$hmin,$hhour,$hmday,$hmon,$hyear,$hwday,$hyday,$hisdst) = localtime($time - (29 * 24 * 60 * 60));
		my $hdim = (31,28,31,30,31,30,31,31,30,31,30,31)[$hmon];
		if ($hmon == 1 && (($hyear % 4 == 0) && ($hyear % 100 != 0) && ($hyear % 400 == 0))) {$hdim++}
		if ($hmon == 1) {
			$maxdays = $hdim;
			($hsec,$hmin,$hhour,$hmday,$hmon,$hyear,$hwday,$hyday,$hisdst) = localtime($time - (($maxdays - 1) * 24 * 60 * 60));
		}
		$cnt = $hmday;
		my (@hh,@ph,@th,@hhp,@hcp);
		my %htriggers;
		for (my $days = 1; $days <= $maxdays;$days++) {
			push @hh,$cnt;
			my ($permdate,$permcount,$tempdate,$tempcount) = split(/\,/,$stats[$cnt+24]);
			if ($time - $permdate > (($maxdays - 1) * 24 * 60 * 60)) {$permdate = 0; $permcount = 0}
			if ($time - $tempdate > (($maxdays - 1) * 24 * 60 * 60)) {$tempdate = 0; $tempcount = 0}
			push @ph,$permcount;
			push @th,$tempcount;
			my @line = split(/\,/,$stats[$cnt+24]);
			for (my $loop = 4; $loop < @line; $loop+=2) {
				if ($time - $line[$loop] > (($maxdays - 1) * 24 * 60 * 60)) {next}
				my ($triggerstat,$triggercount) = split(/\:/,$line[$loop+1]);
				$htriggers{$triggerstat} += $triggercount;
			}
			$cnt++;
			if ($cnt > $hdim) {$cnt = 1}
		}
		my @datah = ([@hh],[@ph],[@th]);
		my $day_graph = GD::Graph::bars->new(750,350);
		$day_graph->set( dclrs => [ qw(yellow dred) ] );
		$day_graph->set(
			x_label => 'Day',
			y_label => 'Total Blocks',
			long_ticks => 1,
			tick_length => 0,
			x_ticks => 0, 
			title => "Blocks by lfd in the last $maxdays Days",
			cumulate => 1,
			borderclrs => $day_graph->{dclrs},
			bar_spacing => 4,
			shadow_depth => 1,
			transparent => 0,
			x_label_position => 1/2,
		);
		$day_graph->set_legend( qw(Permanent Temporary));
		$day_graph->plot(\@datah);
		$img = $imghddir."lfd_month.gif";
		open(OUT, ">$img");
		binmode OUT;
		print OUT $day_graph->gd->gif();
		close OUT;

		foreach my $key (keys %htriggers) {
			push @hhp, "$key ($htriggers{$key})";
			push @hcp, $htriggers{$key};
		}
		my @hpiedata = ([@hhp],[@hcp]);
		$day_pie_graph = new GD::Graph::pie( 400, 300 ); 
		$day_pie_graph->set(
		title => "Block triggers in the last $maxdays days",
		label => 'Trigger in csf.conf',
		axislabelclr => 'black',
		pie_height => 36,
		l_margin => 15,
		r_margin => 15,
		start_angle => 235,
		transparent => 0,
		);
		$day_pie_graph->plot(\@hpiedata); 
		$img = $imghddir."lfd_pie_day.gif";
		open(OUT, ">$img");
		binmode OUT;
		print OUT $day_pie_graph->gd->gif();
		close OUT;

		# Blocks by lfd in the last 12 months
		$cnt = $mon + 2;
		if ($cnt > 12) {$cnt = 1}
		my (@hy,@py,@ty,@yhp,@ycp);
		my %ytriggers;
		for (my $months = 1; $months < 13;$months++) {
			push @hy,$cnt;
			my ($permdate,$permcount,$tempdate,$tempcount) = split(/\,/,$stats[$cnt+54]);
			if ($time - $permdate > (364 * 24 * 60 * 60)) {$permdate = 0; $permcount = 0}
			if ($time - $tempdate > (364 * 24 * 60 * 60)) {$tempdate = 0; $tempcount = 0}
			push @py,$permcount;
			push @ty,$tempcount;
			my @line = split(/\,/,$stats[$cnt+54]);
			for (my $loop = 4; $loop < @line; $loop+=2) {
				if ($time - $line[$loop] > (364 * 24 * 60 * 60)) {next}
				my ($triggerstat,$triggercount) = split(/\:/,$line[$loop+1]);
				$ytriggers{$triggerstat} += $triggercount;
			}
			$cnt++;
			if ($cnt > 12) {$cnt = 1}
		}
		my @datay = ([@hy],[@py],[@ty]);
		my $year_graph = GD::Graph::bars->new(750,350);
		$year_graph->set( dclrs => [ qw(yellow dred) ] );
		$year_graph->set(
			x_label => 'Month',
			y_label => 'Total Blocks',
			long_ticks => 1,
			tick_length => 0,
			x_ticks => 0, 
			title => 'Blocks by lfd in the last 12 months',
			cumulate => 1,
			borderclrs => $year_graph->{dclrs},
			bar_spacing => 4,
			shadow_depth => 1,
			transparent => 0,
			x_label_position => 1/2,
		);
		$year_graph->set_legend( qw(Permanent Temporary));
		$year_graph->plot(\@datay);
		$img = $imghddir."lfd_year.gif";
		open(OUT, ">$img");
		binmode OUT;
		print OUT $year_graph->gd->gif();
		close OUT;

		foreach my $key (keys %ytriggers) {
			push @yhp, "$key ($ytriggers{$key})";
			push @ycp, $ytriggers{$key};
		}
		my @ypiedata = ([@yhp],[@ycp]);
		$year_pie_graph = new GD::Graph::pie( 400, 300 ); 
		$year_pie_graph->set(
		title => 'Block triggers in the last 12 months',
		label => 'Trigger in csf.conf',
		axislabelclr => 'black',
		pie_height => 36,
		l_margin => 15,
		r_margin => 15,
		start_angle => 235,
		transparent => 0,
		);
		$year_pie_graph->plot(\@hpiedata); 
		$img = $imghddir."lfd_pie_year.gif";
		open(OUT, ">$img");
		binmode OUT;
		print OUT $year_pie_graph->gd->gif();
		close OUT;

		if ($config{CC_LOOKUPS}) {
			# Total Top 30 Country Code blocks by lfd
			my (@ccy,@ccx);
			my %ccs;
			my $cntcc;
			@line = split(/\,/,$stats[68]);
			for (my $x = 0; $x < @line; $x+=2) {$ccs{$line[$x]} = $line[$x+1]}
			foreach my $key (sort {$ccs{$b} <=> $ccs{$a}} keys %ccs) {
				push @ccy,$key;
				push @ccx,$ccs{$key};
				$cntcc++;
				if ($cntcc > 29) {last}
			}
			my @datacc = ([@ccy],[@ccx]);
			my $cc_graph = GD::Graph::bars->new(750,350);
			$cc_graph->set( dclrs => [ qw(yellow) ] );
			$cc_graph->set(
				x_label => 'Country Code',
				y_label => 'Total Blocks',
				long_ticks => 1,
				tick_length => 0,
				x_ticks => 0, 
				title => 'Total Top 30 Country Code blocks by lfd',
				cumulate => 1,
				borderclrs => $cc_graph->{dclrs},
				bar_spacing => 4,
				shadow_depth => 1,
				transparent => 0,
				x_label_position => 1/2,
			);
			$cc_graph->plot(\@datacc);
			$img = $imghddir."lfd_cc.gif";
			open(OUT, ">$img");
			binmode OUT;
			print OUT $cc_graph->gd->gif();
			close OUT;
		}

		print "<table style='border: 2px #990000 solid' align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF'>\n";
		print "<tr><td style='border-bottom: 2px #990000 solid'>\n";
		print "<p align='center'><img src='".$imgdir."lfd_hour.gif?text=".time."'></p><p>&nbsp;</p>\n";
		if (@cp) {
			print "<p align='center'><img src='".$imgdir."lfd_pie_hour.gif?text=".time."'></p>\n";
		} else {
			print "<p align='center'>No data for pie chart</p>\n";
		}
		print "</td></tr><tr><td style='border-bottom: 2px #990000 solid'>\n";
		print "<p align='center'><img src='".$imgdir."lfd_month.gif?text=".time."'></p><p>&nbsp;</p>\n";
		if (@hcp) {
			print "<p align='center'><img src='".$imgdir."lfd_pie_day.gif?text=".time."'></p>\n";
		} else {
			print "<p align='center'>No data for pie chart</p>\n";
		}
		if ($config{CC_LOOKUPS}) {
			print "</td></tr><tr><td style='border-bottom: 2px #990000 solid'>\n";
			print "<p align='center'><img src='".$imgdir."lfd_year.gif?text=".time."'></p><p>&nbsp;</p>\n";
			if (@ycp) {
				print "<p align='center'><img src='".$imgdir."lfd_pie_year.gif?text=".time."'></p>\n";
			} else {
				print "<p align='center'>No data for pie chart</p>\n";
			}
			print "</td></tr>\n<tr><td>\n";
			print "<p align='center'><img src='".$imgdir."lfd_cc.gif?text=".time."'></p>\n";
		} else {
			print "</td></tr>\n<tr><td>\n";
			print "<p align='center'><img src='".$imgdir."lfd_year.gif?text=".time."'></p><p>&nbsp;</p>\n";
			if (@ycp) {
				print "<p align='center'><img src='".$imgdir."lfd_pie_year.gif?text=".time."'></p>\n";
			} else {
				print "<p align='center'>No data for pie chart</p>\n";
			}
		}
		print "</td></tr></table>\n";
	} else {
		print "<table style='border: 2px #990000 solid' align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF'>\n";
		print "<tr><td align='center'>No statistical data has been collected yet</td></tr></table>\n";
	}
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
# end chart
###############################################################################
# start systemstats
sub systemstats {
	my $type = shift;
	if ($type eq "") {$type = "load"}
	my $img;
	my $imgdir = "";
	my $imghddir = "";
	if (-e "/usr/local/cpanel/version") {$imgdir = "/"; $imghddir = ""}
	elsif (-e "/usr/local/directadmin/conf/directadmin.conf") {$imgdir = "/CMD_PLUGINS_ADMIN/csf/images/"; $imghddir = "plugins/csf/images/"}
	if ($config{THIS_UI}) {$imgdir = "$images/"; $imghddir = "/etc/csf/ui/images/"}

	sysopen (STATS,"/etc/csf/stats/system", O_RDWR | O_CREAT);
	flock (STATS, LOCK_SH);
	my @stats = <STATS>;
	chomp @stats;
	close (STATS);

	if (@stats > 1) {
		eval {
			local $SIG{__DIE__} = undef;
			my $time = time;
			my %stata;
			our %minmaxavg;
			foreach my $line (@stats) {
				my ($thistime,undef) = split(/\,/,$line);
				if (time - $thistime > (86400 * $config{ST_SYSTEM_MAXDAYS})) {next}
				my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($thistime);
				$stata{$year}{$mon}{$mday}{$hour}{$min} = $line;
			}

			if ($type eq "cpu") {
				my (@h,@p,@t);
				my $cputotal_prev;
				my $cpuidle_prev;
				my $cpuiowait_prev;
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $cputotal eq "") {
						$cputotal_prev = 0;
						$cpuidle_prev = 0;
						$cpuiowait_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						my $idle_diff = $cpuidle - $cpuidle_prev;
						my $iowait_diff = $cpuiowait - $cpuiowait_prev;
						my $total_diff = $cputotal - $cputotal_prev;
						if ($total_diff == 0) {
							$cputotal_prev = 0;
							$cpuidle_prev = 0;
							$cpuiowait_prev = 0;
							push @p,undef;
							push @t,undef;
							next;
						}
						my $idle_use = 100 - 100 * ($total_diff - $idle_diff) / $total_diff;
						my $iowait_use = 100 - 100 * ($total_diff - $iowait_diff) / $total_diff;
						$cpuidle_prev = $cpuidle;
						$cpuiowait_prev = $cpuiowait;
						$cputotal_prev = $cputotal;
						push @p,$idle_use;
						push @t,$iowait_use;

						&minmaxavg("HOUR","1Idle",$idle_use);
						&minmaxavg("HOUR","2IOWAIT",$iowait_use);
					}
				}
				$minmaxavg{HOUR}{"1Idle"}{AVG} /= $minmaxavg{HOUR}{"1Idle"}{CNT};
				$minmaxavg{HOUR}{"2IOWAIT"}{AVG} /= $minmaxavg{HOUR}{"2IOWAIT"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => '% CPU',
					x_label_skip => 3,
					line_width => 2,
					title => 'CPU Usage in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Idle IOWAIT));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "cpu") {
				my (@h,@p,@t);
				my $cputotal_prev;
				my $cpuidle_prev;
				my $cpuiowait_prev;
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $cputotal eq "") {
						$cputotal_prev = 0;
						$cpuidle_prev = 0;
						$cpuiowait_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						my $idle_diff = $cpuidle - $cpuidle_prev;
						my $iowait_diff = $cpuiowait - $cpuiowait_prev;
						my $total_diff = $cputotal - $cputotal_prev;
							if ($total_diff == 0) {
								$cputotal_prev = 0;
								$cpuidle_prev = 0;
								$cpuiowait_prev = 0;
								push @p,undef;
								push @t,undef;
								next;
							}
						my $idle_use = 100 - 100 * ($total_diff - $idle_diff) / $total_diff;
						my $iowait_use = 100 - 100 * ($total_diff - $iowait_diff) / $total_diff;
						$cpuidle_prev = $cpuidle;
						$cpuiowait_prev = $cpuiowait;
						$cputotal_prev = $cputotal;
						push @p,$idle_use;
						push @t,$iowait_use;

						&minmaxavg("DAY","1Idle",$idle_use);
						&minmaxavg("DAY","2IOWAIT",$iowait_use);
					}
				}
				$minmaxavg{DAY}{"1Idle"}{AVG} /= $minmaxavg{DAY}{"1Idle"}{CNT};
				$minmaxavg{DAY}{"2IOWAIT"}{AVG} /= $minmaxavg{DAY}{"2IOWAIT"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => '% CPU',
					x_label_skip => 60,
					title => 'CPU Usage in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Idle IOWAIT));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "cpu") {
				my (@h,@p,@t);
				my $cputotal_prev;
				my $cpuidle_prev;
				my $cpuiowait_prev;
				$minmaxavg{WEEK}{"1Idle"}{MIN} = 100;
				$minmaxavg{WEEK}{"1Idle"}{MAX} = 0;
				$minmaxavg{WEEK}{"2IOWAIT"}{MIN} = 100;
				$minmaxavg{WEEK}{"2IOWAIT"}{MAX} = 0;
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $idle_avg;
					my $iowait_avg;
					my $cnt_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $cputotal ne "") {
							my $idle_diff = $cpuidle - $cpuidle_prev;
							my $iowait_diff = $cpuiowait - $cpuiowait_prev;
							my $total_diff = $cputotal - $cputotal_prev;
							if ($total_diff == 0) {
								$cputotal_prev = 0;
								$cpuidle_prev = 0;
								$cpuiowait_prev = 0;
								next;
							}
							my $idle_use = 100 - 100 * ($total_diff - $idle_diff) / $total_diff;
							my $iowait_use = 100 - 100 * ($total_diff - $iowait_diff) / $total_diff;
							$cpuidle_prev = $cpuidle;
							$cpuiowait_prev = $cpuiowait;
							$cputotal_prev = $cputotal;
							$idle_avg += $idle_use;
							$iowait_avg += $iowait_use;
							$cnt_avg++;
						} else {
							$cputotal_prev = 0;
							$cpuidle_prev = 0;
							$cpuiowait_prev = 0;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$idle_avg/$cnt_avg;
						push @t,$iowait_avg/$cnt_avg;
						&minmaxavg("WEEK","1Idle",($idle_avg/$cnt_avg));
						&minmaxavg("WEEK","2IOWAIT",($iowait_avg/$cnt_avg));
					}
				}
				$minmaxavg{WEEK}{"1Idle"}{AVG} /= $minmaxavg{WEEK}{"1Idle"}{CNT};
				$minmaxavg{WEEK}{"2IOWAIT"}{AVG} /= $minmaxavg{WEEK}{"2IOWAIT"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => '% CPU',
					x_label_skip => 24,
					title => 'CPU Usage in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Idle IOWAIT));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "cpu") {
				my (@h,@p,@t);
				my $cputotal_prev;
				my $cpuidle_prev;
				my $cpuiowait_prev;
				$minmaxavg{MONTH}{"1Idle"}{MIN} = 100;
				$minmaxavg{MONTH}{"1Idle"}{MAX} = 0;
				$minmaxavg{MONTH}{"2IOWAIT"}{MIN} = 100;
				$minmaxavg{MONTH}{"2IOWAIT"}{MAX} = 0;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $idle_avg;
					my $iowait_avg;
					my $cnt_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $cputotal ne "") {
							my $idle_diff = $cpuidle - $cpuidle_prev;
							my $iowait_diff = $cpuiowait - $cpuiowait_prev;
							my $total_diff = $cputotal - $cputotal_prev;
							if ($total_diff == 0) {
								$cputotal_prev = 0;
								$cpuidle_prev = 0;
								$cpuiowait_prev = 0;
								next;
							}
							my $idle_use = 100 - 100 * ($total_diff - $idle_diff) / $total_diff;
							my $iowait_use = 100 - 100 * ($total_diff - $iowait_diff) / $total_diff;
							$cpuidle_prev = $cpuidle;
							$cpuiowait_prev = $cpuiowait;
							$cputotal_prev = $cputotal;
							$idle_avg += $idle_use;
							$iowait_avg += $iowait_use;
							$cnt_avg++;
						} else {
							$cputotal_prev = 0;
							$cpuidle_prev = 0;
							$cpuiowait_prev = 0;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$idle_avg/$cnt_avg;
						push @t,$iowait_avg/$cnt_avg;
						&minmaxavg("MONTH","1Idle",($idle_avg/$cnt_avg));
						&minmaxavg("MONTH","2IOWAIT",($iowait_avg/$cnt_avg));
					}
				}
				$minmaxavg{MONTH}{"1Idle"}{AVG} /= $minmaxavg{MONTH}{"1Idle"}{CNT};
				$minmaxavg{MONTH}{"2IOWAIT"}{AVG} /= $minmaxavg{MONTH}{"2IOWAIT"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => '% CPU',
					x_label_skip => 24,
					title => "CPU Usage in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Idle IOWAIT));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mem") {
				my (@h,@p,@t,@a,@b);
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $memtotal eq "") {
						push @p,undef;
						push @t,undef;
						push @a,undef;
						push @b,undef;
					} else {
						$memfree = $memtotal - $memfree;
						$memswapfree = $memswaptotal - $memswapfree;
						push @p,$memtotal;
						push @t,$memfree;
						push @a,$memswaptotal;
						push @b,$memswapfree;

						&minmaxavg("HOUR","1Used",$memfree);
						&minmaxavg("HOUR","2SwapUsed",$memswapfree);
					}
				}
				$minmaxavg{HOUR}{"1Used"}{AVG} /= $minmaxavg{HOUR}{"1Used"}{CNT};
				$minmaxavg{HOUR}{"2SwapUsed"}{AVG} /= $minmaxavg{HOUR}{"2SwapUsed"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a],[reverse @b]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple blue) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Memory (KB)',
					x_label_skip => 3,
					title => 'Memory Usage in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Total Used SwapTotal SwapUsed));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mem") {
				my (@h,@p,@t,@a,@b);
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $memtotal eq "") {
						push @p,undef;
						push @t,undef;
						push @a,undef;
						push @b,undef;
					} else {
						$memfree = $memtotal - $memfree;
						$memswapfree = $memswaptotal - $memswapfree;
						push @p,$memtotal;
						push @t,$memfree;
						push @a,$memswaptotal;
						push @b,$memswapfree;

						&minmaxavg("DAY","1Used",$memfree);
						&minmaxavg("DAY","2SwapUsed",$memswapfree);
					}
				}
				$minmaxavg{DAY}{"1Used"}{AVG} /= $minmaxavg{DAY}{"1Used"}{CNT};
				$minmaxavg{DAY}{"2SwapUsed"}{AVG} /= $minmaxavg{DAY}{"2SwapUsed"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a],[reverse @b]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple blue) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Memory (KB)',
					x_label_skip => 60,
					title => 'Memory Usage in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Total Used SwapTotal SwapUsed));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mem") {
				my (@h,@p,@t,@a,@b);
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $memtotal_avg;
					my $memfree_avg;
					my $memswaptotal_avg;
					my $memswapfree_avg;
					my $cnt_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $memtotal ne "") {
							$memfree = $memtotal - $memfree;
							$memswapfree = $memswaptotal - $memswapfree;
							$memtotal_avg += $memtotal;
							$memfree_avg += $memfree;
							$memswaptotal_avg += $memswaptotal;
							$memswapfree_avg += $memswapfree;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
						push @a,undef;
						push @b,undef;
					} else {
						push @p,$memtotal_avg/$cnt_avg;
						push @t,$memfree_avg/$cnt_avg;
						push @a,$memswaptotal_avg/$cnt_avg;
						push @b,$memswapfree_avg/$cnt_avg;

						&minmaxavg("WEEK","1Used",($memfree_avg/$cnt_avg));
						&minmaxavg("WEEK","2SwapUsed",($memswapfree_avg/$cnt_avg));
					}
				}
				$minmaxavg{WEEK}{"1Used"}{AVG} /= $minmaxavg{WEEK}{"1Used"}{CNT};
				$minmaxavg{WEEK}{"2SwapUsed"}{AVG} /= $minmaxavg{WEEK}{"1Used"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a],[reverse @b]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple blue) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Memory (KB)',
					x_label_skip => 24,
					title => 'Memory Usage in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Total Used SwapTotal SwapUsed));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mem") {
				my (@h,@p,@t,@a,@b);
				my $cputotal_prev;
				my $cpuidle_prev;
				my $cpuiowait_prev;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $memtotal_avg;
					my $memfree_avg;
					my $memswaptotal_avg;
					my $memswapfree_avg;
					my $cnt_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $memtotal ne "") {
							$memfree = $memtotal - $memfree;
							$memswapfree = $memswaptotal - $memswapfree;
							$memtotal_avg += $memtotal;
							$memfree_avg += $memfree;
							$memswaptotal_avg += $memswaptotal;
							$memswapfree_avg += $memswapfree;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
						push @a,undef;
						push @b,undef;
					} else {
						push @p,$memtotal_avg/$cnt_avg;
						push @t,$memfree_avg/$cnt_avg;
						push @a,$memswaptotal_avg/$cnt_avg;
						push @b,$memswapfree_avg/$cnt_avg;

						&minmaxavg("MONTH","1Used",($memfree_avg/$cnt_avg));
						&minmaxavg("MONTH","2SwapUsed",($memswapfree_avg/$cnt_avg));
					}
				}
				$minmaxavg{MONTH}{"1Used"}{AVG} /= $minmaxavg{MONTH}{"1Used"}{CNT};
				$minmaxavg{MONTH}{"2SwapUsed"}{AVG} /= $minmaxavg{MONTH}{"2SwapUsed"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a],[reverse @b]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple blue) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Memory (Bytes)',
					x_label_skip => 24,
					title => "Memory Usage in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Total Used SwapTotal SwapUsed));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "load") {
				my (@h,@p,@t,@a);
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $load1 eq "") {
						push @p,undef;
						push @t,undef;
						push @a,undef;
					} else {
						push @p,$load1;
						push @t,$load5;
						push @a,$load15;

						&minmaxavg("HOUR","1Load_1",$load1);
						&minmaxavg("HOUR","2Load_5",$load5);
						&minmaxavg("HOUR","3Load_15",$load15);
					}
				}
				$minmaxavg{HOUR}{"1Load_1"}{AVG} /= $minmaxavg{HOUR}{"1Load_1"}{CNT};
				$minmaxavg{HOUR}{"2Load_5"}{AVG} /= $minmaxavg{HOUR}{"2Load_5"}{CNT};
				$minmaxavg{HOUR}{"3Load_15"}{AVG} /= $minmaxavg{HOUR}{"3Load_15"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Load Average',
					x_label_skip => 3,
					title => 'Load Averages in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Load_1 Load_5 Load_15));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "load") {
				my (@h,@p,@t,@a);
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $load1 eq "") {
						push @p,undef;
						push @t,undef;
						push @a,undef;
					} else {
						push @p,$load1;
						push @t,$load5;
						push @a,$load15;

						&minmaxavg("DAY","1Load_1",$load1);
						&minmaxavg("DAY","2Load_5",$load5);
						&minmaxavg("DAY","3Load_15",$load15);
					}
				}
				$minmaxavg{DAY}{"1Load_1"}{AVG} /= $minmaxavg{DAY}{"1Load_1"}{CNT};
				$minmaxavg{DAY}{"2Load_5"}{AVG} /= $minmaxavg{DAY}{"2Load_5"}{CNT};
				$minmaxavg{DAY}{"3Load_15"}{AVG} /= $minmaxavg{DAY}{"3Load_15"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Load Average',
					x_label_skip => 60,
					title => 'Load Averages in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Load_1 Load_5 Load_15));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "load") {
				my (@h,@p,@t,@a);
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $load1_avg;
					my $load5_avg;
					my $load15_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $load1 ne "") {
							$load1_avg += $load1;
							$load5_avg += $load5;
							$load15_avg += $load15;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
						push @a,undef;
					} else {
						push @p,$load1_avg/$cnt_avg;
						push @t,$load5_avg/$cnt_avg;
						push @a,$load15_avg/$cnt_avg;

						&minmaxavg("WEEK","1Load_1",($load1_avg/$cnt_avg));
						&minmaxavg("WEEK","2Load_5",($load5_avg/$cnt_avg));
						&minmaxavg("WEEK","3Load_15",($load15_avg/$cnt_avg));
					}
				}
				$minmaxavg{WEEK}{"1Load_1"}{AVG} /= $minmaxavg{WEEK}{"1Load_1"}{CNT};
				$minmaxavg{WEEK}{"2Load_5"}{AVG} /= $minmaxavg{WEEK}{"2Load_5"}{CNT};
				$minmaxavg{WEEK}{"3Load_15"}{AVG} /= $minmaxavg{WEEK}{"3Load_15"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Load Average',
					x_label_skip => 24,
					title => 'Load Averages in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Load_1 Load_5 Load_15));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "load") {
				my (@h,@p,@t,@a);
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $load1_avg;
					my $load5_avg;
					my $load15_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $load1 ne "") {
							$load1_avg += $load1;
							$load5_avg += $load5;
							$load15_avg += $load15;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
						push @a,undef;
					} else {
						push @p,$load1_avg/$cnt_avg;
						push @t,$load5_avg/$cnt_avg;
						push @a,$load15_avg/$cnt_avg;

						&minmaxavg("MONTH","1Load_1",($load1_avg/$cnt_avg));
						&minmaxavg("MONTH","2Load_5",($load5_avg/$cnt_avg));
						&minmaxavg("MONTH","3Load_15",($load15_avg/$cnt_avg));
					}
				}
				$minmaxavg{MONTH}{"1Load_1"}{AVG} /= $minmaxavg{MONTH}{"1Load_1"}{CNT};
				$minmaxavg{MONTH}{"2Load_5"}{AVG} /= $minmaxavg{MONTH}{"2Load_5"}{CNT};
				$minmaxavg{MONTH}{"3Load_15"}{AVG} /= $minmaxavg{MONTH}{"3Load_15"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t],[reverse @a]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple blue) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Load Average',
					x_label_skip => 24,
					title => "Load Averages in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Load_1 Load_5 Load_15));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "net") {
				my (@h,@p,@t);
				my $netin_prev;
				my $netout_prev;
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $netin eq "") {
						$netin_prev = 0;
						$netout_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($netin_prev < $netin or $netin eq "") {
							push @p,undef;
							$netin_prev = $netin;
						} else {
							my $netin_val = ($netin_prev - $netin) / 60;
							push @p,$netin_val;
							$netin_prev = $netin;
							&minmaxavg("HOUR","1Inbound",$netin_val);
						}
						if ($netout_prev < $netout or $netout eq "") {
							push @t,undef;
							$netout_prev = $netout;
						} else {
							my $netout_val = ($netout_prev - $netout) / 60;
							push @t,$netout_val;
							$netout_prev = $netout;
							&minmaxavg("HOUR","2Outbound",$netout_val);
						}
					}
				}
				$minmaxavg{HOUR}{"1Inbound"}{AVG} /= $minmaxavg{HOUR}{"1Inbound"}{CNT};
				$minmaxavg{HOUR}{"2Outbound"}{AVG} /= $minmaxavg{HOUR}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Bytes/Second',
					x_label_skip => 3,
					title => 'Network Usage in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "net") {
				my (@h,@p,@t);
				my $netin_prev;
				my $netout_prev;
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $netin eq "") {
						$netin_prev = 0;
						$netout_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($netin_prev < $netin or $netin eq "") {
							push @p,undef;
							$netin_prev = $netin;
						} else {
							my $netin_val = ($netin_prev - $netin) / 60;
							push @p,$netin_val;
							$netin_prev = $netin;
							&minmaxavg("DAY","1Inbound",$netin_val);
						}
						if ($netout_prev < $netout or $netout eq "") {
							push @t,undef;
							$netout_prev = $netout;
						} else {
							my $netout_val = ($netout_prev - $netout) / 60;
							push @t,$netout_val;
							$netout_prev = $netout;
							&minmaxavg("DAY","2Outbound",$netout_val);
						}
					}
				}
				$minmaxavg{DAY}{"1Inbound"}{AVG} /= $minmaxavg{DAY}{"1Inbound"}{CNT};
				$minmaxavg{DAY}{"2Outbound"}{AVG} /= $minmaxavg{DAY}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Bytes/Second',
					x_label_skip => 60,
					title => 'Network Usage in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "net") {
				my (@h,@p,@t);
				my $netin_prev;
				my $netout_prev;
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $netin_avg;
					my $netout_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $netin eq "") {
							$netin_prev = 0;
							$netout_prev = 0;
						} else {
							if ($netin_prev < $netin or $netin eq "") {
								$netin_prev = $netin;
							} else {
								my $netin_val = ($netin_prev - $netin) / 60;
								$netin_avg = $netin_avg + $netin_val;
								$netin_prev = $netin;
							}
							if ($netout_prev < $netout or $netout eq "") {
								$netout_prev = $netout;
							} else {
								my $netout_val = ($netout_prev - $netout) / 60;
								$netout_avg = $netout_avg + $netout_val;
								$netout_prev = $netout;
							}
						}
					}
					if ($netin_avg == 0) {
						push @p,undef;
					} else {
						push @p,($netin_avg/60);
						&minmaxavg("WEEK","1Inbound",($netin_avg/60));
					}
					if ($netout_avg == 0) {
						push @t,undef;
					} else {
						push @t,($netout_avg/60);
						&minmaxavg("WEEK","2Outbound",($netout_avg/60));
					}
				}
				$minmaxavg{WEEK}{"1Inbound"}{AVG} /= $minmaxavg{WEEK}{"1Inbound"}{CNT};
				$minmaxavg{WEEK}{"2Outbound"}{AVG} /= $minmaxavg{WEEK}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Bytes/Second',
					x_label_skip => 24,
					title => 'Network Usage in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "net") {
				my (@h,@p,@t);
				my $netin_prev;
				my $netout_prev;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $netin_avg;
					my $netout_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $netin eq "") {
							$netin_prev = 0;
							$netout_prev = 0;
						} else {
							if ($netin_prev < $netin or $netin eq "") {
								$netin_prev = $netin;
							} else {
								my $netin_val = ($netin_prev - $netin) / 60;
								$netin_avg = $netin_avg + $netin_val;
								$netin_prev = $netin;
							}
							if ($netout_prev < $netout or $netout eq "") {
								$netout_prev = $netout;
							} else {
								my $netout_val = ($netout_prev - $netout) / 60;
								$netout_avg = $netout_avg + $netout_val;
								$netout_prev = $netout;
							}
						}
					}
					if ($netin_avg == 0) {
						push @p,undef;
					} else {
						push @p,($netin_avg/60);
						&minmaxavg("MONTH","1Inbound",($netin_avg/60));
					}
					if ($netout_avg == 0) {
						push @t,undef;
					} else {
						push @t,($netout_avg/60);
						&minmaxavg("MONTH","2Outbound",($netout_avg/60));
					}
				}
				$minmaxavg{MONTH}{"1Inbound"}{AVG} /= $minmaxavg{MONTH}{"1Inbound"}{CNT};
				$minmaxavg{MONTH}{"2Outbound"}{AVG} /= $minmaxavg{MONTH}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Bytes/Second',
					x_label_skip => 24,
					title => "Network Usage in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "disk") {
				my (@h,@p,@t);
				my $diskread_prev;
				my $diskwrite_prev;
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $diskread eq "") {
						$diskread_prev = 0;
						$diskwrite_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($diskread_prev < $diskread or $diskread eq "") {
							push @p,undef;
							$diskread_prev = $diskread;
						} else {
							my $diskread_val = ($diskread_prev - $diskread) / 60;
							push @p,$diskread_val;
							$diskread_prev = $diskread;
							&minmaxavg("HOUR","1Reads",$diskread_val);
						}
						if ($diskwrite_prev < $diskwrite or $diskwrite eq "") {
							push @t,undef;
							$diskwrite_prev = $diskwrite;
						} else {
							my $diskwrite_val = ($diskwrite_prev - $diskwrite) / 60;
							push @t,$diskwrite_val;
							$diskwrite_prev = $diskwrite;
							&minmaxavg("HOUR","2Writes",$diskwrite_val);
						}
					}
				}
				$minmaxavg{HOUR}{"1Reads"}{AVG} /= $minmaxavg{HOUR}{"1Reads"}{CNT};
				$minmaxavg{HOUR}{"2Writes"}{AVG} /= $minmaxavg{HOUR}{"2Writes"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'IO/Second',
					x_label_skip => 3,
					title => 'Disk Usage in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Reads Writes));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "disk") {
				my (@h,@p,@t);
				my $diskread_prev;
				my $diskwrite_prev;
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $diskread eq "") {
						$diskread_prev = 0;
						$diskwrite_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($diskread_prev < $diskread or $diskread eq "") {
							push @p,undef;
							$diskread_prev = $diskread;
						} else {
							my $diskread_val = ($diskread_prev - $diskread) / 60;
							push @p,$diskread_val;
							$diskread_prev = $diskread;
							&minmaxavg("DAY","1Reads",$diskread_val);
					}
						if ($diskwrite_prev < $diskwrite or $diskwrite eq "") {
							push @t,undef;
							$diskwrite_prev = $diskwrite;
						} else {
							my $diskwrite_val = ($diskwrite_prev - $diskwrite) / 60;
							push @t,$diskwrite_val;
							$diskwrite_prev = $diskwrite;
							&minmaxavg("DAY","2Writes",$diskwrite_val);
						}
					}
				}
				$minmaxavg{DAY}{"1Reads"}{AVG} /= $minmaxavg{DAY}{"1Reads"}{CNT};
				$minmaxavg{DAY}{"2Writes"}{AVG} /= $minmaxavg{DAY}{"2Writes"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'IO/Second',
					x_label_skip => 60,
					title => 'Disk Usage in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Reads Writes));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "disk") {
				my (@h,@p,@t);
				my $diskread_prev;
				my $diskwrite_prev;
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $diskread_avg;
					my $diskwrite_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $diskread eq "") {
							$diskread_prev = 0;
							$diskwrite_prev = 0;
						} else {
							if ($diskread_prev < $diskread or $diskread eq "") {
								$diskread_prev = $diskread;
							} else {
								$diskread_avg = $diskread_avg + ($diskread_prev - $diskread)/60;
								$diskread_prev = $diskread;
							}
							if ($diskwrite_prev < $diskwrite or $diskwrite eq "") {
								$diskwrite_prev = $diskwrite;
							} else {
								$diskwrite_avg = $diskwrite_avg + ($diskwrite_prev - $diskwrite)/60;
								$diskwrite_prev = $diskwrite;
							}
						}
					}
					if ($diskread_avg == 0) {
						push @p,undef;
					} else {
						push @p,($diskread_avg/60);
						&minmaxavg("WEEK","1Reads",($diskread_avg/60));
					}
					if ($diskwrite_avg == 0) {
						push @t,undef;
					} else {
						push @t,($diskwrite_avg/60);
						&minmaxavg("WEEK","2Writes",($diskwrite_avg/60));
					}
				}
				$minmaxavg{WEEK}{"1Reads"}{AVG} /= $minmaxavg{WEEK}{"1Reads"}{CNT};
				$minmaxavg{WEEK}{"2Writes"}{AVG} /= $minmaxavg{WEEK}{"2Writes"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'IO/Second',
					x_label_skip => 24,
					title => 'Disk Usage in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Reads Writes));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "disk") {
				my (@h,@p,@t);
				my $diskread_prev;
				my $diskwrite_prev;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $diskread_avg;
					my $diskwrite_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $diskread eq "") {
							$diskread_prev = 0;
							$diskwrite_prev = 0;
						} else {
							if ($diskread_prev < $diskread or $diskread eq "") {
								$diskread_prev = $diskread;
							} else {
								$diskread_avg = $diskread_avg + ($diskread_prev - $diskread)/60;
								$diskread_prev = $diskread;
							}
							if ($diskwrite_prev < $diskwrite or $diskwrite eq "") {
								$diskwrite_prev = $diskwrite;
							} else {
								$diskwrite_avg = $diskwrite_avg + ($diskwrite_prev - $diskwrite)/60;
								$diskwrite_prev = $diskwrite;
							}
						}
					}
					if ($diskread_avg == 0) {
						push @p,undef;
					} else {
						push @p,($diskread_avg/60);
						&minmaxavg("MONTH","1Reads",($diskread_avg/60));
					}
					if ($diskwrite_avg == 0) {
						push @t,undef;
					} else {
						push @t,($diskwrite_avg/60);
						&minmaxavg("MONTH","2Writes",($diskwrite_avg/60));
					}
				}
				$minmaxavg{MONTH}{"1Reads"}{AVG} /= $minmaxavg{MONTH}{"1Reads"}{CNT};
				$minmaxavg{MONTH}{"2Writes"}{AVG} /= $minmaxavg{MONTH}{"2Writes"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'IO/Second',
					x_label_skip => 24,
					title => "Disk Usage in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Reads Writes));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
			
			if ($type eq "email") {
				my (@h,@p,@t);
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mailin eq "") {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$mailin;
						push @t,$mailout;

						&minmaxavg("HOUR","1Received",$mailin);
						&minmaxavg("HOUR","2Sent",$mailout);
					}
				}
				$minmaxavg{HOUR}{"1Received"}{AVG} /= $minmaxavg{HOUR}{"1Received"}{CNT};
				$minmaxavg{HOUR}{"2Sent"}{AVG} /= $minmaxavg{HOUR}{"2Sent"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Emails',
					x_label_skip => 3,
					title => 'Email Usage in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Received Sent));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "email") {
				my (@h,@p,@t);
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mailin eq "") {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$mailin;
						push @t,$mailout;

						&minmaxavg("DAY","1Received",$mailin);
						&minmaxavg("DAY","2Sent",$mailout);
					}
				}
				$minmaxavg{DAY}{"1Received"}{AVG} /= $minmaxavg{DAY}{"1Received"}{CNT};
				$minmaxavg{DAY}{"2Sent"}{AVG} /= $minmaxavg{DAY}{"2Sent"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Emails',
					x_label_skip => 60,
					title => 'Email Usage in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Received Sent));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "email") {
				my (@h,@p,@t);
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mailin_avg;
					my $mailout_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $mailin ne "") {
							$mailin_avg += $mailin;
							$mailout_avg += $mailout;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$mailin_avg/$cnt_avg;
						push @t,$mailout_avg/$cnt_avg;

						&minmaxavg("WEEK","1Received",($mailin_avg/$cnt_avg));
						&minmaxavg("WEEK","2Sent",($mailout_avg/$cnt_avg));
					}
				}
				$minmaxavg{WEEK}{"1Received"}{AVG} /= $minmaxavg{WEEK}{"1Received"}{CNT};
				$minmaxavg{WEEK}{"2Sent"}{AVG} /= $minmaxavg{WEEK}{"2Sent"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Emails',
					x_label_skip => 24,
					title => 'Email Usage in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Received Sent));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "email") {
				my (@h,@p,@t);
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mailin_avg;
					my $mailout_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $mailin ne "") {
							$mailin_avg += $mailin;
							$mailout_avg += $mailout;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$mailin_avg/$cnt_avg;
						push @t,$mailout_avg/$cnt_avg;

						&minmaxavg("MONTH","1Received",($mailin_avg/$cnt_avg));
						&minmaxavg("MONTH","2Sent",($mailout_avg/$cnt_avg));
					}
				}
				$minmaxavg{MONTH}{"1Received"}{AVG} /= $minmaxavg{MONTH}{"1Received"}{CNT};
				$minmaxavg{MONTH}{"2Sent"}{AVG} /= $minmaxavg{MONTH}{"2Sent"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Emails',
					x_label_skip => 24,
					title => "Email Usage in last $config{ST_SYSTEM_MAXDAYS}",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Received Sent));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
			
			if ($type eq "temp") {
				my (@h,@p);
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $cputemp eq "") {
						push @p,undef;
					} else {
						push @p,$cputemp;

						&minmaxavg("HOUR","1CPU",$cputemp);
					}
				}
				$minmaxavg{HOUR}{"1CPU"}{AVG} /= $minmaxavg{HOUR}{"1CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Centigrade',
					x_label_skip => 3,
					title => 'CPU Temp in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Highest Core Temperature");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "temp") {
				my (@h,@p);
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $cputemp eq "") {
						push @p,undef;
					} else {
						push @p,$cputemp;

						&minmaxavg("DAY","1CPU",$cputemp);
					}
				}
				$minmaxavg{DAY}{"1CPU"}{AVG} /= $minmaxavg{DAY}{"1CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Centigrade',
					x_label_skip => 60,
					title => 'CPU Temp in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Highest Core Temperature");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "temp") {
				my (@h,@p);
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $cputemp_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $cputemp ne "") {
							$cputemp_avg += $cputemp;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
					} else {
						push @p,$cputemp_avg/$cnt_avg;

						&minmaxavg("WEEK","1CPU",($cputemp_avg/$cnt_avg));
					}
				}
				$minmaxavg{WEEK}{"1CPU"}{AVG} /= $minmaxavg{WEEK}{"1CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Centigrade',
					x_label_skip => 24,
					title => 'CPU Temp in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Highest Core Temperature");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "temp") {
				my (@h,@p);
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $cputemp_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $cputemp ne "") {
							$cputemp_avg += $cputemp;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
					} else {
						push @p,$cputemp_avg/$cnt_avg;

						&minmaxavg("MONTH","1CPU",($cputemp_avg/$cnt_avg));
					}
				}
				$minmaxavg{MONTH}{"1CPU"}{AVG} /= $minmaxavg{MONTH}{"1CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Centigrade',
					x_label_skip => 24,
					title => "CPU Temp in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Highest Core Temperature");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
			
			if ($type eq "mysqldata") {
				my (@h,@p,@t);
				my $mysqlin_prev;
				my $mysqlout_prev;
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mysqlin eq "") {
						$mysqlin_prev = 0;
						$mysqlout_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($mysqlin_prev < $mysqlin or $mysqlin eq "") {
							push @p,undef;
							$mysqlin_prev = $mysqlin;
						} else {
							my $mysqlin_val = ($mysqlin_prev - $mysqlin) / 60;
							push @p,$mysqlin_val;
							$mysqlin_prev = $mysqlin;
							&minmaxavg("HOUR","1Inbound",$mysqlin_val);
						}
						if ($mysqlout_prev < $mysqlout or $mysqlout eq "") {
							push @t,undef;
							$mysqlout_prev = $mysqlout;
						} else {
							my $mysqlout_val = ($mysqlout_prev - $mysqlout) / 60;
							push @t,$mysqlout_val;
							$mysqlout_prev = $mysqlout;
							&minmaxavg("HOUR","2Outbound",$mysqlout_val);
						}
					}
				}
				$minmaxavg{HOUR}{"1Inbound"}{AVG} /= $minmaxavg{HOUR}{"1Inbound"}{CNT};
				$minmaxavg{HOUR}{"2Outbound"}{AVG} /= $minmaxavg{HOUR}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Bytes/Second',
					x_label_skip => 3,
					title => 'MySQL Data in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqldata") {
				my (@h,@p,@t);
				my $mysqlin_prev;
				my $mysqlout_prev;
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mysqlin eq "") {
						$mysqlin_prev = 0;
						$mysqlout_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($mysqlin_prev < $mysqlin or $mysqlin eq "") {
							push @p,undef;
							$mysqlin_prev = $mysqlin;
						} else {
							my $mysqlin_val = ($mysqlin_prev - $mysqlin) / 60;
							push @p,$mysqlin_val;
							$mysqlin_prev = $mysqlin;
							&minmaxavg("DAY","1Inbound",$mysqlin_val);
						}
						if ($mysqlout_prev < $mysqlout or $mysqlout eq "") {
							push @t,undef;
							$mysqlout_prev = $mysqlout;
						} else {
							my $mysqlout_val = ($mysqlout_prev - $mysqlout) / 60;
							push @t,$mysqlout_val;
							$mysqlout_prev = $mysqlout;
							&minmaxavg("DAY","2Outbound",$mysqlout_val);
						}
					}
				}
				$minmaxavg{DAY}{"1Inbound"}{AVG} /= $minmaxavg{DAY}{"1Inbound"}{CNT};
				$minmaxavg{DAY}{"2Outbound"}{AVG} /= $minmaxavg{DAY}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Bytes/Second',
					x_label_skip => 60,
					title => 'MySQL Data in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqldata") {
				my (@h,@p,@t);
				my $mysqlin_prev;
				my $mysqlout_prev;
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mysqlin_avg;
					my $mysqlout_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $mysqlin eq "") {
							$mysqlin_prev = 0;
							$mysqlout_prev = 0;
						} else {
							if ($mysqlin_prev < $mysqlin or $mysqlin eq "") {
								$mysqlin_prev = $mysqlin;
							} else {
								my $mysqlin_val = ($mysqlin_prev - $mysqlin) / 60;
								$mysqlin_avg = $mysqlin_avg + $mysqlin_val;
								$mysqlin_prev = $mysqlin;
							}
							if ($mysqlout_prev < $mysqlout or $mysqlout eq "") {
								$mysqlout_prev = $mysqlout;
							} else {
								my $mysqlout_val = ($mysqlout_prev - $mysqlout) / 60;
								$mysqlout_avg = $mysqlout_avg + $mysqlout_val;
								$mysqlout_prev = $mysqlout;
							}
						}
					}
					if ($mysqlin_avg == 0) {
						push @p,undef;
					} else {
						push @p,($mysqlin_avg/60);
						&minmaxavg("WEEK","1Inbound",($mysqlin_avg/60));
					}
					if ($mysqlout_avg == 0) {
						push @t,undef;
					} else {
						push @t,($mysqlout_avg/60);
						&minmaxavg("WEEK","2Outbound",($mysqlout_avg/60));
					}
				}
				$minmaxavg{WEEK}{"1Inbound"}{AVG} /= $minmaxavg{WEEK}{"1Inbound"}{CNT};
				$minmaxavg{WEEK}{"2Outbound"}{AVG} /= $minmaxavg{WEEK}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Bytes/Second',
					x_label_skip => 24,
					title => 'MySQL Data in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqldata") {
				my (@h,@p,@t);
				my $mysqlin_prev;
				my $mysqlout_prev;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mysqlin_avg;
					my $mysqlout_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $mysqlin eq "") {
							$mysqlin_prev = 0;
							$mysqlout_prev = 0;
						} else {
							if ($mysqlin_prev < $mysqlin or $mysqlin eq "") {
								$mysqlin_prev = $mysqlin;
							} else {
								my $mysqlin_val = ($mysqlin_prev - $mysqlin) / 60;
								$mysqlin_avg = $mysqlin_avg + $mysqlin_val;
								$mysqlin_prev = $mysqlin;
							}
							if ($mysqlout_prev < $mysqlout or $mysqlout eq "") {
								$mysqlout_prev = $mysqlout;
							} else {
								my $mysqlout_val = ($mysqlout_prev - $mysqlout) / 60;
								$mysqlout_avg = $mysqlout_avg + $mysqlout_val;
								$mysqlout_prev = $mysqlout;
							}
						}
					}
					if ($mysqlin_avg == 0) {
						push @p,undef;
					} else {
						push @p,($mysqlin_avg/60);
						&minmaxavg("MONTH","1Inbound",($mysqlin_avg/60));
					}
					if ($mysqlout_avg == 0) {
						push @t,undef;
					} else {
						push @t,($mysqlout_avg/60);
						&minmaxavg("MONTH","2Outbound",($mysqlout_avg/60));
					}
				}
				$minmaxavg{MONTH}{"1Inbound"}{AVG} /= $minmaxavg{MONTH}{"1Inbound"}{CNT};
				$minmaxavg{MONTH}{"2Outbound"}{AVG} /= $minmaxavg{MONTH}{"2Outbound"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Bytes/Second',
					x_label_skip => 24,
					title => "MySQL Data in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Inbound Outbound));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
			
			if ($type eq "mysqlqueries") {
				my (@h,@p,@t);
				my $mysqlq_prev;
				my $mysqlsq_prev;
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mysqlq eq "") {
						$mysqlq_prev = 0;
						$mysqlsq_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($mysqlq_prev < $mysqlq or $mysqlq eq "") {
							push @p,undef;
							$mysqlq_prev = $mysqlq;
						} else {
							my $mysqlq_val = ($mysqlq_prev - $mysqlq);
							push @p,$mysqlq_val;
							$mysqlq_prev = $mysqlq;
							&minmaxavg("HOUR","1Queries",$mysqlq_val);
						}
						if ($mysqlsq_prev < $mysqlsq or $mysqlsq eq "") {
							push @t,undef;
							$mysqlsq_prev = $mysqlsq;
						} else {
							my $mysqlsq_val = ($mysqlsq_prev - $mysqlsq);
							push @t,$mysqlsq_val;
							$mysqlsq_prev = $mysqlsq;
							&minmaxavg("HOUR","2Slow_Queries",$mysqlsq_val);
						}
					}
				}
				$minmaxavg{HOUR}{"1Queries"}{AVG} /= $minmaxavg{HOUR}{"1Queries"}{CNT};
				$minmaxavg{HOUR}{"2Slow_Queries"}{AVG} /= $minmaxavg{HOUR}{"2Slow_Queries"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Queries',
					x_label_skip => 3,
					title => 'MySQL Queries in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Queries Slow_Queries));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqlqueries") {
				my (@h,@p,@t);
				my $mysqlq_prev;
				my $mysqlsq_prev;
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mysqlq eq "") {
						$mysqlq_prev = 0;
						$mysqlsq_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($mysqlq_prev < $mysqlq or $mysqlq eq "") {
							push @p,undef;
							$mysqlq_prev = $mysqlq;
						} else {
							my $mysqlq_val = ($mysqlq_prev - $mysqlq);
							push @p,$mysqlq_val;
							$mysqlq_prev = $mysqlq;
							&minmaxavg("DAY","1Queries",$mysqlq_val);
						}
						if ($mysqlsq_prev < $mysqlsq or $mysqlsq eq "") {
							push @t,undef;
							$mysqlsq_prev = $mysqlsq;
						} else {
							my $mysqlsq_val = ($mysqlsq_prev - $mysqlsq);
							push @t,$mysqlsq_val;
							$mysqlsq_prev = $mysqlsq;
							&minmaxavg("DAY","2Slow_Queries",$mysqlsq_val);
						}
					}
				}
				$minmaxavg{DAY}{"1Queries"}{AVG} /= $minmaxavg{DAY}{"1Queries"}{CNT};
				$minmaxavg{DAY}{"2Slow_Queries"}{AVG} /= $minmaxavg{DAY}{"2Slow_Queries"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Queries',
					x_label_skip => 60,
					title => 'MySQL Queries in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Queries Slow_Queries));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqlqueries") {
				my (@h,@p,@t);
				my $mysqlq_prev;
				my $mysqlsq_prev;
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mysqlq_avg;
					my $mysqlsq_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $mysqlq eq "") {
							$mysqlq_prev = 0;
							$mysqlsq_prev = 0;
						} else {
							if ($mysqlq_prev < $mysqlq or $mysqlq eq "") {
								$mysqlq_prev = $mysqlq;
							} else {
								my $mysqlq_val = ($mysqlq_prev - $mysqlq);
								$mysqlq_avg = $mysqlq_avg + $mysqlq_val;
								$mysqlq_prev = $mysqlq;
							}
							if ($mysqlsq_prev < $mysqlsq or $mysqlsq eq "") {
								$mysqlsq_prev = $mysqlsq;
							} else {
								my $mysqlsq_val = ($mysqlsq_prev - $mysqlsq);
								$mysqlsq_avg = $mysqlsq_avg + $mysqlsq_val;
								$mysqlsq_prev = $mysqlsq;
							}
						}
					}
					if ($mysqlq_avg == 0) {
						push @p,undef;
					} else {
						push @p,($mysqlq_avg/60);
						&minmaxavg("WEEK","1Queries",($mysqlq_avg/60));
					}
					if ($mysqlsq_avg == 0) {
						push @t,undef;
					} else {
						push @t,($mysqlsq_avg/60);
						&minmaxavg("WEEK","2Slow_Queries",($mysqlsq_avg/60));
					}
				}
				if ($minmaxavg{WEEK}{"1Queries"}{CNT} > 0) {$minmaxavg{WEEK}{"1Queries"}{AVG} /= $minmaxavg{WEEK}{"1Queries"}{CNT}}
				if ($minmaxavg{WEEK}{"2Slow_Queries"}{CNT} > 0) {$minmaxavg{WEEK}{"2Slow_Queries"}{AVG} /= $minmaxavg{WEEK}{"2Slow_Queries"}{CNT}}
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Queries',
					x_label_skip => 24,
					title => 'MySQL Queries in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Queries Slow_Queries));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqlqueries") {
				my (@h,@p,@t);
				my $mysqlq_prev;
				my $mysqlsq_prev;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mysqlq_avg;
					my $mysqlsq_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $mysqlq eq "") {
							$mysqlq_prev = 0;
							$mysqlsq_prev = 0;
						} else {
							if ($mysqlq_prev < $mysqlq or $mysqlq eq "") {
								$mysqlq_prev = $mysqlq;
							} else {
								my $mysqlq_val = ($mysqlq_prev - $mysqlq);
								$mysqlq_avg = $mysqlq_avg + $mysqlq_val;
								$mysqlq_prev = $mysqlq;
							}
							if ($mysqlsq_prev < $mysqlsq or $mysqlsq eq "") {
								$mysqlsq_prev = $mysqlsq;
							} else {
								my $mysqlsq_val = ($mysqlsq_prev - $mysqlsq);
								$mysqlsq_avg = $mysqlsq_avg + $mysqlsq_val;
								$mysqlsq_prev = $mysqlsq;
							}
						}
					}
					if ($mysqlq_avg == 0) {
						push @p,undef;
					} else {
						push @p,($mysqlq_avg/60);
						&minmaxavg("MONTH","1Queries",($mysqlq_avg/60));
					}
					if ($mysqlsq_avg == 0) {
						push @t,undef;
					} else {
						push @t,($mysqlsq_avg/60);
						&minmaxavg("MONTH","2Slow_Queries",($mysqlsq_avg/60));
					}
				}
				if ($minmaxavg{MONTH}{"1Queries"}{CNT} > 0) {$minmaxavg{MONTH}{"1Queries"}{AVG} /= $minmaxavg{MONTH}{"1Queries"}{CNT}}
				if ($minmaxavg{MONTH}{"2Slow_Queries"}{CNT} > 0) {$minmaxavg{MONTH}{"2Slow_Queries"}{AVG} /= $minmaxavg{MONTH}{"2Slow_Queries"}{CNT}}
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Queries',
					x_label_skip => 24,
					title => "MySQL Queries in last $config{ST_SYSTEM_MAXDAYS}",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Queries Slow_Queries));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqlconns") {
				my (@h,@p,@t);
				my $mysqlcn_prev;
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mysqlq eq "") {
						$mysqlcn_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($mysqlcn_prev < $mysqlcn or $mysqlcn eq "") {
							push @p,undef;
							$mysqlcn_prev = $mysqlcn;
						} else {
							my $mysqlcn_val = ($mysqlcn_prev - $mysqlcn);
							push @p,$mysqlcn_val;
							$mysqlcn_prev = $mysqlcn;
							&minmaxavg("HOUR","1Connections",$mysqlcn_val);
						}
						if ($mysqlth eq "") {
							push @t,undef;
						} else {
							push @t,$mysqlth;
							&minmaxavg("HOUR","2Threads",$mysqlth);
						}
					}
				}
				$minmaxavg{HOUR}{"1Connections"}{AVG} /= $minmaxavg{HOUR}{"1Connections"}{CNT};
				$minmaxavg{HOUR}{"2Threads"}{AVG} /= $minmaxavg{HOUR}{"2Threads"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => '',
					x_label_skip => 3,
					title => 'MySQL Connections & Threads in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections Threads));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqlconns") {
				my (@h,@p,@t);
				my $mysqlcn_prev;
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $mysqlq eq "") {
						$mysqlcn_prev = 0;
						push @p,undef;
						push @t,undef;
					} else {
						if ($mysqlcn_prev < $mysqlcn or $mysqlcn eq "") {
							push @p,undef;
							$mysqlcn_prev = $mysqlcn;
						} else {
							my $mysqlcn_val = ($mysqlcn_prev - $mysqlcn);
							push @p,$mysqlcn_val;
							$mysqlcn_prev = $mysqlcn;
							&minmaxavg("DAY","1Connections",$mysqlcn_val);
						}
						if ($mysqlth eq "") {
							push @t,undef;
						} else {
							push @t,$mysqlth;
							&minmaxavg("DAY","2Threads",$mysqlth);
						}
					}
				}
				$minmaxavg{DAY}{"1Connections"}{AVG} /= $minmaxavg{DAY}{"1Connections"}{CNT};
				$minmaxavg{DAY}{"2Threads"}{AVG} /= $minmaxavg{DAY}{"2Threads"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => '',
					x_label_skip => 60,
					title => 'MySQL Connections & Threads in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections Threads));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqlconns") {
				my (@h,@p,@t);
				my $mysqlcn_prev;
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mysqlcn_avg;
					my $mysqlth_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $mysqlq eq "") {
							$mysqlcn_prev = 0;
						} else {
							if ($mysqlcn_prev < $mysqlcn or $mysqlcn eq "") {
								$mysqlcn_prev = $mysqlcn;
							} else {
								my $mysqlcn_val = ($mysqlcn_prev - $mysqlcn);
								$mysqlcn_avg = $mysqlcn_avg + $mysqlcn_val;
								$mysqlcn_prev = $mysqlcn;
							}
							$mysqlth_avg = $mysqlth_avg + $mysqlth;
						}
					}
					if ($mysqlcn_avg == 0) {
						push @p,undef;
					} else {
						push @p,($mysqlcn_avg/60);
						&minmaxavg("WEEK","1Connections",($mysqlcn_avg/60));
					}
					if ($mysqlth_avg == 0) {
						push @t,undef;
					} else {
						push @t,($mysqlth_avg/60);
						&minmaxavg("WEEK","2Threads",($mysqlth_avg/60));
					}
				}
				if ($minmaxavg{WEEK}{"1Connections"}{CNT} > 0) {$minmaxavg{WEEK}{"1Connections"}{AVG} /= $minmaxavg{WEEK}{"1Connections"}{CNT}}
				if ($minmaxavg{WEEK}{"2Threads"}{CNT} > 0) {$minmaxavg{WEEK}{"2Threads"}{AVG} /= $minmaxavg{WEEK}{"2Threads"}{CNT}}
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => '',
					x_label_skip => 24,
					title => 'MySQL Connections & Threads in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections Threads));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "mysqlconns") {
				my (@h,@p,@t);
				my $mysqlcn_prev;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $mysqlcn_avg;
					my $mysqlth_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $mysqlq eq "") {
							$mysqlcn_prev = 0;
						} else {
							if ($mysqlcn_prev < $mysqlcn or $mysqlcn eq "") {
								$mysqlcn_prev = $mysqlcn;
							} else {
								my $mysqlcn_val = ($mysqlcn_prev - $mysqlcn);
								$mysqlcn_avg = $mysqlcn_avg + $mysqlcn_val;
								$mysqlcn_prev = $mysqlcn;
							}
							$mysqlth_avg = $mysqlth_avg + $mysqlth;
						}
					}
					if ($mysqlcn_avg == 0) {
						push @p,undef;
					} else {
						push @p,($mysqlcn_avg/60);
						&minmaxavg("MONTH","1Connections",($mysqlcn_avg/60));
					}
					if ($mysqlth_avg == 0) {
						push @t,undef;
					} else {
						push @t,($mysqlth_avg/60);
						&minmaxavg("MONTH","2Threads",($mysqlth_avg/60));
					}
				}
				if ($minmaxavg{MONTH}{"1Connections"}{CNT} > 0) {$minmaxavg{MONTH}{"1Connections"}{AVG} /= $minmaxavg{MONTH}{"1Connections"}{CNT}}
				if ($minmaxavg{MONTH}{"2Threads"}{CNT} > 0) {$minmaxavg{MONTH}{"2Threads"}{AVG} /= $minmaxavg{MONTH}{"2Threads"}{CNT}}
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => '',
					x_label_skip => 24,
					title => "MySQL Connections & Threads in last $config{ST_SYSTEM_MAXDAYS} days",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections Threads));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
			
			if ($type eq "apachecpu") {
				my (@h,@p);
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $apachecpu eq "") {
						push @p,undef;
					} else {
						push @p,$apachecpu*100;

						&minmaxavg("HOUR","1Apache_CPU",$apachecpu*100);
					}
				}
				$minmaxavg{HOUR}{"1Apache_CPU"}{AVG} /= $minmaxavg{HOUR}{"1Apache_CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Percentage',
					x_label_skip => 3,
					title => 'Apache CPU Usage in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Apache CPU");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apachecpu") {
				my (@h,@p);
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $apachecpu eq "") {
						push @p,undef;
					} else {
						push @p,$apachecpu*100;

						&minmaxavg("DAY","1Apache_CPU",$apachecpu*100);
					}
				}
				$minmaxavg{DAY}{"1Apache_CPU"}{AVG} /= $minmaxavg{DAY}{"1Apache_CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Percentage',
					x_label_skip => 60,
					title => 'Apache CPU Usage in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Apache CPU");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apachecpu") {
				my (@h,@p);
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $apachecpu_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $apachecpu ne "") {
							$apachecpu_avg += $apachecpu*100;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
					} else {
						push @p,$apachecpu_avg/$cnt_avg;

						&minmaxavg("WEEK","1Apache_CPU",($apachecpu_avg/$cnt_avg));
					}
				}
				$minmaxavg{WEEK}{"1Apache_CPU"}{AVG} /= $minmaxavg{WEEK}{"1Apache_CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Percentage',
					x_label_skip => 24,
					title => 'Apache CPU Usage in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Apache CPU");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apachecpu") {
				my (@h,@p);
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $apachecpu_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $apachecpu ne "") {
							$apachecpu_avg += $apachecpu*100;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
					} else {
						push @p,$apachecpu_avg/$cnt_avg;

						&minmaxavg("MONTH","1Apache_CPU",($apachecpu_avg/$cnt_avg));
					}
				}
				$minmaxavg{MONTH}{"1Apache_CPU"}{AVG} /= $minmaxavg{MONTH}{"1Apache_CPU"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Percentage',
					x_label_skip => 24,
					title => "Apache CPU Usage in last $config{ST_SYSTEM_MAXDAYS}",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend("Apache CPU");
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
			
			if ($type eq "apacheconn") {
				my (@h,@p);
				my $apacheacc_prev;
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $apacheacc eq "") {
						$apacheacc_prev = 0;
						push @p,undef;
					} else {
						if ($apacheacc_prev < $apacheacc or $apacheacc eq "") {
							push @p,undef;
							$apacheacc_prev = $apacheacc;
						} else {
							my $apacheacc_val = ($apacheacc_prev - $apacheacc);
							push @p,$apacheacc_val;
							$apacheacc_prev = $apacheacc;
							&minmaxavg("HOUR","1Connections",$apacheacc_val);
						}
					}
				}
				$minmaxavg{HOUR}{"1Connections"}{AVG} /= $minmaxavg{HOUR}{"1Connections"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => '',
					x_label_skip => 3,
					title => 'Apache Connections in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apacheconn") {
				my (@h,@p,@t);
				my $apacheacc_prev;
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $apacheacc eq "") {
						$apacheacc_prev = 0;
						push @p,undef;
					} else {
						if ($apacheacc_prev < $apacheacc or $apacheacc eq "") {
							push @p,undef;
							$apacheacc_prev = $apacheacc;
						} else {
							my $apacheacc_val = ($apacheacc_prev - $apacheacc);
							push @p,$apacheacc_val;
							$apacheacc_prev = $apacheacc;
							&minmaxavg("DAY","1Connections",$apacheacc_val);
						}
					}
				}
				$minmaxavg{DAY}{"1Connections"}{AVG} /= $minmaxavg{DAY}{"1Connections"}{CNT};
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => '',
					x_label_skip => 60,
					title => 'Apache Connections in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apacheconn") {
				my (@h,@p,@t);
				my $apacheacc_prev;
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $apacheacc_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $apacheacc eq "") {
							$apacheacc_prev = 0;
						} else {
							if ($apacheacc_prev < $apacheacc or $apacheacc eq "") {
								$apacheacc_prev = $apacheacc;
							} else {
								my $apacheacc_val = ($apacheacc_prev - $apacheacc);
								$apacheacc_avg = $apacheacc_avg + $apacheacc_val;
								$apacheacc_prev = $apacheacc;
							}
						}
					}
					if ($apacheacc_avg == 0) {
						push @p,undef;
					} else {
						push @p,($apacheacc_avg/60);
						&minmaxavg("WEEK","1Connections",($apacheacc_avg/60));
					}
				}
				if ($minmaxavg{WEEK}{"1Connections"}{CNT} > 0) {$minmaxavg{WEEK}{"1Connections"}{AVG} /= $minmaxavg{WEEK}{"1Connections"}{CNT}}
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => '',
					x_label_skip => 24,
					title => 'Apache Connections in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections Threads));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apacheconn") {
				my (@h,@p,@t);
				my $apacheacc_prev;
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $apacheacc_avg;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time eq "" or $apacheacc eq "") {
							$apacheacc_prev = 0;
						} else {
							if ($apacheacc_prev < $apacheacc or $apacheacc eq "") {
								$apacheacc_prev = $apacheacc;
							} else {
								my $apacheacc_val = ($apacheacc_prev - $apacheacc);
								$apacheacc_avg = $apacheacc_avg + $apacheacc_val;
								$apacheacc_prev = $apacheacc;
							}
						}
					}
					if ($apacheacc_avg == 0) {
						push @p,undef;
					} else {
						push @p,($apacheacc_avg/60);
						&minmaxavg("MONTH","1Connections",($apacheacc_avg/60));
					}
				}
				if ($minmaxavg{MONTH}{"1Connections"}{CNT} > 0) {$minmaxavg{MONTH}{"1Connections"}{AVG} /= $minmaxavg{MONTH}{"1Connections"}{CNT}}
				my @data = ([reverse @h],[reverse @p]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => '',
					x_label_skip => 24,
					title => "Apache Connections in last $config{ST_SYSTEM_MAXDAYS}",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Connections Threads));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
			
			if ($type eq "apachework") {
				my (@h,@p,@t);
				for (my $mins = 0; $mins < 60;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$min;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $apachebwork eq "") {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$apachebwork;
						push @t,$apacheiwork;

						&minmaxavg("HOUR","1Busy",$apachebwork);
						&minmaxavg("HOUR","2Idle",$apacheiwork);
					}
				}
				$minmaxavg{HOUR}{"1Busy"}{AVG} /= $minmaxavg{HOUR}{"1Busy"}{CNT};
				$minmaxavg{HOUR}{"2Idle"}{AVG} /= $minmaxavg{HOUR}{"2Idle"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Minute',
					y_label => 'Workers',
					x_label_skip => 3,
					title => 'Apache Workers in last hour',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Busy Idle));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemhour.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apachework") {
				my (@h,@p,@t);
				for (my $mins = 0; $mins < 1440;$mins++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($mins * 60));
					push @h,$hour;
					my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$min});
					if ($time eq "" or $apachebwork eq "") {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$apachebwork;
						push @t,$apacheiwork;

						&minmaxavg("DAY","1Busy",$apachebwork);
						&minmaxavg("DAY","2Idle",$apacheiwork);
					}
				}
				$minmaxavg{DAY}{"1Busy"}{AVG} /= $minmaxavg{DAY}{"1Busy"}{CNT};
				$minmaxavg{DAY}{"2Idle"}{AVG} /= $minmaxavg{DAY}{"2Idle"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred purple) ] );
				$hour_graph->set(
					x_label => 'Hour',
					y_label => 'Workers',
					x_label_skip => 60,
					title => 'Apache Workers in last 24 hours',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Busy Idle));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemday.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apachework") {
				my (@h,@p,@t);
				for (my $hours = 0; $hours < 168;$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $apachebwork_avg;
					my $apacheiwork_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $apachebwork ne "") {
							$apachebwork_avg += $apachebwork;
							$apacheiwork_avg += $apacheiwork;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$apachebwork_avg/$cnt_avg;
						push @t,$apacheiwork_avg/$cnt_avg;

						&minmaxavg("WEEK","1Busy",($apachebwork_avg/$cnt_avg));
						&minmaxavg("WEEK","2Idle",($apacheiwork_avg/$cnt_avg));
					}
				}
				$minmaxavg{WEEK}{"1Busy"}{AVG} /= $minmaxavg{WEEK}{"1Busy"}{CNT};
				$minmaxavg{WEEK}{"2Idle"}{AVG} /= $minmaxavg{WEEK}{"2Idle"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Workers',
					x_label_skip => 24,
					title => 'Apache Workers in last 7 days',
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Busy Idle));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemweek.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}

			if ($type eq "apachework") {
				my (@h,@p,@t);
				for (my $hours = 0; $hours < (24 * $config{ST_SYSTEM_MAXDAYS});$hours++) {
					($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time - ($hours * 60 * 60));
					push @h,$mday;
					my $apachebwork_avg;
					my $apacheiwork_avg;
					my $cnt_avg = 0;
					for ($mins = 59; $mins >= 0;$mins--) {
						my ($time,$cputotal,$cpuidle,$cpuiowait,$memtotal,$memfree,$memswaptotal,$memswapfree,$load1,$load5,$load15,$netin,$netout,$diskread,$diskwrite,$mailin,$mailout,$cputemp,$mysqlin,$mysqlout,$mysqlq,$mysqlsq,$mysqlcn,$mysqlth,$apachecpu,$apacheacc,$apachebwork,$apacheiwork) = split(/\,/,$stata{$year}{$mon}{$mday}{$hour}{$mins});
						if ($time and $apachebwork ne "") {
							$apachebwork_avg += $apachebwork;
							$apacheiwork_avg += $apacheiwork;
							$cnt_avg++;
						}
					}
					if ($cnt_avg == 0) {
						push @p,undef;
						push @t,undef;
					} else {
						push @p,$apachebwork_avg/$cnt_avg;
						push @t,$apacheiwork_avg/$cnt_avg;

						&minmaxavg("MONTH","1Busy",($apachebwork_avg/$cnt_avg));
						&minmaxavg("MONTH","2Idle",($apacheiwork_avg/$cnt_avg));
					}
				}
				$minmaxavg{MONTH}{"1Busy"}{AVG} /= $minmaxavg{MONTH}{"1Busy"}{CNT};
				$minmaxavg{MONTH}{"2Idle"}{AVG} /= $minmaxavg{MONTH}{"2Idle"}{CNT};
				my @data = ([reverse @h],[reverse @p],[reverse @t]);
				my $hour_graph = GD::Graph::lines->new(750,350);
				$hour_graph->set( dclrs => [ qw(yellow dred) ] );
				$hour_graph->set(
					x_label => 'Day (Hourly Average)',
					y_label => 'Workers',
					x_label_skip => 24,
					title => "Apache Workers in last $config{ST_SYSTEM_MAXDAYS}",
					borderclrs => $hour_graph->{dclrs},
					transparent => 0,
				);
				$hour_graph->set_legend( qw(Busy Idle));
				$hour_graph->plot(\@data);
				$img = $imghddir."lfd_systemmonth.gif";
				open(OUT, ">$img");
				binmode OUT;
				print OUT $hour_graph->gd->gif();
				close OUT;
			}
		};
		print "<div align='center'><form action='$script' method='post'><input type='hidden' name='action' value='systemstats'><select name='graph'>\n";
		my $selected;
		if ($type eq "" or $type eq "load") {$selected = "selected"} else {$selected = ""}
		print "<option value='load' $selected>Load Average Statistics</option>\n";
		if ($type eq "cpu") {$selected = "selected"} else {$selected = ""}
		print "<option value='cpu' $selected>CPU Statistics</option>\n";
		if ($type eq "mem") {$selected = "selected"} else {$selected = ""}
		print "<option value='mem' $selected>Memory Statistics</option>\n";
		if ($type eq "net") {$selected = "selected"} else {$selected = ""}
		print "<option value='net' $selected>Network Statistics</option>\n";
		if (-e "/proc/diskstats") {
			if ($type eq "disk") {$selected = "selected"} else {$selected = ""}
			print "<option value='disk' $selected>Disk Statistics</option>\n";
		}
		if (-e "/etc/csf/stats/email") {
			if ($type eq "email") {$selected = "selected"} else {$selected = ""}
			print "<option value='email' $selected>Email Statistics</option>\n";
		}
		if (-e "/sys/devices/platform/coretemp.0/temp1_input") {
			if ($type eq "temp") {$selected = "selected"} else {$selected = ""}
			print "<option value='temp' $selected>CPU Temperature</option>\n";
		}
		if ($config{ST_MYSQL}) {
			if ($type eq "mysqldata") {$selected = "selected"} else {$selected = ""}
			print "<option value='mysqldata' $selected>MySQL Data</option>\n";
			if ($type eq "mysqlqueries") {$selected = "selected"} else {$selected = ""}
			print "<option value='mysqlqueries' $selected>MySQL Queries</option>\n";
			if ($type eq "mysqlconns") {$selected = "selected"} else {$selected = ""}
			print "<option value='mysqlconns' $selected>MySQL Connections</option>\n";
		}
		if ($config{ST_APACHE}) {
			if ($type eq "apachecpu") {$selected = "selected"} else {$selected = ""}
			print "<option value='apachecpu' $selected>Apache CPU Usage</option>\n";
			if ($type eq "apacheconn") {$selected = "selected"} else {$selected = ""}
			print "<option value='apacheconn' $selected>Apache Connections</option>\n";
			if ($type eq "apachework") {$selected = "selected"} else {$selected = ""}
			print "<option value='apachework' $selected>Apache Workers</option>\n";
		}
		print "</select><input type='submit' value='Select Graphs'></form></div><br />\n";
		if ($@) {
			print "<table style='border: 2px #990000 solid' align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF'>\n";
			print "<tr><td align='center'>There was a problem generating these graphs. Try leaving the statistics collection running for an hour before viewing these again</td></tr></table>\n";
		} else {
			print "<table style='border: 2px #990000 solid' align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF'>\n";
			print "<tr><td style='border-bottom: 2px #990000 solid'>\n";
			print "<p align='center'><img src='".$imgdir."lfd_systemhour.gif?text=".time."'><br><table border='0' align='center'>\n";
			foreach my $key (sort keys %{$minmaxavg{HOUR}}) {
				my $item = $key;
				if ($key =~ /^\d(.*)$/) {$item = $1}
				print "<tr><td><b>$item</b></td>";
				print "<td>Min:<b>".sprintf("%.2f",$minmaxavg{HOUR}{$key}{MIN})."</b></td>";
				print "<td>Max:<b>".sprintf("%.2f",$minmaxavg{HOUR}{$key}{MAX})."</b></td>";
				print "<td>Avg:<b>".sprintf("%.2f",$minmaxavg{HOUR}{$key}{AVG})."</b></td></tr>\n";
			}
			print "</table></p>Note: This graph displays per minute statistics unless otherwise stated</td></tr><tr><td style='border-bottom: 2px #990000 solid'>\n";
			print "<p align='center'><img src='".$imgdir."lfd_systemday.gif?text=".time."'><br><table border='0' align='center'>\n";
			foreach my $key (sort keys %{$minmaxavg{DAY}}) {
				my $item = $key;
				if ($key =~ /^\d(.*)$/) {$item = $1}
				print "<tr><td><b>$item</b></td>";
				print "<td>Min:<b>".sprintf("%.2f",$minmaxavg{DAY}{$key}{MIN})."</b></td>";
				print "<td>Max:<b>".sprintf("%.2f",$minmaxavg{DAY}{$key}{MAX})."</b></td>";
				print "<td>Avg:<b>".sprintf("%.2f",$minmaxavg{DAY}{$key}{AVG})."</b></td></tr>\n";
			}
			print "</table></p>Note: This graph displays per minute statistics unless otherwise stated</td></tr><tr><td style='border-bottom: 2px #990000 solid'>\n";
			print "<p align='center'><img src='".$imgdir."lfd_systemweek.gif?text=".time."'><br><table border='0' align='center'>\n";
			foreach my $key (sort keys %{$minmaxavg{WEEK}}) {
				my $item = $key;
				if ($key =~ /^\d(.*)$/) {$item = $1}
				print "<tr><td><b>$item</b></td>";
				print "<td>Min:<b>".sprintf("%.2f",$minmaxavg{WEEK}{$key}{MIN})."</b></td>";
				print "<td>Max:<b>".sprintf("%.2f",$minmaxavg{WEEK}{$key}{MAX})."</b></td>";
				print "<td>Avg:<b>".sprintf("%.2f",$minmaxavg{WEEK}{$key}{AVG})."</b></td></tr>\n";
			}
			print "</table></p>Note: This graph displays an hourly average of the per minute statistics, so you will not see the peak minute values</td></tr><tr><td>\n";
			print "<p align='center'><img src='".$imgdir."lfd_systemmonth.gif?text=".time."'><br><table border='0' align='center'>\n";
			foreach my $key (sort keys %{$minmaxavg{MONTH}}) {
				my $item = $key;
				if ($key =~ /^\d(.*)$/) {$item = $1}
				print "<tr><td><b>$item</b></td>";
				print "<td>Min:<b>".sprintf("%.2f",$minmaxavg{MONTH}{$key}{MIN})."</b></td>";
				print "<td>Max:<b>".sprintf("%.2f",$minmaxavg{MONTH}{$key}{MAX})."</b></td>";
				print "<td>Avg:<b>".sprintf("%.2f",$minmaxavg{MONTH}{$key}{AVG})."</b></td></tr>\n";
			}
			print "</table></p>Note: This graph displays an hourly average of the per minute statistics, so you will not see the peak minute values</td></tr></table>\n";
			unless ($config{ST_MYSQL} and $config{ST_APACHE}) {
				print "<br>\n<table style='border: 2px #990000 solid' align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF'>\n";
				print "<tr><td align='center'>You may be able to collect more statistics by enabling ST_MYSQL or ST_APACHE in the csf configuration</td></tr></table>\n";
			}
		}
	} else {
		print "<table style='border: 2px #990000 solid' align='center' border='0' cellspacing='0' cellpadding='4' bgcolor='#FFFFFF'>\n";
		print "<tr><td align='center'>No statistical data has been collected yet</td></tr></table>\n";
	}
	print "<p align='center'><form action='$script' method='post'><input type='submit' value='Return'></form></p>\n";
}
# end systemstats
###############################################################################
# start minmaxavg
sub minmaxavg {
	my $graph = shift;
	my $name = shift;
	my $value = shift;

	unless (defined $minmaxavg{$graph}{$name}{MIN}) {$minmaxavg{$graph}{$name}{MIN} = $value}
	unless (defined $minmaxavg{$graph}{$name}{MAX}) {$minmaxavg{$graph}{$name}{MAX} = $value}
	if ($minmaxavg{$graph}{$name}{MIN} > $value) {$minmaxavg{$graph}{$name}{MIN} = $value}
	if ($minmaxavg{$graph}{$name}{MAX} < $value) {$minmaxavg{$graph}{$name}{MAX} = $value}
	$minmaxavg{$graph}{$name}{AVG} += $value;
	$minmaxavg{$graph}{$name}{CNT}++;
}
# end minmaxavg
###############################################################################

###############################################################################
# start urlget (v1.3)
#
# Examples:
#my ($status, $text) = &urlget("http://prdownloads.sourceforge.net/clamav/clamav-0.92.tar.gz","/tmp/clam.tgz");
#if ($status) {print "Oops: $text\n"}
#
#my ($status, $text) = &urlget("http://www.configserver.com/free/msfeversion.txt");
#if ($status) {print "Oops: $text\n"} else {print "Version: $text\n"}
#
sub urlget {
	my $url = shift;
	my $file = shift;
	my $status = 0;
	my $timeout = 1200;

	use LWP::UserAgent;
	my $ua = LWP::UserAgent->new;
	$ua->timeout(30);
	my $req = HTTP::Request->new(GET => $url);
	my $res;
	my $text;

	($status, $text) = eval {
		local $SIG{__DIE__} = undef;
		local $SIG{'ALRM'} = sub {die "Download timeout after $timeout seconds"};
		alarm($timeout);
		if ($file) {
			$|=1;
			my $expected_length;
			my $bytes_received = 0;
			my $per = 0;
			my $oldper = 0;
			open (OUT, ">$file\.tmp") or return (1, "Unable to open $file\.tmp: $!");
			binmode (OUT);
			print "...0\%\n";
			$res = $ua->request($req,
				sub {
				my($chunk, $res) = @_;
				$bytes_received += length($chunk);
				unless (defined $expected_length) {$expected_length = $res->content_length || 0}
				if ($expected_length) {
					my $per = int(100 * $bytes_received / $expected_length);
					if ((int($per / 5) == $per / 5) and ($per != $oldper)) {
						print "...$per\%\n";
						$oldper = $per;
					}
				} else {
					print ".";
				}
				print OUT $chunk;
			});
			close (OUT);
			print "\n";
		} else {
			$res = $ua->request($req);
		}
		alarm(0);
		if ($res->is_success) {
			if ($file) {
				rename ("$file\.tmp","$file") or return (1, "Unable to rename $file\.tmp to $file: $!");
				return (0, $file);
			} else {
				return (0, $res->content);
			}
		} else {
			return (1, "Unable to download: ".$res->message);
		}
	};
	alarm(0);
	if ($@) {return (1, $@)}
	return ($status,$text);
}
# end urlget
###############################################################################

1;
