<?php
#
# Copyright (C) 2008 Red Hat, Inc.
# Author: Andreas Thienemann <athienem@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Library General Public License as published by
# the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

require_once('phplot-5.0.5/phplot.php');

// Get the data from the table, format it and write it out to a file
function chart_prepare($flowsrc, $starttime, $endtime) {
	global $date_fmt_str;
	global $dbh;


	// Define the plot properties
	$style = 'Protocol Distribution';
	$chart_title = $style.' '.$flowsrc.' - '.strftime($date_fmt_str, $starttime).' to '.strftime($date_fmt_str, $endtime);
	$ytitle = 'Bytes';
	$output = tempnam('tmp/', 'plot');
	$data_colors = array('SkyBlue', 'green', 'blue', 'red', 'violet', 'azure1', 'yellow', 'DarkGreen');


	// Grab the data from the database
	// get all protocols
	$q = $dbh->prepare('SELECT IPProto, SUM(Bytes) AS TotalBytes
			FROM Flows
			WHERE TimeStop BETWEEN ? AND ?
			AND FlowSrc = ?
			GROUP BY IPProto
			ORDER BY TotalBytes DESC
			LIMIT 0, 9');
	$q->bindParam(1, $starttime, PDO::PARAM_INT);
	$q->bindParam(2, $endtime, PDO::PARAM_INT);
	$q->bindParam(3, sprintf('%u', ip2long($flowsrc)), PDO::PARAM_INT);
	$q->execute();

	$r = $q->fetchAll();

	// Build the data table and the legend
	$data = array();
	$legend = array();
	foreach($r as $row) {
		$proto = getprotobynumber($row[0]);
		$legend[] = $proto;
		$data[] = array($proto, $row[1]);
	}

	// Create the chart
	$plot = new PHPlot(800, 400);
	$plot->SetIsInline(True);
	//$plot->SetPrintImage(False);
	$plot->SetImageBorderType('plain');
	$plot->SetDataColors($data_colors);


	$plot->SetPlotType('pie');
	$plot->SetDataType('text-data-single');
	$plot->SetDataValues($data);

	$plot->SetTitle($chart_title);
	$plot->SetLegend($legend);

	$plot->SetOutputFile($output);
	$plot->DrawGraph();

	chmod($output, 0644);
	$target =  dirname($output).'/'.basename($output).'.png';
	if (rename($output, $target)) {
		return 'tmp/'.basename($target);
	} else {
		return False;
	}
}

