<?
/* $Id$ */
/*
	mail_reports.inc
	Part of pfSense
	Copyright (C) 2011 Jim Pingle <jimp@pfsense.org>
	Portions Copyright (C) 2007-2011 Seth Mos <seth.mos@dds.nl>
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.
*/

require_once("globals.inc");
require_once("config.inc");
require_once("filter.inc");
require_once("rrd.inc");

$graph_length = array(
	"eighthour" => 28800,
	"day" => 86400,
	"week" => 604800,
	"month" => 2764800,
	"quarter" => 8035200,
	"year" => 31622400,
	"fouryear" => 126489600);

$logfile_friendly = array(
	"dhcpd"      => "DHCP",
	"filter"     => "Firewall (raw)",
	"gateways"   => "Gateway Events",
	"installer"  => "Installation",
	"ipsec"      => "IPsec VPN",
	"l2tps"      => "L2TP Server (raw)",
	"lighttpd"   => "Web Server (lighttpd)",
	"ntpd"       => "NTP",
	"openvpn"    => "OpenVPN",
	"poes"       => "PPPoE Server (raw)",
	"portalauth" => "Captive Portal Authentication",
	"ppp"        => "PPP",
	"pptps"      => "PPTP Server (raw)",
	"relayd"     => "Load Balancer (relayd)",
	"resolver"   => "DNS Resolver",
	"routing"    => "Routing",
	"system"     => "System",
	"vpn"        => "PPTP/L2TP/PPPoE Server Login Events",
	"wireless"   => "Wireless"
);

function get_dates($curperiod, $graph) {
	global $graph_length;
	$now = time();
	$end = $now;

	if($curperiod == "absolute") {
		$start = $end - $graph_length[$graph];
	} else {
		$curyear = date('Y', $now);
		$curmonth = date('m', $now);
		$curweek = date('W', $now);
		$curweekday = date('N', $now) - 1; // We want to start on monday
		$curday = date('d', $now);
		$curhour = date('G', $now);

		switch($curperiod) {
			case "previous":
				$offset = -1;
				break;
			default:
				$offset = 0;
		}
		switch($graph) {
			case "eighthour":
			case "8hour":
				if($curhour < 24)
					$starthour = 16;
				if($curhour < 16)
					$starthour = 8;
				if($curhour < 8)
					$starthour = 0;

				switch($offset) {
					case 0:
						$houroffset = $starthour;
						break;
					default:
						$houroffset = $starthour + ($offset * 8);
						break;
				}
				$start = mktime($houroffset, 0, 0, $curmonth, $curday, $curyear);
				if($offset != 0) {
					$end = mktime(($houroffset + 8), 0, 0, $curmonth, $curday, $curyear);
				}
				break;
			case "day":
				$start = mktime(0, 0, 0, $curmonth, ($curday + $offset), $curyear);
				if($offset != 0)
					$end = mktime(0, 0, 0, $curmonth, (($curday + $offset) + 1), $curyear);
				break;
			case "week":
				switch($offset) {
					case 0:
						$weekoffset = 0;
						break;
					default:
						$weekoffset = ($offset * 7) - 7;
						break;
				}
				$start = mktime(0, 0, 0, $curmonth, (($curday - $curweekday) + $weekoffset), $curyear);
				if($offset != 0)
					$end = mktime(0, 0, 0, $curmonth, (($curday - $curweekday) + $weekoffset + 7), $curyear);
				break;
			case "month":
				$start = mktime(0, 0, 0, ($curmonth + $offset), 0, $curyear);
				if($offset != 0)
					$end = mktime(0, 0, 0, (($curmonth + $offset) + 1), 0, $curyear);
				break;
			case "quarter":
				$start = mktime(0, 0, 0, (($curmonth - 2) + $offset), 0, $curyear);
				if($offset != 0)
					$end = mktime(0, 0, 0, (($curmonth + $offset) + 1), 0, $curyear);
				break;
			case "year":
				$start = mktime(0, 0, 0, 1, 0, ($curyear + $offset));
				if($offset != 0)
					$end = mktime(0, 0, 0, 1, 0, (($curyear + $offset) +1));
				break;
			case "fouryear":
			case "4year":
				$start = mktime(0, 0, 0, 1, 0, (($curyear - 3) + $offset));
				if($offset != 0)
					$end = mktime(0, 0, 0, 1, 0, (($curyear + $offset) +1));
				break;
		}
	}
	// echo "start $start ". date('l jS \of F Y h:i:s A', $start) .", end $end ". date('l jS \of F Y h:i:s A', $end) ."<br>";
	$dates = array();
	$dates['start'] = $start;
	$dates['end'] = $end;
	return $dates;
}

function set_mail_report_cron_jobs($a_mailreports) {
	global $config, $g;

	if(!$config['cron']['item'])
		$config['cron']['item'] = array();

	// Search for old report cron jobs and remove them all
	for ($x=0, $numjobs=sizeof($config['cron']['item']); $x < $numjobs; $x++) {
		if(strpos($config['cron']['item'][$x]['command'], "mail_reports_generate.php") !== FALSE) {
			unset($config['cron']['item'][$x]);
		}
	}

	// Add new cron jobs
	foreach($a_mailreports as $id => $report) {
		$cron_item = array();
		$cron_item['minute'] = 0;
		$cron_item['hour'] = isset($report['timeofday']) ? $report['timeofday'] : 0;
		$cron_item['mday'] = isset($report['dayofmonth']) ? $report['dayofmonth'] : "*";
		$cron_item['month'] = isset($report['monthofyear']) ? $report['monthofyear'] : "*";;
		$cron_item['wday'] = isset($report['dayofweek']) ? $report['dayofweek'] : "*";
		$cron_item['who'] = "root";
		$cron_item['command'] = "/usr/local/bin/mail_reports_generate.php {$id} &";
		$config['cron']['item'][] = $cron_item;
	}
}

include('phpmailer/PHPMailerAutoload.php');

function mail_report_send($headertext, $cmdtext, $logtext, $attachments) {
	global $config, $g;

	if (empty($config['notifications']['smtp']['ipaddress']))
		return;

	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->Host = $config['notifications']['smtp']['ipaddress'];
	$mail->Port = empty($config['notifications']['smtp']['port']) ? 25 : $config['notifications']['smtp']['port'];

	if ((isset($config['notifications']['smtp']['ssl']) && $config['notifications']['smtp']['ssl'] != "unchecked") || $config['notifications']['smtp']['ssl'] == "checked")
		$mail->SMTPSecure =  "ssl";

	if ((isset($config['notifications']['smtp']['tls']) && $config['notifications']['smtp']['tls'] != "unchecked") || $config['notifications']['smtp']['tls'] == "checked")
		$mail->SMTPSecure =  "tls";

	if($config['notifications']['smtp']['username'] &&
	   $config['notifications']['smtp']['password']) {
		$mail->SMTPAuth	= true;
		$mail->Username	= $config['notifications']['smtp']['username'];
		$mail->Password	= $config['notifications']['smtp']['password'];
	}

	$mail->ContentType = 'text/html';
	$mail->IsHTML(true);
	$mail->AddReplyTo($config['notifications']['smtp']['fromaddress'], "Firewall Email Report");
	$mail->SetFrom($config['notifications']['smtp']['fromaddress'], "Firewall Email Report");
	$address = $config['notifications']['smtp']['notifyemailaddress'];
	$mail->AddAddress($address, "Report Recipient");
	$mail->Subject = "{$config['system']['hostname']}.{$config['system']['domain']} Email Report: {$headertext}";
	$mail->Body .= "This is a periodic report from your firewall, {$config['system']['hostname']}.{$config['system']['domain']}.<br /><br />Current report: {$headertext}<br />\n<br />\n";
	if (!empty($cmdtext))
		$mail->Body .= $cmdtext;
	if (!empty($logtext))
		$mail->Body .= $logtext;
	if(is_array($attachments)) {
		foreach($attachments as $filename) {
			$shortname = basename($filename);
			$mail->AddEmbeddedImage($filename, $shortname, $shortname);
			$mail->Body .= "<br/><br/>{$shortname}<br/><img src=\"cid:{$shortname}\" />\n";
		}
	}

	if(!$mail->Send()) {
		echo "Mailer Error: " . $mail->ErrorInfo;
	}
}

function mail_report_generate_graph($database, $style, $graph, $start, $end) {
	// Yes, it's ugly, but I didn't want to move code around in includes this late in the 2.0 release cycle.
	require_once("globals.inc");
	require_once("filter.inc");
	require_once("shaper.inc");
	require_once("rrd.inc");
	require_once("util.inc");
	global $g;
	$g['theme'] = get_current_theme();

	$pgtitle = array(gettext("System"),gettext("RRD Graphs"),gettext("Image viewer"));

	if ($database) {
		$curdatabase = basename($database);
	} else {
		$curdatabase = "wan-traffic.rrd";
	}

	if ($style) {
		$curstyle = $style;
	} else {
		$curstyle = "inverse";
	}

	/* this is used for temp name */
	if ($graph) {
		$curgraph = $graph;
	} else {
		$curgraph = "custom";
	}

	$now = time();

	if (is_numeric($start)) {
			if($start < ($now - (3600 * 24 * 365 * 5))) {
					$start = $now - (8 * 3600);
			}
			$start = $start;
	} else {
			$start = $now - (8 * 3600);
	}

	if (is_numeric($end)) {
			$end = $end;
	} else {
			$end = $now;
	}

	/* this should never happen */
	if($end < $start) {
		log_error("start $start is greater than end $end");
			$end = $now;
	}

	$seconds = $end - $start;

	$scales = array();
	$scales[14400] = "MINUTE:5:MINUTE:10:MINUTE:30:0:%H%:%M";
	$scales[57600] = "MINUTE:30:HOUR:1:HOUR:1:0:%H";
	$scales[172800] = "HOUR:1:HOUR:6:HOUR:2:0:%H";
	$scales[691200] = "HOUR:2:HOUR:12:DAY:1:0:%D %d";
	$scales[2764800] = "DAY:1:WEEK:1:WEEK:1:0:Week %W";
	$scales[16070400] = "WEEK:1:MONTH:1:MONTH:1:0:%b";
	$scales[42854400] = "MONTH:1:MONTH:1:MONTH:1:0:%b";

	$archives = array();
	$archives[1] = 1000;
	$archives[5] = 1000;
	$archives[60] = 1000;
	$archives[720] = 3000;

	$defOptions = array(
		'to' => 1,
		'parts' => 1,
		'precision' => 'minute',
		'distance' => FALSE,
		'separator' => ', '
	);

	/* always set the average to the highest value as a fallback */
	$average = 720 * 60;
	foreach($archives as $rra => $value) {
			$archivestart = $end - ($rra * 60 * $value);
			if($archivestart <= $start) {
					$average = $rra * 60;
					break;
			}
	}

	foreach($scales as $scalelength => $value) {
			if($scalelength >= $seconds) {
					$scale = $value;
					break;
			}
	}

	// log_error("start $start, end $end, archivestart $archivestart, average $average, scale $scale, seconds $seconds");

	/* Deduce a interface if possible and use the description */
	$curif = explode("-", $curdatabase);
	$curif[1] = str_replace(".rrd", "", $curif[1]);
	$friendly = convert_friendly_interface_to_friendly_descr(strtolower($curif[0]));
	if(!empty($friendly)) {
		$curif[0] = $friendly;
	}
	$prettydb = ucwords(implode(" :: ", $curif));
	$curif = $curif[0];

	$rrddbpath = "/var/db/rrd/";
	$rrdtmppath = "/tmp/";
	$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
	$uptime = "/usr/bin/uptime";
	$sed = "/usr/bin/sed";

	$havg = timeDiff($average, $defOptions);
	$hperiod = timeDiff($seconds, $defOptions);
	$data = true;

	$rrddbpath = "/var/db/rrd/";
	chdir($rrddbpath);
	$databases = glob("*.rrd");
	rsort($databases);

	/* compare bytes/sec counters, divide bps by 8 */
	read_altq_config();
	if ($altq_list_queues[$curif]) {
		$altq =& $altq_list_queues[$curif];
		switch ($altq->GetBwscale()) {
			case "Gb":
					$factor = 1024 * 1024 * 1024;
			break;
			case "Mb":
					$factor = 1024 * 1024;
			break;
			case "Kb":
					$factor = 1024;
			break;
			case "b":
			default:
					$factor = 1;
			break;
			}
		$upstream = (($altq->GetBandwidth()*$factor)/8);
		$downstream = $upstream; /* XXX: Ugly hack */
		$upif = $curif;
		$downif = "lan"; /* XXX should this be set to something else?! */
	} else {
		$altq = null;
		$downstream = 12500000;
		$upstream = 12500000;
		$upif = "wan";
		$downif = "lan";
	}

	$speedlimit = ($upstream + $downstream);

	/* Set default colors explicitly, the theme can then override them below.
	   This prevents missing colors in themes from crashing the graphs. */
	$colortrafficup = array("666666", "CCCCCC");
	$colortrafficdown = array("990000", "CC0000");
	$colortraffic95 = array("660000", "FF0000");
	$colorpacketsup = array("666666", "CCCCCC");
	$colorpacketsdown = array("990000", "CC0000");
	$colorstates = array('990000','a83c3c','b36666','bd9090','cccccc','000000');
	$colorprocessor = array('990000','a83c3c','b36666','bd9090','cccccc','000000');
	$colormemory = array('990000','a83c3c','b36666','bd9090','cccccc','000000');
	$colormbuf = array('990000','a83c3c','b36666','bd9090','cccccc','000000');
	$colorqueuesup = array('000000','7B0000','990000','BB0000','CC0000','D90000','EE0000','FF0000','CC0000');
	$colorqueuesdown = array('000000','7B7B7B','999999','BBBBBB','CCCCCC','D9D9D9','EEEEEE','FFFFFF','CCCCCC');
	$colorqueuesdropup = array('000000','7B0000','990000','BB0000','CC0000','D90000','EE0000','FF0000','CC0000');
	$colorqueuesdropdown = array('000000','7B7B7B','999999','BBBBBB','CCCCCC','D9D9D9','EEEEEE','FFFFFF','CCCCCC');
	$colorqualityrtt = array('990000','a83c3c','b36666','bd9090','cccccc','000000');
	$colorqualityloss = "ee0000";
	$colorwireless = array('333333','a83c3c','999999');
	$colorspamdtime = array('DDDDFF', 'AAAAFF', 'DDDDFF', '000066');
	$colorspamdconn = array('00AA00BB', 'FFFFFFFF', '00660088', 'FFFFFF88', '006600');
	$colorvpnusers = array('990000');
	$colorcaptiveportalusers = array('990000');

	/* select theme colors if the inclusion file exists */
	$rrdcolors = "{$g['www_path']}/themes/{$g['theme']}/rrdcolors.inc.php";
	if(file_exists($rrdcolors)) {
		include($rrdcolors);
	} else {
		log_error(sprintf(gettext("rrdcolors.inc.php for theme %s does not exist, using defaults!"),$g['theme']));
	}

	switch ($curstyle) {
	case "absolute":
		$multiplier = 1;
		$AREA = "LINE1";
		break;
	default:
		$multiplier = -1;
		$AREA = "AREA";
		break;
	}

	if((strstr($curdatabase, "-traffic.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for traffic stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end --vertical-label \"bits/sec\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:$curif-in_bytes_pass=$rrddbpath$curdatabase:inpass:AVERAGE ";
		$graphcmd .= "DEF:$curif-out_bytes_pass=$rrddbpath$curdatabase:outpass:AVERAGE ";
		$graphcmd .= "DEF:$curif-in_bytes_block=$rrddbpath$curdatabase:inblock:AVERAGE ";
		$graphcmd .= "DEF:$curif-out_bytes_block=$rrddbpath$curdatabase:outblock:AVERAGE ";

		$graphcmd .= "CDEF:\"$curif-in_bits_pass=$curif-in_bytes_pass,8,*\" ";
		$graphcmd .= "CDEF:\"$curif-out_bits_pass=$curif-out_bytes_pass,8,*\" ";
		$graphcmd .= "CDEF:\"$curif-in_bits_block=$curif-in_bytes_block,8,*\" ";
		$graphcmd .= "CDEF:\"$curif-out_bits_block=$curif-out_bytes_block,8,*\" ";

		$graphcmd .= "CDEF:\"$curif-in_bytes=$curif-in_bytes_pass,$curif-in_bytes_block,+\" ";
		$graphcmd .= "CDEF:\"$curif-out_bytes=$curif-out_bytes_pass,$curif-out_bytes_block,+\" ";
		$graphcmd .= "CDEF:\"$curif-in_bits=$curif-in_bits_pass,$curif-in_bits_block,+\" ";
		$graphcmd .= "CDEF:\"$curif-out_bits=$curif-out_bits_pass,$curif-out_bits_block,+\" ";

		$graphcmd .= "CDEF:\"$curif-bits_io=$curif-in_bits,$curif-out_bits,+\" ";
		$graphcmd .= "CDEF:\"$curif-out_bits_block_neg=$curif-out_bits_block,$multiplier,*\" ";
		$graphcmd .= "CDEF:\"$curif-out_bits_pass_neg=$curif-out_bits_pass,$multiplier,*\" ";

		$graphcmd .= "CDEF:\"$curif-bytes_in_pass=$curif-in_bytes_pass,0,$speedlimit,LIMIT,UN,0,$curif-in_bytes_pass,IF,$average,*\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_out_pass=$curif-out_bytes_pass,0,$speedlimit,LIMIT,UN,0,$curif-out_bytes_pass,IF,$average,*\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_in_block=$curif-in_bytes_block,0,$speedlimit,LIMIT,UN,0,$curif-in_bytes_block,IF,$average,*\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_out_block=$curif-out_bytes_block,0,$speedlimit,LIMIT,UN,0,$curif-out_bytes_block,IF,$average,*\" ";

		$graphcmd .= "CDEF:\"$curif-bytes_pass=$curif-bytes_in_pass,$curif-bytes_out_pass,+\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_block=$curif-bytes_in_block,$curif-bytes_out_block,+\" ";

		$graphcmd .= "CDEF:\"$curif-bytes_in_t_pass=$curif-in_bytes_pass,0,$speedlimit,LIMIT,UN,0,$curif-in_bytes_pass,IF,$seconds,*\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_out_t_pass=$curif-out_bytes_pass,0,$speedlimit,LIMIT,UN,0,$curif-out_bytes_pass,IF,$seconds,*\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_in_t_block=$curif-in_bytes_block,0,$speedlimit,LIMIT,UN,0,$curif-in_bytes_block,IF,$seconds,*\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_out_t_block=$curif-out_bytes_block,0,$speedlimit,LIMIT,UN,0,$curif-out_bytes_block,IF,$seconds,*\" ";

		$graphcmd .= "CDEF:\"$curif-bytes_t_pass=$curif-bytes_in_t_pass,$curif-bytes_out_t_pass,+\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_t_block=$curif-bytes_in_t_block,$curif-bytes_out_t_block,+\" ";
		$graphcmd .= "CDEF:\"$curif-bytes_t=$curif-bytes_in_t_pass,$curif-bytes_out_t_block,+\" ";

		$graphcmd .= "VDEF:\"$curif-in_bits_95=$curif-in_bits,95,PERCENT\" ";
		$graphcmd .= "CDEF:\"$curif-out_bits_mul=$curif-out_bits,$multiplier,*\" ";
		$perc = $multiplier > 0 ? "95" : "5";
		$graphcmd .= "VDEF:\"$curif-out_bits_95=$curif-out_bits_mul,{$perc},PERCENT\" ";

		$graphcmd .= "AREA:\"$curif-in_bits_block#{$colortrafficdown[1]}:$curif-in-block\" ";
		$graphcmd .= "AREA:\"$curif-in_bits_pass#{$colortrafficdown[0]}:$curif-in-pass:STACK\" ";
		$graphcmd .= "{$AREA}:\"$curif-out_bits_block_neg#{$colortrafficup[1]}:$curif-out-block\" ";
		$graphcmd .= "{$AREA}:\"$curif-out_bits_pass_neg#{$colortrafficup[0]}:$curif-out-pass:STACK\" ";
		$graphcmd .= "HRULE:\"$curif-in_bits_95#{$colortraffic95[1]}:$curif-in (95%)\" ";
		$graphcmd .= "HRULE:\"$curif-out_bits_95#{$colortraffic95[0]}:$curif-out (95%)\" ";

		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t  maximum	   average	   current		period		95th percentile\\n\" ";

		$graphcmd .= "COMMENT:\"in-pass\t\" ";
		$graphcmd .= "GPRINT:\"$curif-in_bits_pass:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-in_bits_pass:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-in_bits_pass:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-bytes_in_t_pass:AVERAGE:%7.2lf %sB i\" ";
		$graphcmd .= "GPRINT:\"$curif-in_bits_95:%7.2lf %sb/s\" ";

		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"out-pass\t\" ";
		$graphcmd .= "GPRINT:\"$curif-out_bits_pass:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-out_bits_pass:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-out_bits_pass:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-bytes_out_t_pass:AVERAGE:%7.2lf %sB o\" ";
		$graphcmd .= "GPRINT:\"$curif-out_bits_95:%7.2lf %sb/s\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"in-block\t\" ";
		$graphcmd .= "GPRINT:\"$curif-in_bits_block:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-in_bits_block:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-in_bits_block:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-bytes_in_t_block:AVERAGE:%7.2lf %sB i\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"out-block\t\" ";
		$graphcmd .= "GPRINT:\"$curif-out_bits_block:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-out_bits_block:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-out_bits_block:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"$curif-bytes_out_t_block:AVERAGE:%7.2lf %sB o\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif(strstr($curdatabase, "-throughput.rrd")) {
		/* define graphcmd for throughput stats */
		/* this gathers all interface statistics, the database does not actually exist */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"bits/sec\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";

		$iflist = get_configured_interface_list();
		$h = 0;
		$operand = "";
		$comma = "";
		$graphtputbip = "";
		$graphtputbop = "";
		$graphtputbtp = "";
		$graphtputbib = "";
		$graphtputbob = "";
		$graphtputbtb = "";
		$graphtputbyip = "";
		$graphtputbyop = "";
		$graphtputbytp = "";
		$graphtputbyib = "";
		$graphtputbyob = "";
		$graphtputbytb = "";
		foreach($iflist as $ifname) {
			/* collect all interface stats */
			$graphcmd .= "DEF:\"{$ifname}-in_bytes_pass={$rrddbpath}{$ifname}-traffic.rrd:inpass:AVERAGE\" ";
			$graphcmd .= "DEF:\"{$ifname}-out_bytes_pass={$rrddbpath}{$ifname}-traffic.rrd:outpass:AVERAGE\" ";
			$graphcmd .= "DEF:\"{$ifname}-in_bytes_block={$rrddbpath}{$ifname}-traffic.rrd:inblock:AVERAGE\" ";
			$graphcmd .= "DEF:\"{$ifname}-out_bytes_block={$rrddbpath}{$ifname}-traffic.rrd:outblock:AVERAGE\" ";

			$graphcmd .= "CDEF:\"{$ifname}-in_bytes={$ifname}-in_bytes_pass,{$ifname}-in_bytes_block,+\" ";
			$graphcmd .= "CDEF:\"{$ifname}-out_bytes={$ifname}-out_bytes_pass,{$ifname}-out_bytes_block,+\" ";

			$graphcmd .= "CDEF:\"{$ifname}-in_bits_pass={$ifname}-in_bytes_pass,8,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-out_bits_pass={$ifname}-out_bytes_pass,8,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bits_io_pass={$ifname}-in_bits_pass,{$ifname}-out_bits_pass,+\" ";

			$graphcmd .= "CDEF:\"{$ifname}-in_bits_block={$ifname}-in_bytes,8,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-out_bits_block={$ifname}-out_bytes,8,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bits_io_block={$ifname}-in_bits_block,{$ifname}-out_bits_block,+\" ";

			$graphcmd .= "CDEF:\"{$ifname}-bytes_in_pass={$ifname}-in_bytes_pass,0,$speedlimit,LIMIT,UN,0,{$ifname}-in_bytes_pass,IF,$average,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_out_pass={$ifname}-out_bytes_pass,0,$speedlimit,LIMIT,UN,0,{$ifname}-out_bytes_pass,IF,$average,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_in_block={$ifname}-in_bytes_block,0,$speedlimit,LIMIT,UN,0,{$ifname}-in_bytes_block,IF,$average,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_out_block={$ifname}-out_bytes_block,0,$speedlimit,LIMIT,UN,0,{$ifname}-out_bytes_block,IF,$average,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_pass={$ifname}-bytes_in_pass,{$ifname}-bytes_out_pass,+\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_block={$ifname}-bytes_in_pass,{$ifname}-bytes_out_block,+\" ";

			$graphcmd .= "CDEF:\"{$ifname}-bytes_in_t_pass={$ifname}-in_bytes,0,$speedlimit,LIMIT,UN,0,{$ifname}-in_bytes_pass,IF,$seconds,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_in_t_block={$ifname}-in_bytes,0,$speedlimit,LIMIT,UN,0,{$ifname}-in_bytes_block,IF,$seconds,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_out_t_pass={$ifname}-out_bytes,0,$speedlimit,LIMIT,UN,0,{$ifname}-out_bytes_pass,IF,$seconds,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_out_t_block={$ifname}-out_bytes,0,$speedlimit,LIMIT,UN,0,{$ifname}-out_bytes_block,IF,$seconds,*\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_t_pass={$ifname}-bytes_in_t_pass,{$ifname}-bytes_out_t_pass,+\" ";
			$graphcmd .= "CDEF:\"{$ifname}-bytes_t_block={$ifname}-bytes_in_t_block,{$ifname}-bytes_out_t_block,+\" ";
			if ($h > 0) {
				$operand .= ",+";
				$comma = ",";
			}
			$graphtputbip .= "{$comma}{$ifname}-in_bits_pass";
			$graphtputbop .= "{$comma}{$ifname}-out_bits_pass";
			$graphtputbtp .= "{$comma}{$ifname}-bits_io_pass";
			$graphtputbib .= "{$comma}{$ifname}-in_bits_block";
			$graphtputbob .= "{$comma}{$ifname}-out_bits_block";
			$graphtputbtb .= "{$comma}{$ifname}-bits_io_block";
			$graphtputbyip .= "{$comma}{$ifname}-bytes_in_t_pass";
			$graphtputbyop .= "{$comma}{$ifname}-bytes_out_t_pass";
			$graphtputbyib .= "{$comma}{$ifname}-bytes_in_t_block";
			$graphtputbyob .= "{$comma}{$ifname}-bytes_out_t_block";
			$graphtputbytp .= "{$comma}{$ifname}-bytes_t_pass";
			$graphtputbytb .= "{$comma}{$ifname}-bytes_t_block";
			$h++;
		}
		$graphcmd .= "CDEF:\"tput-in_bits_pass={$graphtputbip}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-out_bits_pass={$graphtputbop}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-bits_io_pass={$graphtputbtp}{$operand}\" ";

		$graphcmd .= "CDEF:\"tput-in_bits_block={$graphtputbib}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-out_bits_block={$graphtputbob}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-bits_io_block={$graphtputbtb}{$operand}\" ";

		$graphcmd .= "CDEF:\"tput-out_bits_pass_neg=tput-out_bits_pass,$multiplier,*\" ";
		$graphcmd .= "CDEF:\"tput-out_bits_block_neg=tput-out_bits_block,$multiplier,*\" ";

		$graphcmd .= "CDEF:\"tput-bytes_in_t_pass={$graphtputbyip}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-bytes_out_t_pass={$graphtputbyop}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-bytes_t_pass={$graphtputbytp}{$operand}\" ";

		$graphcmd .= "CDEF:\"tput-bytes_in_t_block={$graphtputbyib}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-bytes_out_t_block={$graphtputbyob}{$operand}\" ";
		$graphcmd .= "CDEF:\"tput-bytes_t_block={$graphtputbytb}{$operand}\" ";

		$graphcmd .= "AREA:\"tput-in_bits_block#{$colortrafficdown[0]}:in-block \" ";
		$graphcmd .= "AREA:\"tput-in_bits_pass#{$colortrafficdown[1]}:in-pass \" ";

		$graphcmd .= "{$AREA}:\"tput-out_bits_block_neg#{$colortrafficup[1]}:out-block \" ";
		$graphcmd .= "{$AREA}:\"tput-out_bits_pass_neg#{$colortrafficup[0]}:out-pass \" ";

		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t  maximum	   average	   current		period\\n\" ";
		$graphcmd .= "COMMENT:\"in-pass\t\" ";
		$graphcmd .= "GPRINT:\"tput-in_bits_pass:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-in_bits_pass:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-in_bits_pass:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-bytes_in_t_pass:AVERAGE:%7.2lf %sB i\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"out-pass\t\" ";
		$graphcmd .= "GPRINT:\"tput-out_bits_pass:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-out_bits_pass:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-out_bits_pass:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-bytes_out_t_pass:AVERAGE:%7.2lf %sB o\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"in-block\t\" ";
		$graphcmd .= "GPRINT:\"tput-in_bits_block:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-in_bits_block:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-in_bits_block:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-bytes_in_t_block:AVERAGE:%7.2lf %sB i\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"out-block\t\" ";
		$graphcmd .= "GPRINT:\"tput-out_bits_block:MAX:%7.2lf %sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-out_bits_block:AVERAGE:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-out_bits_block:LAST:%7.2lf %Sb/s\" ";
		$graphcmd .= "GPRINT:\"tput-bytes_out_t_block:AVERAGE:%7.2lf %sB o\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-packets.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for packets stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"packets/sec\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"$curif-in_pps_pass=$rrddbpath$curdatabase:inpass:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-out_pps_pass=$rrddbpath$curdatabase:outpass:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-in_pps_block=$rrddbpath$curdatabase:inblock:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-out_pps_block=$rrddbpath$curdatabase:outblock:AVERAGE\" ";

		$graphcmd .= "CDEF:\"$curif-in_pps=$curif-in_pps_pass,$curif-in_pps_block,+\" ";
		$graphcmd .= "CDEF:\"$curif-out_pps=$curif-out_pps_pass,$curif-out_pps_block,+\" ";
		$graphcmd .= "CDEF:\"$curif-out_pps_pass_neg=$curif-out_pps_pass,$multiplier,*\" ";
		$graphcmd .= "CDEF:\"$curif-out_pps_block_neg=$curif-out_pps_block,$multiplier,*\" ";

		$graphcmd .= "CDEF:\"$curif-pps_in_pass=$curif-in_pps_pass,0,12500000,LIMIT,UN,0,$curif-in_pps_pass,IF,$average,*\" ";
		$graphcmd .= "CDEF:\"$curif-pps_out_pass=$curif-out_pps_pass,0,12500000,LIMIT,UN,0,$curif-out_pps_pass,IF,$average,*\" ";
		$graphcmd .= "CDEF:\"$curif-pps_in_block=$curif-in_pps_block,0,12500000,LIMIT,UN,0,$curif-in_pps_block,IF,$average,*\" ";
		$graphcmd .= "CDEF:\"$curif-pps_out_block=$curif-out_pps_block,0,12500000,LIMIT,UN,0,$curif-out_pps_block,IF,$average,*\" ";

		$graphcmd .= "CDEF:\"$curif-pps_io=$curif-in_pps,$curif-out_pps,+\" ";
		$graphcmd .= "CDEF:\"$curif-pps_pass=$curif-pps_in_pass,$curif-pps_out_pass,+\" ";
		$graphcmd .= "CDEF:\"$curif-pps_block=$curif-pps_in_block,$curif-pps_out_block,+\" ";

		$graphcmd .= "CDEF:\"$curif-pps_in_t_pass=$curif-in_pps_pass,0,12500000,LIMIT,UN,0,$curif-in_pps_pass,IF,$seconds,*\" ";
		$graphcmd .= "CDEF:\"$curif-pps_out_t_pass=$curif-out_pps_pass,0,12500000,LIMIT,UN,0,$curif-out_pps_pass,IF,$seconds,*\" ";
		$graphcmd .= "CDEF:\"$curif-pps_in_t_block=$curif-in_pps_block,0,12500000,LIMIT,UN,0,$curif-in_pps_block,IF,$seconds,*\" ";
		$graphcmd .= "CDEF:\"$curif-pps_out_t_block=$curif-out_pps_block,0,12500000,LIMIT,UN,0,$curif-out_pps_block,IF,$seconds,*\" ";

		$graphcmd .= "CDEF:\"$curif-pps_t_pass=$curif-pps_in_t_pass,$curif-pps_out_t_pass,+\" ";
		$graphcmd .= "CDEF:\"$curif-pps_t_block=$curif-pps_in_t_block,$curif-pps_out_t_block,+\" ";

		$graphcmd .= "AREA:\"$curif-in_pps_block#{$colorpacketsdown[1]}:$curif-in-block\" ";
		$graphcmd .= "AREA:\"$curif-in_pps_pass#{$colorpacketsdown[0]}:$curif-in-pass:STACK\" ";

		$graphcmd .= "$AREA:\"$curif-out_pps_block_neg#{$colorpacketsup[1]}:$curif-out-block\" ";
		$graphcmd .= "$AREA:\"$curif-out_pps_pass_neg#{$colorpacketsup[0]}:$curif-out-pass:STACK\" ";

		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t  maximum	   average	   current		period\\n\" ";
		$graphcmd .= "COMMENT:\"in-pass\t\" ";
		$graphcmd .= "GPRINT:\"$curif-in_pps_pass:MAX:%7.2lf %s pps\" ";
		$graphcmd .= "GPRINT:\"$curif-in_pps_pass:AVERAGE:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-in_pps_pass:LAST:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-pps_in_t_pass:AVERAGE:%7.2lf %s pkts\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"out-pass\t\" ";
		$graphcmd .= "GPRINT:\"$curif-out_pps_pass:MAX:%7.2lf %s pps\" ";
		$graphcmd .= "GPRINT:\"$curif-out_pps_pass:AVERAGE:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-out_pps_pass:LAST:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-pps_out_t_pass:AVERAGE:%7.2lf %s pkts\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"in-block\t\" ";
		$graphcmd .= "GPRINT:\"$curif-in_pps_block:MAX:%7.2lf %s pps\" ";
		$graphcmd .= "GPRINT:\"$curif-in_pps_block:AVERAGE:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-in_pps_block:LAST:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-pps_in_t_block:AVERAGE:%7.2lf %s pkts\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"out-block\t\" ";
		$graphcmd .= "GPRINT:\"$curif-out_pps_block:MAX:%7.2lf %s pps\" ";
		$graphcmd .= "GPRINT:\"$curif-out_pps_block:AVERAGE:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-out_pps_block:LAST:%7.2lf %S pps\" ";
		$graphcmd .= "GPRINT:\"$curif-pps_out_t_block:AVERAGE:%7.2lf %s pkts\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-wireless.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for wireless stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"snr/channel/rate\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"$curif-snr=$rrddbpath$curdatabase:snr:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-rate=$rrddbpath$curdatabase:rate:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-channel=$rrddbpath$curdatabase:channel:AVERAGE\" ";
		$graphcmd .= "LINE2:\"$curif-snr#{$colorwireless[0]}:$curif-snr\" ";
		$graphcmd .= "LINE2:\"$curif-rate#{$colorwireless[1]}:$curif-rate\" ";
		$graphcmd .= "LINE2:\"$curif-channel#{$colorwireless[2]}:$curif-channel\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t   maximum\t\t average\t	 current\\n\" ";
		$graphcmd .= "COMMENT:\"SNR\t\t\" ";
		$graphcmd .= "GPRINT:\"$curif-snr:MAX:%7.2lf dBi  \" ";
		$graphcmd .= "GPRINT:\"$curif-snr:AVERAGE:%7.2lf dBi  \" ";
		$graphcmd .= "GPRINT:\"$curif-snr:LAST:%7.2lf dBi\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"RATE\t\t\" ";
		$graphcmd .= "GPRINT:\"$curif-rate:MAX:%7.2lf Mb   \" ";
		$graphcmd .= "GPRINT:\"$curif-rate:AVERAGE:%7.2lf Mb   \" ";
		$graphcmd .= "GPRINT:\"$curif-rate:LAST:%7.2lf Mb\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Channel\t\" ";
		$graphcmd .= "GPRINT:\"$curif-channel:MAX:%7.2lf	  \" ";
		$graphcmd .= "GPRINT:\"$curif-channel:AVERAGE:%7.2lf	  \" ";
		$graphcmd .= "GPRINT:\"$curif-channel:LAST:%7.2lf\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-vpnusers.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for vpn users stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"users\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"$curif-users=$rrddbpath$curdatabase:users:AVERAGE\" ";
		$graphcmd .= "LINE2:\"$curif-users#{$colorvpnusers[0]}:$curif-users\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t	maximum\t\t average\t	 current\\n\" ";
		$graphcmd .= "COMMENT:\"Users Online\t\" ";
		$graphcmd .= "GPRINT:\"$curif-users:MAX:%7.2lf	 \" ";
		$graphcmd .= "GPRINT:\"$curif-users:AVERAGE:%7.2lf	  \" ";
		$graphcmd .= "GPRINT:\"$curif-users:LAST:%7.2lf \" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-states.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for states stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start -$seconds -e -$average ";
		$graphcmd .= "--vertical-label \"states, ip\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"$curif-pfrate=$rrddbpath$curdatabase:pfrate:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-pfstates=$rrddbpath$curdatabase:pfstates:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-pfnat=$rrddbpath$curdatabase:pfnat:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-srcip=$rrddbpath$curdatabase:srcip:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-dstip=$rrddbpath$curdatabase:dstip:AVERAGE\" ";
		$graphcmd .= "CDEF:\"$curif-pfrate_t=$curif-pfrate,0,1000000,LIMIT,UN,0,$curif-pfrate,IF,$seconds,*\" ";
		$graphcmd .= "LINE1:\"$curif-pfrate#{$colorstates[0]}:$curif-pfrate\" ";
		$graphcmd .= "LINE1:\"$curif-pfstates#{$colorstates[1]}:$curif-pfstates\" ";
		$graphcmd .= "LINE1:\"$curif-pfnat#{$colorstates[2]}:$curif-pfnat\" ";
		$graphcmd .= "LINE1:\"$curif-srcip#{$colorstates[3]}:$curif-srcip\" ";
		$graphcmd .= "LINE1:\"$curif-dstip#{$colorstates[4]}:$curif-dstip\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t	  minimum		average		maximum		current		 period\\n\" ";
		$graphcmd .= "COMMENT:\"state changes\" ";
		$graphcmd .= "GPRINT:\"$curif-pfrate:MIN:%7.2lf %s cps\" ";
		$graphcmd .= "GPRINT:\"$curif-pfrate:AVERAGE:%7.2lf %s cps\" ";
		$graphcmd .= "GPRINT:\"$curif-pfrate:MAX:%7.2lf %s cps\" ";
		$graphcmd .= "GPRINT:\"$curif-pfrate:LAST:%7.2lf %S cps\" ";
		$graphcmd .= "GPRINT:\"$curif-pfrate_t:AVERAGE:%7.2lf %s chg\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"filter states\" ";
		$graphcmd .= "GPRINT:\"$curif-pfstates:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-pfstates:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-pfstates:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-pfstates:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"nat states   \" ";
		$graphcmd .= "GPRINT:\"$curif-pfnat:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-pfnat:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-pfnat:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-pfnat:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Source addr. \" ";
		$graphcmd .= "GPRINT:\"$curif-srcip:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-srcip:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-srcip:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-srcip:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Dest. addr.  \" ";
		$graphcmd .= "GPRINT:\"$curif-dstip:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-dstip:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-dstip:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"$curif-dstip:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-processor.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for processor stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"utilization, number\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"user=$rrddbpath$curdatabase:user:AVERAGE\" ";
		$graphcmd .= "DEF:\"nice=$rrddbpath$curdatabase:nice:AVERAGE\" ";
		$graphcmd .= "DEF:\"system=$rrddbpath$curdatabase:system:AVERAGE\" ";
		$graphcmd .= "DEF:\"interrupt=$rrddbpath$curdatabase:interrupt:AVERAGE\" ";
		$graphcmd .= "DEF:\"processes=$rrddbpath$curdatabase:processes:AVERAGE\" ";
		$graphcmd .= "AREA:\"user#{$colorprocessor[0]}:user\" ";
		$graphcmd .= "AREA:\"nice#{$colorprocessor[1]}:nice:STACK\" ";
		$graphcmd .= "AREA:\"system#{$colorprocessor[2]}:system:STACK\" ";
		$graphcmd .= "AREA:\"interrupt#{$colorprocessor[3]}:interrupt:STACK\" ";
		$graphcmd .= "LINE2:\"processes#{$colorprocessor[4]}:processes\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t	  minimum		average		maximum		current\\n\" ";
		$graphcmd .= "COMMENT:\"User util.   \" ";
		$graphcmd .= "GPRINT:\"user:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"user:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"user:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"user:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Nice util.   \" ";
		$graphcmd .= "GPRINT:\"nice:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"nice:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"nice:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"nice:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"System util. \" ";
		$graphcmd .= "GPRINT:\"system:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"system:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"system:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"system:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Interrupt	\" ";
		$graphcmd .= "GPRINT:\"interrupt:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"interrupt:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"interrupt:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"interrupt:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Processes	\" ";
		$graphcmd .= "GPRINT:\"processes:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"processes:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"processes:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"processes:LAST:%7.2lf %s	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-memory.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for memory usage stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"utilization, percent\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"active=$rrddbpath$curdatabase:active:AVERAGE\" ";
		$graphcmd .= "DEF:\"inactive=$rrddbpath$curdatabase:inactive:AVERAGE\" ";
		$graphcmd .= "DEF:\"free=$rrddbpath$curdatabase:free:AVERAGE\" ";
		$graphcmd .= "DEF:\"cache=$rrddbpath$curdatabase:cache:AVERAGE\" ";
		$graphcmd .= "DEF:\"wire=$rrddbpath$curdatabase:wire:AVERAGE\" ";
		$graphcmd .= "LINE2:\"active#{$colormemory[0]}:active\" ";
		$graphcmd .= "LINE2:\"inactive#{$colormemory[1]}:inactive\" ";
		$graphcmd .= "LINE2:\"free#{$colormemory[2]}:free\" ";
		$graphcmd .= "LINE2:\"cache#{$colormemory[3]}:cache\" ";
		$graphcmd .= "LINE2:\"wire#{$colormemory[4]}:wire\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t	  minimum		average		maximum		current\\n\" ";
		$graphcmd .= "COMMENT:\"Active.	  \" ";
		$graphcmd .= "GPRINT:\"active:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"active:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"active:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"active:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Inactive.	\" ";
		$graphcmd .= "GPRINT:\"inactive:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"inactive:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"inactive:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"inactive:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Free.		\" ";
		$graphcmd .= "GPRINT:\"free:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"free:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"free:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"free:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Cached.	  \" ";
		$graphcmd .= "GPRINT:\"cache:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"cache:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"cache:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"cache:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Wired.	   \" ";
		$graphcmd .= "GPRINT:\"wire:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"wire:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"wire:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"wire:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-mbuf.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for mbuf usage stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"utilization, percent\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} clusters - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"current=$rrddbpath$curdatabase:current:AVERAGE\" ";
		$graphcmd .= "DEF:\"cache=$rrddbpath$curdatabase:cache:AVERAGE\" ";
		$graphcmd .= "DEF:\"total=$rrddbpath$curdatabase:total:AVERAGE\" ";
		$graphcmd .= "DEF:\"max=$rrddbpath$curdatabase:max:AVERAGE\" ";
		$graphcmd .= "LINE2:\"current#{$colormbuf[0]}:current\" ";
		$graphcmd .= "LINE2:\"cache#{$colormbuf[1]}:cache\" ";
		$graphcmd .= "LINE2:\"total#{$colormbuf[2]}:total\" ";
		$graphcmd .= "LINE2:\"max#{$colormbuf[3]}:max\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t	minimum	average	maximum	current\\n\" ";
		$graphcmd .= "COMMENT:\"Current.	\" ";
		$graphcmd .= "GPRINT:\"current:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"current:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"current:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"current:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Cache.	\" ";
		$graphcmd .= "GPRINT:\"cache:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"cache:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"cache:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"cache:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Total.	\" ";
		$graphcmd .= "GPRINT:\"total:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"total:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"total:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"total:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Max.		\" ";
		$graphcmd .= "GPRINT:\"max:MIN:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"max:AVERAGE:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"max:MAX:%7.2lf %s	\" ";
		$graphcmd .= "GPRINT:\"max:LAST:%7.2lf %S	\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-queues.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for queue stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"bits/sec\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		if ($altq) {
			$a_queues =& $altq->get_queue_list();
			$t = 0;
		} else {
			$a_queues = array();
			$i = 0;
			$t = 0;
		}
		foreach ($a_queues as $name => $q) {
			$color = "$colorqueuesup[$t]";
			if($t > 0) { $stack = ":STACK"; }
			$graphcmd .= "DEF:\"$name=$rrddbpath$curdatabase:$name:AVERAGE\" ";
			$graphcmd .= "CDEF:\"$name-bytes_out=$name,0,$speedlimit,LIMIT,UN,0,$name,IF\" ";
			$graphcmd .= "CDEF:\"$name-bits_out=$name-bytes_out,8,*\" ";
			$graphcmd .= "$AREA:\"$name-bits_out#${color}:$name\" ";
			$t++;
			if($t > 7) { $t = 0; }
		}
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-queuedrops.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for queuedrop stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"drops / sec\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		if ($altq) {
			$a_queues =& $altq->get_queue_list();
			$t = 0;
		} else {
				$a_queues = array();
			$i = 0;
			$t = 0;
		}
		foreach ($a_queues as $name => $q) {
			$color = "$colorqueuesdropup[$t]";
			if($t > 0) { $stack = ":STACK"; }
			$graphcmd .= "DEF:\"$name=$rrddbpath$curdatabase:$name:AVERAGE\" ";
			$graphcmd .= "CDEF:\"$name-bytes_out=$name,0,$speedlimit,LIMIT,UN,0,$name,IF\" ";
			$graphcmd .= "CDEF:\"$name-bits_out=$name-bytes_out,8,*\" ";
			$graphcmd .= "CDEF:\"$name-bits_out_neg=$name-bits_out,$multiplier,*\" ";
			$graphcmd .= "$AREA:\"$name-bits_out_neg#${color}:$name\" ";
			$t++;
			if($t > 7) { $t = 0; }
		}
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-quality.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* make a link quality graphcmd, we only have WAN for now, others too follow */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png \\
			--start $start --end $end  \\
			--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" \\
			--color SHADEA#eeeeee --color SHADEB#eeeeee \\
			--vertical-label \"ms / %\" \\
			--height 200 --width 620 \\
			--lower-limit 0 \\
			DEF:delayraw=$rrddbpath$curdatabase:delay:AVERAGE \\
			DEF:loss=$rrddbpath$curdatabase:loss:AVERAGE \\
			\"CDEF:delay=delayraw,1000,*\" \\
			\"CDEF:roundavg=delay,PREV(delay),+,2,/\" \\
			\"CDEF:loss10=loss,$multiplier,*\" \\
			\"CDEF:r0=delay,20,MIN\" \\
			\"CDEF:r1=delay,60,MIN\" \\
			\"CDEF:r2=delay,180,MIN\" \\
			\"CDEF:r3=delay,420,MIN\" \\
			COMMENT:\"\t\t\t\t\tDelay\t\t\tPacket loss\\n\" \\
			AREA:delay#$colorqualityrtt[0]:\"> 420	  ms\" \\
			GPRINT:delay:MIN:\"\t\tMin\\:  %7.2lf ms\" \\
			GPRINT:loss:MIN:\"\tMin\\: %3.1lf %%\\n\" \\
				AREA:r3#$colorqualityrtt[1]:\"180-420	ms\" \\
			GPRINT:delay:AVERAGE:\"\t\tAvg\\:  %7.2lf ms\" \\
			GPRINT:loss:AVERAGE:\"\tAvg\\: %3.1lf %%\\n\" \\
			AREA:r2#$colorqualityrtt[2]:\"60-180	 ms\" \\
			GPRINT:delay:MAX:\"\t\tMax\\:  %7.2lf ms\" \\
			GPRINT:loss:MAX:\"\tMax\\: %3.1lf %%\\n\" \\
			AREA:r1#$colorqualityrtt[3]:\"20-60	  ms\\n\" \\
			AREA:r0#$colorqualityrtt[4]:\"< 20	   ms\" \\
			GPRINT:delay:LAST:\"\t\tLast\\: %7.2lf ms\" \\
			GPRINT:loss:LAST:\"\tLast\: %3.1lf %%\\n\" \\
			AREA:loss10#$colorqualityloss:\"Packet loss\\n\" \\
			LINE1:delay#$colorqualityrtt[5]:\"Delay average\\n\" \\
			COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\"";
	}
	elseif((strstr($curdatabase, "spamd.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* graph a spamd statistics graph */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png \\
			--start $start --end $end \\
			--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" \\
			--color SHADEA#eeeeee --color SHADEB#eeeeee \\
			--vertical-label=\"Conn / Time, sec.\" \\
			--height 200 --width 620 --no-gridfit \\
			--lower-limit 0 \\
			DEF:consmin=$rrddbpath$curdatabase:conn:MIN \\
			DEF:consavg=$rrddbpath$curdatabase:conn:AVERAGE \\
			DEF:consmax=$rrddbpath$curdatabase:conn:MAX \\
			DEF:timemin=$rrddbpath$curdatabase:time:MIN \\
			DEF:timeavg=$rrddbpath$curdatabase:time:AVERAGE \\
			DEF:timemax=$rrddbpath$curdatabase:time:MAX \\
			\"CDEF:timeminadj=timemin,0,86400,LIMIT,UN,0,timemin,IF\" \\
			\"CDEF:timeavgadj=timeavg,0,86400,LIMIT,UN,0,timeavg,IF\" \\
			\"CDEF:timemaxadj=timemax,0,86400,LIMIT,UN,0,timemax,IF\" \\
			\"CDEF:t1=timeminadj,timeavgadj,+,2,/,timeminadj,-\" \\
			\"CDEF:t2=timeavgadj,timemaxadj,+,2,/,timeminadj,-,t1,-\" \\
			\"CDEF:t3=timemaxadj,timeminadj,-,t1,-,t2,-\" \\
			AREA:timeminadj \\
			AREA:t1#$colorspamdtime[0]::STACK \\
			AREA:t2#$colorspamdtime[1]::STACK \\
			AREA:t3#$colorspamdtime[2]::STACK \\
			LINE2:timeavgadj#$colorspamdtime[3]:\"Time \" \\
			GPRINT:timeminadj:MIN:\"Min\\:%6.2lf\\t\" \\
			GPRINT:timeavgadj:AVERAGE:\"Avg\\:%6.2lf\\t\" \\
			GPRINT:timemaxadj:MAX:\"Max\\:%6.2lf\\n\" \\
			AREA:consmax#$colorspamdconn[0] \\
			AREA:consmin#$colorspamdconn[1] \\
			LINE1:consmin#$colorspamdconn[2] \\
			LINE1:consmax#$colorspamdconn[3] \\
			LINE1:consavg#$colorspamdconn[4]:\"Cons \" \\
			GPRINT:consmin:MIN:\"Min\\:%6.2lf\\t\" \\
			GPRINT:consavg:AVERAGE:\"Avg\\:%6.2lf\\t\" \\
			GPRINT:consmax:MAX:\"Max\\:%6.2lf\\n\" \\
			COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-cellular.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"signal\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"$curif-signal1=$rrddbpath$curdatabase:signal1:AVERAGE\" ";
		$graphcmd .= "DEF:\"$curif-signal2=$rrddbpath$curdatabase:signal2:AVERAGE\" ";
		$graphcmd .= "LINE2:\"$curif-signal1#{$colorwireless[0]}:$curif-signal1\" ";
		$graphcmd .= "LINE2:\"$curif-signal2#{$colorwireless[1]}:$curif-signal2\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t   maximum\t\t average\t	 current\\n\" ";
		$graphcmd .= "COMMENT:\"Signal1\t\t\" ";
		$graphcmd .= "GPRINT:\"$curif-signal1:MAX:%7.2lf dBm  \" ";
		$graphcmd .= "GPRINT:\"$curif-signal1:AVERAGE:%7.2lf dBm  \" ";
		$graphcmd .= "GPRINT:\"$curif-signal1:LAST:%7.2lf dBm\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"Signal2\t\t\" ";
		$graphcmd .= "GPRINT:\"$curif-signal2:MAX:%7.2lf dBm  \" ";
		$graphcmd .= "GPRINT:\"$curif-signal2:AVERAGE:%7.2lf dBm  \" ";
		$graphcmd .= "GPRINT:\"$curif-signal2:LAST:%7.2lf dBm\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-loggedin.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for online Captive Portal users stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"Captive Portal Users\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--base=1000 ";
		$graphcmd .= "--lower-limit=0 ";
		$graphcmd .= "--slope-mode ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"$curif-loggedinusers=$rrddbpath$curdatabase:loggedinusers:AVERAGE\" ";
		$graphcmd .= "CDEF:\"$curif-totalusers_t=PREV,UN,0,PREV,IF,$curif-loggedinusers,+\" ";
		$graphcmd .= "CDEF:\"$curif-totalusers_d=$curif-totalusers_t,FLOOR\" ";
		$graphcmd .= "AREA:\"$curif-totalusers_d#{$colorcaptiveportalusers[0]}:Total logged in users\" ";
		$graphcmd .= "GPRINT:\"$curif-totalusers_d:MAX:%8.0lf \\n\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	elseif((strstr($curdatabase, "-concurrent.rrd")) && (file_exists("$rrddbpath$curdatabase"))) {
		/* define graphcmd for online Captive Portal users stats */
		$graphcmd = "$rrdtool graph $rrdtmppath$curdatabase-$curgraph.png ";
		$graphcmd .= "--start $start --end $end ";
		$graphcmd .= "--vertical-label \"Captive Portal Users\" ";
		$graphcmd .= "--color SHADEA#eeeeee --color SHADEB#eeeeee ";
		$graphcmd .= "--title \"`hostname` - {$prettydb} - {$hperiod} - {$havg} average\" ";
		$graphcmd .= "--base=1000 ";
		$graphcmd .= "--lower-limit=0 ";
		$graphcmd .= "--slope-mode ";
		$graphcmd .= "--height 200 --width 620 ";
		$graphcmd .= "DEF:\"$curif-concurrentusers=$rrddbpath$curdatabase:concurrentusers:AVERAGE\" ";
		$graphcmd .= "AREA:\"$curif-concurrentusers#{$colorcaptiveportalusers[0]}:Concurrent Users\" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t	current\t\t average\t	 maximum\\n\" ";
		$graphcmd .= "COMMENT:\"Users Online\t\" ";
		$graphcmd .= "GPRINT:\"$curif-concurrentusers:LAST:%8.0lf	 \" ";
		$graphcmd .= "GPRINT:\"$curif-concurrentusers:AVERAGE:%8.0lf	  \" ";
		$graphcmd .= "GPRINT:\"$curif-concurrentusers:MAX:%8.0lf \" ";
		$graphcmd .= "COMMENT:\"\\n\" ";
		$graphcmd .= "COMMENT:\"\t\t\t\t\t\t\t\t\t\t\t\t\t`date +\"%b %d %H\:%M\:%S %Y\"`\" ";
	}
	else {
		$data = false;
		log_error(sprintf(gettext("Sorry we do not have data to graph for %s"),$curdatabase));
	}

	/* check modification time to see if we need to generate image */
	if (file_exists("$rrdtmppath$curdatabase-$curgraph.png")) {
		if((time() - filemtime("$rrdtmppath$curdatabase-$curgraph.png")) >= 5 ) {
			if($data)
				exec("$graphcmd 2>&1", $graphcmdoutput, $graphcmdreturn);
				$graphcmdoutput = implode(" ", $graphcmdoutput) . $graphcmd;
				flush();
				usleep(500);
		}
	} else {
		if($data)
			exec("$graphcmd 2>&1", $graphcmdoutput, $graphcmdreturn);
			$graphcmdoutput = implode(" ", $graphcmdoutput) . $graphcmd;
			flush();
			usleep(500);
	}
	if(($graphcmdreturn <> 0) || (! $data)) {
		log_error(sprintf(gettext('Failed to create graph with error code %1$s, the error is: %2$s'),$graphcmdreturn,$graphcmdoutput));
		if(strstr($curdatabase, "queues")) {
			log_error(sprintf(gettext("failed to create graph from %s%s, removing database"),$rrddbpath,$curdatabase));
			exec("/bin/rm -f $rrddbpath$curif$queues");
			flush();
			usleep(500);
			enable_rrd_graphing();
		}
		if(strstr($curdatabase, "queuesdrop")) {
			log_error(sprintf(gettext("failed to create graph from %s%s, removing database"),$rrddbpath,$curdatabase));
			exec("/bin/rm -f $rrddbpath$curdatabase");
			flush();
			usleep(500);
			enable_rrd_graphing();
		}
		header("Content-type: image/png");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false);
		header("Pragma: no-cache");
		$file= "/usr/local/www/themes/{$g['theme']}/images/misc/rrd_error.png";
		return($file);
	} else {
		$file = "$rrdtmppath$curdatabase-$curgraph.png";
		if(file_exists("$file")) {
			header("Content-type: image/png");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: no-store, no-cache, must-revalidate");
			header("Cache-Control: post-check=0, pre-check=0", false);
			header("Pragma: no-cache");
			return($file);
		}
	}

}
function timeDiff($time, $opt = array()) {
	// The default values
	$defOptions = array(
		'to' => 0,
		'parts' => 1,
		'precision' => 'second',
		'distance' => TRUE,
		'separator' => ', '
	);
	$opt = array_merge($defOptions, $opt);
	// Default to current time if no to point is given
	(!$opt['to']) && ($opt['to'] = time());
	// Init an empty string
	$str = '';
	// To or From computation
	$diff = ($opt['to'] > $time) ? $opt['to'] - $time : $time - $opt['to'];
	// An array of label => periods of seconds;
	$periods = array(
		'decade' => 315569260,
		'year' => 31539600,
		'month' => 2629744,
		'week' => 604800,
		'day' => 86400,
		'hour' => 3600,
		'minute' => 60,
		'second' => 1
	);
	// 31539600, 31556926, 31622400
	// Round to precision
	if ($opt['precision'] != 'second')
		$diff = round(($diff / $periods[$opt['precision']])) * $periods[$opt['precision']];
	// Report the value is 'less than 1 ' precision period away
	(0 == $diff) && ($str = 'less than 1 ' . $opt['precision']);
	// Loop over each period
	foreach ($periods as $label => $value) {
		// Stitch together the time difference string
		(($x = round($diff / $value)) && $opt['parts']--) && $str .= ($str ? $opt['separator'] : '') . ($x .' '. $label. ($x > 1 ? 's' : ''));
		// Stop processing if no more parts are going to be reported.
		if ($opt['parts'] == 0 || $label == $opt['precision']) break;
		// Get ready for the next pass
		$diff -= $x * $value;
	}
	$opt['distance'] && $str .= ($str && $opt['to'] >= $time) ? ' ago' : ' away';
	return $str;
}

function mail_report_get_log($logfile, $tail, $grepfor) {
	global $g, $config;
	$logfile = "{$g['varlog_path']}/{$logfile}";
	$logarr = "";
	$grepline = "  ";
	if(is_array($grepfor))
		$grepline = " | /usr/bin/egrep " . escapeshellarg(implode("|", $grepfor));
	if($config['system']['disablesyslogclog']) {
		exec("cat {$logfile}{$grepline} | /usr/bin/tail -n {$tail}", $logarr);
	} else {
		if(isset($config['system']['usefifolog'])) {
			exec("/usr/sbin/fifolog_reader {$logfile}{$grepline} | /usr/bin/tail -n {$tail}", $logarr);
		} else {
			if (is_executable("/usr/local/sbin/clog")) {
				exec("/usr/local/sbin/clog {$logfile}{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail -n {$tail}", $logarr);
			} elseif (is_executable("/usr/sbin/clog")) {
				exec("/usr/sbin/clog {$logfile}{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail -n {$tail}", $logarr);
			} else {
				$logarr = array("Cannot locate clog which is required for reading log files.");
			}
		}
	}
	return($logarr);
}

function get_friendly_log_name($logfile) {
	global $logfile_friendly;
	$friendly = str_replace(".log", "", $logfile);
	if (!empty($logfile_friendly[$friendly]))
		$friendly = $logfile_friendly[$friendly];
	return $friendly;
}

function fixup_graph_timespan($timespan) {
	switch ($timespan) {
		case "8hour":
			return "eighthour";
		case "4year":
			return "fouryear";
		default:
			return $timespan;
	}
}

?>