<?php

/*
** CBLM
** $Id: graph.php,v 1.17 2008/02/10 07:01:44 sella Exp $
** Copyright (c) 2005-2006 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

require('config/config.php');
require('menu.php');
require('db.php');

if (version_compare(phpversion(), "5.0.0", "<")) {
	include("libs/jpgraph-1.22/src/jpgraph.php");   
	include("libs/jpgraph-1.22/src/jpgraph_date.php");
	include("libs/jpgraph-1.22/src/jpgraph_bar.php");
	include("libs/jpgraph-1.22/src/jpgraph_line.php");
	include("libs/jpgraph-1.22/src/jpgraph_scatter.php");
	include("libs/jpgraph-1.22/src/jpgraph_regstat.php");
} else {
	include("libs/jpgraph-2.3/src/jpgraph.php");   
	include("libs/jpgraph-2.3/src/jpgraph_date.php");
	include("libs/jpgraph-2.3/src/jpgraph_bar.php");
	include("libs/jpgraph-2.3/src/jpgraph_line.php");
	include("libs/jpgraph-2.3/src/jpgraph_scatter.php");
	include("libs/jpgraph-2.3/src/jpgraph_regstat.php");
}

# Main - start
func();
# Main - end

function func() {
	if (!isset($_REQUEST['func'])) {
		$_REQUEST['func'] = 'view';
	}

	switch ($_REQUEST['func']) {
		case 'edit': /* Edit Screen */
			head();
			edit();
			foot();
			break;
		case 'commit': /* Modify Template Commit */
			head();
			if (isset($_REQUEST['graph_save'])) {
				graph_commit();
			} else if (isset($_REQUEST['graph_copy'])) {
				unset($_REQUEST['graph']);

				if (substr_count($_REQUEST['title'], "(copy", 0) < 1) {
					$_REQUEST['title'] = sprintf("%s (copy)", $_REQUEST['title']);
				} else {
					$_REQUEST['title'] = ereg_replace(" \(copy[^\)]*\)", "", $_REQUEST['title']);
					$_REQUEST['title'] = sprintf("%s (copy-%s)", $_REQUEST['title'], rand() % 999);
				}
				graph_commit();
			} else if (isset($_REQUEST['graph_delete'])) {
				graph_delete();
			} else if (isset($_REQUEST['template_load'])) {
			} else if (isset($_REQUEST['template_add'])) {
				template_add();
			} else if (isset($_REQUEST['template_delete'])) {
				template_delete();
			}
			edit();
			foot();
			break;
		case 'graph': /* Generate graph */
			if (version_compare(phpversion(), "5.0.0", "<")) {
				graph_jp1();
			} else {
				graph_jp2();
			}
			break;
		case 'view': /* View Screen */
		default:
			head();
			if (isset($_REQUEST['template_edit'])) {
				edit();
			} else {
				view();
			}
			foot();
			break;
	}
}

function graph_jp1() { /* Graph for JPGraph v1.x for PHP4. */
	global $config;

	$width = isset($_REQUEST['width']) ? $_REQUEST['width'] : $config['width'];
	$height = isset($_REQUEST['height']) ? $_REQUEST['height'] : $config['height'];
	$max_ds = isset($_REQUEST['max_ds']) ? $_REQUEST['max_ds'] : $config['max-ds'];
	$legend_count = 0;
	$has_y2 = false;

	$data = graph_data($_REQUEST['graph']);

	$graph = new Graph($width, $height, "auto");
	$graph->SetScale("datelin");
	//$graph->AdjBackgroundImage(0.4,0.7,-1); //setting BG type
	//$graph->SetBackgroundImage("linux_pez.png",BGIMG_FILLFRAME); //adding image

	if ($config['shadow']) {
		$graph->SetShadow();
	}

	$graph->title->Set($data['title']);
	$graph->xaxis->title->Set("time");
	$graph->xaxis->SetTitleMargin(35); 
	$graph->yaxis->title->Set("ms"); 
	$graph->yaxis->SetTitleMargin(38); 

	$graph->legend->Pos(0.5,0.97,"center","bottom");

	$graph->xaxis->SetLabelAngle($config['xasis-label-angle']);

	if ($data['secs'] == 86400) {
		$graph->xaxis->scale->SetDateFormat($config['date-format-long']);
	} else if ($data['secs'] == 3600) {
		if ($data['period'] > 6 * 86400) {
			$graph->xaxis->scale->SetDateFormat($config['date-format-long']);
		} else {
			$graph->xaxis->scale->SetDateFormat($config['date-format-medium']);
		}
	} else {
		$graph->xaxis->scale->SetDateFormat($config['date-format-short']);
	}

	/* Fix graph date/timestamp wonkines */
	$graph->xaxis->scale->SetTimeAlign(MINADJ_1);

	/* Setup major/minor tick coloring */
	$graph->xaxis->scale->ticks->SetColor($config['xaxis-tick-colors'][0], $config['xaxis-tick-colors'][1]); 
	$graph->yaxis->scale->ticks->SetColor($config['yaxis-tick-colors'][0], $config['yaxis-tick-colors'][1]); 

	/* Setup ygrid */
	if ($data['ygrid'] == 1 || $data['ygrid'] == 3) {
		$graph->ygrid->Show(true, false);
	} else if ($data['ygrid'] == 2 || $data['ygrid'] == 4) {
		$graph->ygrid->Show(true, true);
	} else {
		$graph->ygrid->Show(false, false);
	}

	/* Setup ygrid for Minor+ or Major+ */
	if ($data['ygrid'] == 3 || $data['ygrid'] == 4) {
		$graph->ygrid->SetFill(true, '#EFEFEF@0.5', '#BBCCFF@0.5');
	}

	/* Setup xgrid */
	if ($data['xgrid'] == 1 || $data['xgrid'] == 3) {
		$graph->xgrid->Show(true, false);
	} else if ($data['xgrid'] == 2 || $data['xgrid'] == 4) {
		$graph->xgrid->Show(true, true);
	} else {
		$graph->xgrid->Show(false, false);
	}

	/* Setup xgrid for Minor+ or Major+ */
	if ($data['xgrid'] == 3 || $data['xgrid'] == 4) {
		$graph->xgrid->SetFill(true, '#EFEFEF@0.5', '#BBCCFF@0.5');
	}

	/* Setup xaxis min */
	if ($data['xaxis_min'] == 1) {
		$graph->xaxis->SetPos('min');
	}

	/* Build plots */
	for ($i = 0; $i < count($data['ds']); $i++) {
		/* Skip DS without points since we can't display it. */
		if (empty($data['ds'][$i]['point'])) {
			continue;
		}

		switch ($data['ds'][$i]['type']) {
			default:
			case 'line':
				$plot[$i] = new LinePlot($data['ds'][$i]['point'], $data['ds'][$i]['timestamp']);

				if (strlen($data['ds'][$i]['mark']) > 0) {
					eval(sprintf('$mark = MARK_%s;', strtoupper($data['ds'][$i]['mark'])));
					$plot[$i]->mark->SetType($mark);
				}

				if (strlen($data['ds'][$i]['fill_color']) > 0) {
					$plot[$i]->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
					$plot[$i]->mark->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
				}

				if ($data['ds'][$i]['width'] > 0) {
					$plot[$i]->mark->SetWidth($data['ds'][$i]['width']);
				} else {
					$plot[$i]->mark->SetWidth(4);
				}

				break;

			case 'scatter':
				$plot[$i] = new ScatterPlot($data['ds'][$i]['point'], $data['ds'][$i]['timestamp']);

				if (strlen($data['ds'][$i]['mark']) > 0) {
					eval(sprintf('$mark = MARK_%s;', strtoupper($data['ds'][$i]['mark'])));
					$plot[$i]->mark->SetType($mark);
				}

				if ($data['ds'][$i]['impuls'] == 1) {
					$plot[$i]->SetImpuls();
				}
		
				if (strlen($data['ds'][$i]['fill_color']) > 0) {
					$plot[$i]->mark->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
				}

				if ($data['ds'][$i]['width'] > 0) {
					$plot[$i]->mark->SetWidth($data['ds'][$i]['width']);
				} else {
					$plot[$i]->mark->SetWidth(4);
				}

				break;

			case 'bar':
				$plot[$i] = new BarPlot($data['ds'][$i]['point'], $data['ds'][$i]['timestamp']);

				$plot[$i]->SetValuePos($config['bar-value-pos']); 

				if (strlen($data['ds'][$i]['fill_color']) > 0) {
					$plot[$i]->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
				}

				if ($data['ds'][$i]['width'] > 0) {
					$plot[$i]->SetWidth($data['ds'][$i]['width']);
				} else {
					$plot[$i]->SetWidth(4);
				}

				break;
		}

		/* Set common values */
		if (strlen($data['ds'][$i]['color']) > 0) {
			$plot[$i]->SetColor($data['ds'][$i]['color']);
		} else {
			$plot[$i]->SetColor($config['colors'][$i % count($config['colors'])]);
		}

		if ($data['ds'][$i]['weight'] > 0) {
			$plot[$i]->SetWeight($data['ds'][$i]['weight']);
		} else {
			$plot[$i]->SetWeight($config['weight']);
		}

		if (strlen($data['ds'][$i]['legend']) > 0) {
			$plot[$i]->SetLegend($data['ds'][$i]['legend']);
			$legend_count++;
		}

		if ($data['ds'][$i]['value'] == 1) {
			$plot[$i]->value->Show();
			if ($data['ds'][$i]['y2']) {
				$plot[$i]->value->SetColor($config['value-color-per']);
				$plot[$i]->value->SetFormat($config['value-format-per']);
			} else {
				$plot[$i]->value->SetColor($config['value-color-ms']);
				$plot[$i]->value->SetFormat($config['value-format-ms']);
			}
			if (strlen($config['value-angle']) > 0) {
				if ($config['truetype']) {
					$plot[$i]->value->SetFont(FF_ARIAL,FS_BOLD);
					$plot[$i]->value->SetAngle($config['value-angle']);
				} else if ($config['value-angle'] % 90 == 0) {
					$plot[$i]->value->SetAngle($config['value-angle']);
				}
			}
		}

		if ($data['allow_y2'] && $data['ds'][$i]['y2'] == 1) {
			$graph->SetY2Scale("lin");
			$graph->AddY2($plot[$i]);

			$graph->y2axis->title->Set("percent"); 
			$graph->y2axis->scale->ticks->SetColor($config['yaxis-tick-colors'][0], $config['yaxis-tick-colors'][1]); 
			$graph->y2axis->SetTitleMargin(32); 
			$has_y2 = true;
		} else if ($data['ds'][$i]['y2'] == 1) {
			$graph->Add($plot[$i]);
			$graph->yaxis->title->Set("percent"); 
		} else {
			$graph->Add($plot[$i]);
		}
	}

	/* Set Margins */
	if ($legend_count > 0 && $has_y2) {
		$graph->img->SetMargin(50, 50, 25, 75 + (16 * $legend_count));
	} else if ($legend_count > 0 && !$has_y2) {
		$graph->img->SetMargin(50, 25, 25, 75 + (16 * $legend_count));
	} else if ($has_y2) {
		$graph->img->SetMargin(50, 50, 25, 65);
	} else {
		$graph->img->SetMargin(50, 25, 25, 65);
	}

	/* Draw Graph */
	$graph->Stroke();
}

function graph_jp2() { /* Graph for JPGraph v2.x for PHP5. */
	global $config;

	$width = isset($_REQUEST['width']) ? $_REQUEST['width'] : $config['width'];
	$height = isset($_REQUEST['height']) ? $_REQUEST['height'] : $config['height'];
	$max_ds = isset($_REQUEST['max_ds']) ? $_REQUEST['max_ds'] : $config['max-ds'];
	$legend_count = 0;
	$has_y2 = false;

	$data = graph_data($_REQUEST['graph']);

	$graph = new Graph($width, $height, "auto");
	$graph->SetScale("datelin");
	//$graph->AdjBackgroundImage(0.4,0.7,-1); //setting BG type
	//$graph->SetBackgroundImage("linux_pez.png",BGIMG_FILLFRAME); //adding image

	if ($config['shadow']) {
		$graph->SetShadow();
	}

	$graph->title->Set($data['title']);
	$graph->xaxis->title->Set("time");
	$graph->xaxis->SetTitleMargin(35); 
	$graph->yaxis->title->Set("ms"); 
	$graph->yaxis->SetTitleMargin(38); 

	$graph->legend->Pos(0.5,0.97,"center","bottom");

	$graph->xaxis->SetLabelAngle($config['xasis-label-angle']);

	if ($data['secs'] == 86400) {
		$graph->xaxis->scale->SetDateFormat($config['date-format-long']);
	} else if ($data['secs'] == 3600) {
		if ($data['period'] > 6 * 86400) {
			$graph->xaxis->scale->SetDateFormat($config['date-format-long']);
		} else {
			$graph->xaxis->scale->SetDateFormat($config['date-format-medium']);
		}
	} else {
		$graph->xaxis->scale->SetDateFormat($config['date-format-short']);
	}

	/* Fix graph date/timestamp wonkines */
	$graph->xaxis->scale->SetTimeAlign(MINADJ_1);

	/* Setup major/minor tick coloring */
	$graph->xaxis->scale->ticks->SetColor($config['xaxis-tick-colors'][0], $config['xaxis-tick-colors'][1]); 
	$graph->yaxis->scale->ticks->SetColor($config['yaxis-tick-colors'][0], $config['yaxis-tick-colors'][1]); 

	/* Setup ygrid */
	if ($data['ygrid'] == 1 || $data['ygrid'] == 3) {
		$graph->ygrid->Show(true, false);
	} else if ($data['ygrid'] == 2 || $data['ygrid'] == 4) {
		$graph->ygrid->Show(true, true);
	} else {
		$graph->ygrid->Show(false, false);
	}

	/* Setup ygrid for Minor+ or Major+ */
	if ($data['ygrid'] == 3 || $data['ygrid'] == 4) {
		$graph->ygrid->SetFill(true, '#EFEFEF@0.5', '#BBCCFF@0.5');
	}

	/* Setup xgrid */
	if ($data['xgrid'] == 1 || $data['xgrid'] == 3) {
		$graph->xgrid->Show(true, false);
	} else if ($data['xgrid'] == 2 || $data['xgrid'] == 4) {
		$graph->xgrid->Show(true, true);
	} else {
		$graph->xgrid->Show(false, false);
	}

	/* Setup xgrid for Minor+ or Major+ */
	if ($data['xgrid'] == 3 || $data['xgrid'] == 4) {
		$graph->xgrid->SetFill(true, '#EFEFEF@0.5', '#BBCCFF@0.5');
	}

	/* Setup xaxis min */
	if ($data['xaxis_min'] == 1) {
		$graph->xaxis->SetPos('min');
	}

	/* Build plots */
	for ($i = 0; $i < count($data['ds']); $i++) {
		/* Skip DS without points since we can't display it. */
		if (empty($data['ds'][$i]['point'])) {
			continue;
		}

		switch ($data['ds'][$i]['type']) {
			default:
			case 'line':
				$plot[$i] = new LinePlot($data['ds'][$i]['point'], $data['ds'][$i]['timestamp']);

				if (strlen($data['ds'][$i]['mark']) > 0) {
					eval(sprintf('$mark = MARK_%s;', strtoupper($data['ds'][$i]['mark'])));
					$plot[$i]->mark->SetType($mark);
				}

				if (strlen($data['ds'][$i]['fill_color']) > 0) {
					$plot[$i]->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
					$plot[$i]->mark->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
				}

				if ($data['ds'][$i]['width'] > 0) {
					$plot[$i]->mark->SetWidth($data['ds'][$i]['width']);
				} else {
					$plot[$i]->mark->SetWidth(4);
				}

				break;

			case 'scatter':
				$plot[$i] = new ScatterPlot($data['ds'][$i]['point'], $data['ds'][$i]['timestamp']);

				if (strlen($data['ds'][$i]['mark']) > 0) {
					eval(sprintf('$mark = MARK_%s;', strtoupper($data['ds'][$i]['mark'])));
					$plot[$i]->mark->SetType($mark);
				}

				if ($data['ds'][$i]['impuls'] == 1) {
					$plot[$i]->SetImpuls();
				}
		
				if (strlen($data['ds'][$i]['fill_color']) > 0) {
					$plot[$i]->mark->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
				}

				if ($data['ds'][$i]['width'] > 0) {
					$plot[$i]->mark->SetWidth($data['ds'][$i]['width']);
				} else {
					$plot[$i]->mark->SetWidth(4);
				}

				break;

			case 'bar':
				$plot[$i] = new BarPlot($data['ds'][$i]['point'], $data['ds'][$i]['timestamp']);

				$plot[$i]->SetValuePos($config['bar-value-pos']); 

				if (strlen($data['ds'][$i]['fill_color']) > 0) {
					$plot[$i]->SetFillColor($data['ds'][$i]['fill_color'] . '@' . $data['ds'][$i]['fill_shade']);
				}

				if ($data['ds'][$i]['width'] > 0) {
					$plot[$i]->SetWidth($data['ds'][$i]['width']);
				} else {
					$plot[$i]->SetWidth(4);
				}

				break;
		}

		/* Set common values */
		if (strlen($data['ds'][$i]['color']) > 0) {
			$plot[$i]->SetColor($data['ds'][$i]['color']);
		} else {
			$plot[$i]->SetColor($config['colors'][$i % count($config['colors'])]);
		}

		if ($data['ds'][$i]['weight'] > 0) {
			$plot[$i]->SetWeight($data['ds'][$i]['weight']);
		} else {
			$plot[$i]->SetWeight($config['weight']);
		}

		if (strlen($data['ds'][$i]['legend']) > 0) {
			$plot[$i]->SetLegend($data['ds'][$i]['legend']);
			$legend_count++;
		}

		if ($data['ds'][$i]['value'] == 1) {
			$plot[$i]->value->Show();
			if ($data['ds'][$i]['y2']) {
				$plot[$i]->value->SetColor($config['value-color-per']);
				$plot[$i]->value->SetFormat($config['value-format-per']);
			} else {
				$plot[$i]->value->SetColor($config['value-color-ms']);
				$plot[$i]->value->SetFormat($config['value-format-ms']);
			}
			if (strlen($config['value-angle']) > 0) {
				if ($config['truetype']) {
					$plot[$i]->value->SetFont(FF_ARIAL,FS_BOLD);
					$plot[$i]->value->SetAngle($config['value-angle']);
				} else if ($config['value-angle'] % 90 == 0) {
					$plot[$i]->value->SetAngle($config['value-angle']);
				}
			}
		}

		if ($data['allow_y2'] && $data['ds'][$i]['y2'] == 1) {
			$graph->SetY2Scale("lin");
			$graph->AddY2($plot[$i]);

			$graph->y2axis->title->Set("percent"); 
			$graph->y2axis->scale->ticks->SetColor($config['yaxis-tick-colors'][0], $config['yaxis-tick-colors'][1]); 
			$graph->y2axis->SetTitleMargin(32); 
			$has_y2 = true;
		} else if ($data['ds'][$i]['y2'] == 1) {
			$graph->Add($plot[$i]);
			$graph->yaxis->title->Set("percent"); 
		} else {
			$graph->Add($plot[$i]);
		}
	}

	/* Set Margins */
	if ($legend_count > 0 && $has_y2) {
		$graph->img->SetMargin(50, 50, 25, 75 + (16 * $legend_count));
	} else if ($legend_count > 0 && !$has_y2) {
		$graph->img->SetMargin(50, 25, 25, 75 + (16 * $legend_count));
	} else if ($has_y2) {
		$graph->img->SetMargin(50, 50, 25, 65);
	} else {
		$graph->img->SetMargin(50, 25, 25, 65);
	}

	/* Draw Graph */
	$graph->Stroke();
}

function graph_data($graph) {
	global $config;

	$con = connect();

	$sql = sprintf("SELECT id, name, period, secs, probe_as, xgrid, ygrid, xaxis_min FROM graph_graph WHERE id = %d", $graph);
	if ($config['debug']) printf("SQL: %s<BR>", $sql);
	$result = mysql_query($sql);
	$graph = mysql_fetch_array($result, MYSQL_ASSOC);

	$data['title'] = $graph['name'];
	$data['period'] = $graph['period'];
	$data['secs'] = $graph['secs'];
	$data['probe_as'] = $graph['probe_as'];
	$data['xgrid'] = $graph['xgrid'];
	$data['ygrid'] = $graph['ygrid'];
	$data['xaxis_min'] = $graph['xaxis_min'];
	$data['allow_y2'] = 0;

	$sql = sprintf("SELECT ds, src, p_src.name src_host, dst, p_dst.name dst_host, tos, field, type, color, weight, fill_color, fill_shade, value, legend, width, impuls, mark FROM graph_ds LEFT JOIN probes AS p_src ON (src = p_src.ip) LEFT JOIN probes p_dst ON (dst = p_dst.ip) WHERE graph = %d", $graph['id']);
	if ($config['debug']) printf("SQL: %s<BR>", $sql);
	$ds_result = mysql_query($sql);
	while ($ds = mysql_fetch_array($ds_result, MYSQL_ASSOC)) {
		switch ($ds['field']) {
			case 'avail':
				$field = "SUM(rx)/SUM(tx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Availability";
				break;

			case 'loss':
				$field = "100-(SUM(rx)/SUM(tx)*100) ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Packet Loss";
				break;

			case 'r_min':
				$field = "AVG(rtt_min)/1000.0 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "RTT Minimum";
				break;

			case 'r_max':
				$field = "AVG(rtt_max)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "RTT Maximum";
				break;

			case 'r_avg':
				$field = "AVG(rtt_avg)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "RTT Average";
				break;

			case 'r_per':
				$field = "AVG(rtt_min)/AVG(rtt_avg)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "RTT Percentage";
				break;

			case 'o_min':
				$field = "AVG(ott_min)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "OTT Minimum";
				break;

			case 'o_max':
				$field = "AVG(ott_max)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "OTT Maximum";
				break;

			case 'o_avg':
				$field = "AVG(ott_avg)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "OTT Average";
				break;

			case 'o_per':
				$field = "AVG(ott_min)/AVG(ott_avg)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "OTT Percentage";
				break;

			case 'j_min':
				$field = "AVG(jtr_min)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Jitter Minimum";
				break;

			case 'j_max':
				$field = "AVG(jtr_max)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Jitter Maximum";
				break;

			case 'j_avg':
				$field = "AVG(jtr_avg)/1000 ds";
				$data['allow_y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Jitter Average";
				break;

			case 'j_per':
				$field = "AVG(jtr_min)/AVG(jtr_avg)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Jitter Percentage";
				break;

			case 't_paz':
				$field = "SUM(tos_a2z)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "ToS A to Z";
				break;

			case 't_pza':
				$field = "SUM(tos_z2a)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "ToS Z to A";
				break;

			case 't_faz':
				$field = "SUM(tos_a2z)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "ToS A to Z";
				break;

			case 't_fza':
				$field = "SUM(tos_z2a)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "ToS Z to A";
				break;

			case 'p_faz':
				$field = "SUM(pri_a2z)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Priority A to Z";
				break;

			case 'p_fza':
				$field = "SUM(pri_z2a)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Priority Z to A";
				break;

			case 'p_paz':
				$field = "SUM(pri_a2z)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Priority A to Z";
				break;

			case 'p_pza':
				$field = "SUM(pri_z2a)/SUM(rx)*100 ds";
				$data['ds'][$ds['ds']]['y2'] = 1;
				$data['ds'][$ds['ds']]['legend'] = "Priority Z to A";
				break;
		}

		if ($ds['src'] > 0) {
			$sql_src = sprintf("src = %s AND", $ds['src']);
		} else {
			$sql_src = '';
		}

		if ($ds['dst'] > 0) {
			$sql_dst = sprintf("dst = %s AND", $ds['dst']);
		} else {
			$sql_dst = '';
		}

		$sql = sprintf("SELECT %s, UNIX_TIMESTAMP(timestamp) - SECOND(timestamp) timestamp FROM data WHERE %s %s secs = %d AND timestamp > NOW() - %d GROUP BY UNIX_TIMESTAMP(timestamp) - SECOND(timestamp) ORDER BY timestamp", $field, $sql_src, $sql_dst, $graph['secs'], $graph['period']);

		if ($config['debug']) printf("SQL: %s<BR>", $sql);
		$result = mysql_query($sql);
		while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$data['ds'][$ds['ds']]['point'][] = (float) $line['ds'];
			$data['ds'][$ds['ds']]['timestamp'][] = (int) $line['timestamp'];
		}
		$data['ds'][$ds['ds']]['src'] = $ds['src'];
		$data['ds'][$ds['ds']]['dst'] = $ds['dst'];
		$data['ds'][$ds['ds']]['tos'] = $ds['tos'];
		$data['ds'][$ds['ds']]['field'] = $ds['field'];
		$data['ds'][$ds['ds']]['type'] = $ds['type'];
		$data['ds'][$ds['ds']]['color'] = $ds['color'];
		$data['ds'][$ds['ds']]['weight'] = $ds['weight'];
		$data['ds'][$ds['ds']]['fill_color'] = $ds['fill_color'];
		$data['ds'][$ds['ds']]['fill_shade'] = $ds['fill_shade'];
		$data['ds'][$ds['ds']]['value'] = $ds['value'];
		$data['ds'][$ds['ds']]['width'] = $ds['width'];
		$data['ds'][$ds['ds']]['impuls'] = $ds['impuls'];
		$data['ds'][$ds['ds']]['mark'] = $ds['mark'];

		if ($ds['legend'] == 1) {
			$x = $data['ds'][$ds['ds']]['legend'];

			if (isset($ds['dst_host'])) {
				$data['ds'][$ds['ds']]['legend'] = sprintf("%s to %s %s", $ds['src_host'], $ds['dst_host'], $x);
			} else {
				$data['ds'][$ds['ds']]['legend'] = sprintf("%s to All %s", $ds['src_host'], $x);
			}
		} else {
			$data['ds'][$ds['ds']]['legend'] = "";
		}
	}

	if ($config['debug']) {
		printf("Data: ");
		print_r($data);
		printf("<BR>\n");
	}

	return $data;
}

function view() {
	global $config;

	$con = connect();

	$rows = isset($_REQUEST['rows']) ? $_REQUEST['rows'] : $config['rows'];
	$width = isset($_REQUEST['width']) ? $_REQUEST['width'] : $config['width'];
	$height = isset($_REQUEST['height']) ? $_REQUEST['height'] : $config['height'];
	$refresh = isset($_REQUEST['refresh']) ? $_REQUEST['refresh'] : $config['refresh'];

	printf("<TABLE ALIGN=center><TR><TD ALIGN=center><FORM>\n");
	printf("<INPUT TYPE=hidden NAME=\"func\" VALUE=\"view\">");
	printf("<INPUT TYPE=hidden NAME=\"rand\" VALUE=\"%s\">", rand());

	$sql = "SELECT id, name FROM graph_template";
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	if (mysql_num_rows($result) < 1) {
		$sql = "INSERT INTO graph_template (name) VALUES ('default')";
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$sql = "SELECT id, name FROM graph_template";
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$_REQUEST['template'] = $line['id'];
		$result = mysql_query($sql);
	} else if (!isset($_REQUEST['template']) || $_REQUEST['template'] < 1) {/* Select one, if not selected */
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$_REQUEST['template'] = $line['id'];
		$result = mysql_query($sql);
	}

	printf("Template <SELECT NAME=\"template\">\n");
	while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
		printf("<OPTION %s VALUE=\"%d\">%s</OPTION>\n", $_REQUEST['template'] == $line['id'] ? 'SELECTED' : '', $line['id'], $line['name']);
	}
	printf("</SELECT>");
	printf("&nbsp;<INPUT VALUE=\"Load\" TYPE=\"submit\">\n");
	printf("&nbsp;<INPUT NAME=\"template_edit\" VALUE=\"Edit\" TYPE=\"submit\">\n");

	printf("&nbsp;Width <INPUT NAME=\"width\" VALUE=\"%s\" SIZE=4>", $width);
	printf("&nbsp;Height <INPUT NAME=\"height\" VALUE=\"%s\" SIZE=4>", $height);

	printf("&nbsp;Rows <SELECT NAME=\"rows\">\n");
	for ($i = 1; $i < 10; $i++) {
		printf("<OPTION %s VALUE=\"%d\">%d</OPTION>\n", $rows == $i ? 'SELECTED' : '', $i, $i);
	}
	printf("</SELECT>");

	printf("&nbsp;Refresh <SELECT NAME=\"refresh\">\n");
	printf("<OPTION %s VALUE=\"60\">1 min</OPTION>\n", $refresh == 60 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"300\">5 min</OPTION>\n", $refresh == 300 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"900\">15 min</OPTION>\n", $refresh == 900 ? 'SELECTED' : '');
	if ($refresh != 60 && $refresh != 300 && $refresh != 900) {
		printf("<OPTION SELECTED VALUE=\"%s\">%s sec</OPTION>\n", $refresh, $refresh);
	}
	printf("</SELECT>");

	printf("&nbsp;<INPUT VALUE=\"Submit\" TYPE=\"submit\">\n");
	printf("</B></FORM></TD>\n");
	printf("</FORM></TD></TR></TABLE>\n<P>\n");

	$sql = sprintf("SELECT id FROM graph_graph WHERE template = %d", $_REQUEST['template']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	if (mysql_num_rows($result) < 1) {
		printf("<CENTER><B>[ No graphs configured. <A HREF=\"%s?func=edit&template=%d&rand=%d\">Edit</A> template to add graphs. ]</B></CENTER>\n", $_SERVER['PHP_SELF'], $_REQUEST['template'], rand());

		return;
	}

	printf("<TABLE ALIGN=center>\n");

	$i = 0;
	while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
		if ($i % $rows == 0) {
			printf("<TR>");
		}

		printf("<TD><IMG SRC=\"%s?func=graph&graph=%d&height=%d&width=%d\"></TD>", $_SERVER['PHP_SELF'],$line['id'], $height, $width);

		if ($i % $rows == $rows - 1) {
			printf("</TR>");
		}
		$i++;
	}

	printf("</TABLE>\n");
}

function template_delete() {
	global $config;

	$con = connect();

	if ($config['debug']) {
		while (list($var, $val) = each($_REQUEST)) {
			if (is_array($val)) {
				printf("Var: %s, Val: ", $var);
				print_r($val);
				printf("<BR>\n");
			} else {
				printf("Var: %s, Val: %s<BR>\n", $var, $val);
			}
		}
	}

	$sql = sprintf("SELECT id FROM graph_graph WHERE template = %d", $_REQUEST['template']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
		$sql = sprintf("DELETE FROM graph_graph WHERE id = %d", $line['id']);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		mysql_query($sql);

		$sql = sprintf("DELETE FROM graph_ds WHERE graph = %d", $line['id']);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		mysql_query($sql);
	}

	$sql = sprintf("DELETE FROM graph_template WHERE id = %d", $_REQUEST['template']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	mysql_query($sql);

	/* Update template for display in edit() */
	$sql = "SELECT id FROM graph_template LIMIT 1";
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	$_REQUEST['template'] = $line['id'];
}
function graph_delete() {
	global $config;

	$con = connect();

	if ($config['debug']) {
		while (list($var, $val) = each($_REQUEST)) {
			if (is_array($val)) {
				printf("Var: %s, Val: ", $var);
				print_r($val);
				printf("<BR>\n");
			} else {
				printf("Var: %s, Val: %s<BR>\n", $var, $val);
			}
		}
	}

	$sql = sprintf("DELETE FROM graph_graph WHERE id = %d", $_REQUEST['graph']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);

	$sql = sprintf("DELETE FROM graph_ds WHERE graph = %d", $_REQUEST['graph']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);

	/* Update graph for display in edit() */
	$_REQUEST['graph'] = 0;
}

function template_add() {
	global $config;

	$con = connect();

	if (strlen($_REQUEST['template_name']) < 1) {
		$_REQUEST['template_name'] = sprintf("template-%d", rand() % 999);
	}

	/* Get template id */
	$sql = sprintf("SELECT id FROM graph_template WHERE name = '%s'", $_REQUEST['template_name']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	if (mysql_num_rows($result) > 0) {
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$template = $line['id'];
	} else {
		$sql = sprintf("INSERT INTO graph_template (name) VALUES ('%s')", $_REQUEST['template_name']);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$sql = sprintf("SELECT id FROM graph_template WHERE name = '%s'", $_REQUEST['template_name']);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$template = $line['id'];
	}

	/* Update template for display in edit() */
	$_REQUEST['template'] = $template;
}

function graph_commit() {
	global $config;

	$con = connect();

	/* Sanitize Data */
	if (strlen($_REQUEST['title']) < 1 || !strcmp($_REQUEST['title'], "New Graph")) {
		$_REQUEST['title'] = sprintf("graph-%d", rand() % 999);
	}

	if ($config['debug']) {
		while (list($var, $val) = each($_REQUEST)) {
			if (is_array($val)) {
				printf("Var: %s, Val: ", $var);
				print_r($val);
				printf("<BR>\n");
			} else {
				printf("Var: %s, Val: %s<BR>\n", $var, $val);
			}
		}
	}

	/* Get graph id */
	$sql = sprintf("SELECT id FROM graph_graph WHERE id = %d", $_REQUEST['graph']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	if (mysql_num_rows($result) > 0) {
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$graph = $line['id'];
		/* Update graph data */
		$sql = sprintf("UPDATE graph_graph SET name = '%s', period = %d, secs = %d, probe_as = %d, xgrid = %d, ygrid = %d, xaxis_min = %d WHERE id = %d", $_REQUEST['title'], $_REQUEST['period'], $_REQUEST['secs'], $_REQUEST['probe_as'], $_REQUEST['xgrid'], $_REQUEST['ygrid'], $_REQUEST['xaxis_min'], $graph);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
	} else {
		$sql = sprintf("INSERT INTO graph_graph (template, name, period, secs, probe_as, xgrid, ygrid, xaxis_min) VALUES (%d, '%s', %d, %d, %d, %d, %d, %d)", $_REQUEST['template'], $_REQUEST['title'], $_REQUEST['period'], $_REQUEST['secs'], $_REQUEST['probe_as'], $_REQUEST['xgrid'], $_REQUEST['ygrid'], $_REQUEST['xaxis_min']);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$sql = sprintf("SELECT id FROM graph_graph WHERE name = '%s' AND template = %d", $_REQUEST['title'], $_REQUEST['template']);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$graph = $line['id'];
	}

	/* Loop though data */
	for ($i = 0; $i < count($_REQUEST['src']); $i++) {
		$add = true;
		if ($_REQUEST['src'][$i] == 0) {
			$add = false;
		} else if ($_REQUEST['dst'][$i] == 0) {
			printf("<CENTER><B>DS%d invalid - no destination selected<BR>\n", $i);
			$add = false;
		} else if (strlen($_REQUEST['f'][$i]) < 1) {
			printf("<CENTER><B>DS%d invalid - no field selected<BR>\n", $i);
			$add = false;
		} else if ($_REQUEST['src'][$i] == $_REQUEST['dst'][$i]) {
			printf("<CENTER><B>DS%d invalid - source matches destination<BR>\n", $i);
			$add = false;
		}

		/* Remove old ds */
		$sql = sprintf("DELETE FROM graph_ds WHERE ds = %d AND graph = %d", $i, $graph);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);

		if ($add) {
			$sql = sprintf("INSERT INTO graph_ds (graph, ds, src, dst, tos, field, type, color, weight, fill_color, fill_shade, value, width, legend, impuls, mark) VALUES (%d, %d, %s, %s, '%s', '%s','%s', '%s', %d, '%s', '%s', %d, %d, %d, %d, '%s')", $graph, $i, $_REQUEST['src'][$i], $_REQUEST['dst'][$i], $_REQUEST['tos'][$i], $_REQUEST['f'][$i], $_REQUEST['type'][$i], $_REQUEST['color'][$i], $_REQUEST['weight'][$i], $_REQUEST['fill_color'][$i], $_REQUEST['fill_shade'][$i], $_REQUEST['value'][$i], $_REQUEST['width'][$i], $_REQUEST['legend'][$i], $_REQUEST['impuls'][$i], $_REQUEST['mark'][$i]);
			if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
			$result = mysql_query($sql);
		}
	}

	/* Update graph for display in mod() */
	$_REQUEST['graph'] = $graph;
}

function edit() {
	global $config;

	$con = connect();
	$max_ds = isset($_REQUEST['max_ds']) ? $_REQUEST['max_ds'] : $config['max-ds'];

	if (!isset($_REQUEST['period'])) {
		list($_REQUEST['period'],) = each($config['periods']);
		reset($config['periods']);
	}

	/* Template Form */
	printf("<TABLE ALIGN=center><FORM><TR><TD BGCOLOR=c9c9c9><B>\n");
	printf("<INPUT TYPE=hidden NAME=\"func\" VALUE=\"commit\">");
	printf("<INPUT TYPE=hidden NAME=\"rand\" VALUE=\"%s\">", rand());

	$sql = "SELECT id, name FROM graph_template";
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	if (mysql_num_rows($result) < 1) {
		$sql = "INSERT INTO graph_template (name) VALUES ('default')";
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$sql = "SELECT id, name FROM graph_template";
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$_REQUEST['template'] = $line['id'];
		$result = mysql_query($sql);
	} else if (!isset($_REQUEST['template']) || $_REQUEST['template'] < 1) {/* Select one, if not selected */
		$line = mysql_fetch_array($result, MYSQL_ASSOC);
		$_REQUEST['template'] = $line['id'];
		$result = mysql_query($sql);
	}

	printf("Template <SELECT NAME=\"template\">\n");
	while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
		printf("<OPTION %s VALUE=\"%d\">%s</OPTION>\n", $_REQUEST['template'] == $line['id'] ? 'SELECTED' : '', $line['id'], $line['name']);
	}
	printf("</SELECT>");
	printf("&nbsp;<INPUT NAME=\"template_load\" VALUE=\"Load\" TYPE=\"submit\">\n");
	printf("&nbsp;<INPUT NAME=\"template_delete\" VALUE=\"Delete\" TYPE=\"submit\"></TD>\n");
	printf("<TD BGCOLOR=c9c9c9><B>&nbsp;Template <INPUT NAME=\"template_name\" VALUE=\"\" SIZE=25>");
	printf("&nbsp;<INPUT NAME=\"template_add\" VALUE=\"Add\" TYPE=\"submit\">\n");
	printf("</B></TD></TR></FORM></TABLE><P>");

	/* Graph Form */
	printf("<TABLE WIDTH=1%% ALIGN=\"CENTER\"><FORM>\n");
	printf("<INPUT TYPE=hidden NAME=\"func\" VALUE=\"commit\">");
	printf("<INPUT TYPE=hidden NAME=\"rand\" VALUE=\"%s\">", rand());
	printf("<INPUT TYPE=hidden NAME=\"graph\" VALUE=\"%s\">", $_REQUEST['graph']);
	printf("<INPUT TYPE=hidden NAME=\"template\" VALUE=\"%s\">", $_REQUEST['template']);

	/* Select Graph */
	printf("<TR><TD COLSPAN=2 BGCOLOR=#999999 ALIGN=center><B>");
	$sql = sprintf("SELECT id, name FROM graph_graph WHERE template = %d", $_REQUEST['template']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
		if ($_REQUEST['graph'] == $line['id']) {
			printf("[>%s<] ", $line['name']);
		} else {
			printf("[ <A HREF=\"?func=edit&template=%s&graph=%d&rand=%d\">%s</A> ] \n", $_REQUEST['template'], $line['id'], rand(), $line['name']);
		}
	}
	if ($_REQUEST['graph'] == 0) {
		printf("[>New Graph<]");
	} else {
		printf("[ <A HREF=\"?func=edit&template=%s&graph=0&rand=%d\">New Graph</A> ]", $_REQUEST['template'], rand());
	}
	printf("</B></TD></TR>\n");

	/* Load DS from DB */
	$sql = sprintf("SELECT ds, src, dst, tos, field, type, color, weight, fill_color, fill_shade, value, width, legend, impuls, mark FROM graph_ds WHERE graph = %d", $_REQUEST['graph']);
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);

	$max_ds = (mysql_num_rows($result) > $max_ds) ? mysql_num_rows($result) : $max_ds;

	while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
		$ds['src'][$line['ds']] = $line['src'];
		$ds['dst'][$line['ds']] = ($line['dst'] == 0) ? -1 : $line['dst'];
		$ds['tos'][$line['ds']] = $line['tos'];
		$ds['f'][$line['ds']] = $line['field'];
		$ds['type'][$line['ds']] = $line['type'];
		$ds['color'][$line['ds']] = $line['color'];
		$ds['weight'][$line['ds']] = $line['weight'];
		$ds['fill_color'][$line['ds']] = $line['fill_color'];
		$ds['fill_shade'][$line['ds']] = $line['fill_shade'];
		$ds['value'][$line['ds']] = $line['value'];
		$ds['width'][$line['ds']] = $line['width'];
		$ds['legend'][$line['ds']] = $line['legend'];
		$ds['impuls'][$line['ds']] = $line['impuls'];
		$ds['mark'][$line['ds']] = $line['mark'];
	}

	/* Graph Title */
	printf("<TR><TD NOWRAP COLSPAN=2 BGCOLOR=#999999 ALIGN=center>\n");
	if (isset($_REQUEST['graph']) && $_REQUEST['graph'] != 0) {
		$sql = sprintf("SELECT id, name, period, secs, probe_as, xgrid, ygrid, xaxis_min FROM graph_graph WHERE id = %d", $_REQUEST['graph']);
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		$graph = mysql_fetch_array($result, MYSQL_ASSOC);
	} else {
		$graph['name'] = 'New Graph';
		$graph['secs'] = 60;
		$graph['period'] = 3600;
		$graph['probe_as'] = 1;
		$graph['xgrid'] = 0;
		$graph['ygrid'] = 3;
		$graph['xaxis_min'] = 0;
	}
	printf("<B>Title <INPUT NAME=\"title\" VALUE=\"%s\" SIZE=20>", $graph['name']);

	/* Query database for Precision Values */
	$sql = "SELECT secs FROM data GROUP BY secs ORDER BY secs";
	if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
	$result = mysql_query($sql);
	printf("&nbsp;Precision <SELECT NAME=\"secs\">\n");
	while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
		if ($line['secs'] >= 86400) {
			$var = "day";
			$val = $line['secs'] / 86400;
		} else if ($line['secs'] >= 3600) {
			$var = "hour";
			$val = $line['secs'] / 3600;
		} else if ($line['secs'] >= 60) {
			$var = "min";
			$val = $line['secs'] / 60;
		} else {
			$var = "sec";
			$val = $line['secs'];
		}
		if (!is_float($val)) {
			printf("<OPTION %s VALUE=\"%d\">%d %s</OPTION>\n", $graph['secs'] == $line['secs'] ? 'SELECTED' : '', $line['secs'], $val, $var);
		} else {
			printf("<OPTION %s VALUE=\"%d\">%.1f %s</OPTION>\n", $graph['secs'] == $line['secs'] ? 'SELECTED' : '', $line['secs'], $val, $var);
		}
		printf("Rsecs: %s, Lsecs: %s<BR>", $graph['secs'], $line['secs']);
	}
	printf("</SELECT>");

	/* Period */
	printf("&nbsp;Period <SELECT NAME=\"period\">\n");
	printf("<OPTION VALUE=\"%s\">%s sec</OPTION>\n", $graph['period'], $graph['period']);
	while (list($int, $desc) = each($config['periods'])) {
		printf("<OPTION %s VALUE=\"%d\">%s</OPTION>\n", $graph['period'] == $int ? "SELECTED" : "", $int, $desc);
	}
	printf("</SELECT>");

	/* Probe As */
	printf("&nbsp;Probe <SELECT NAME=\"probe_as\">\n");
	printf("<OPTION %s VALUE=\"0\">IP</OPTION>\n", $graph['probe_as'] == 0 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"1\">Host</OPTION>\n", $graph['probe_as'] == 1 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"2\">Both</OPTION>\n", $graph['probe_as'] == 2 ? 'SELECTED' : '');
	printf("</SELECT>");

	/* Grid */
	printf("&nbsp;Grid X <SELECT NAME=\"xgrid\">\n");
	printf("<OPTION %s VALUE=\"0\">Off</OPTION>\n", $graph['xgrid'] == 0 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"1\">Major</OPTION>\n", $graph['xgrid'] == 1 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"2\">Minor</OPTION>\n", $graph['xgrid'] == 2 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"3\">Major+</OPTION>\n", $graph['xgrid'] == 3 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"4\">Minor+</OPTION>\n", $graph['xgrid'] == 4 ? 'SELECTED' : '');
	printf("</SELECT>");

	printf("&nbsp;Y <SELECT NAME=\"ygrid\">\n");
	printf("<OPTION %s VALUE=\"0\">Off</OPTION>\n", $graph['ygrid'] == 0 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"1\">Major</OPTION>\n", $graph['ygrid'] == 1 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"2\">Minor</OPTION>\n", $graph['ygrid'] == 2 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"3\">Major+</OPTION>\n", $graph['ygrid'] == 3 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"4\">Minor+</OPTION>\n", $graph['ygrid'] == 4 ? 'SELECTED' : '');
	printf("</SELECT>");

	/* X Axis */
	printf("&nbsp;XAxis <SELECT NAME=\"xaxis_min\">\n");
	printf("<OPTION %s VALUE=\"0\">Zero</OPTION>\n", $graph['xaxis_min'] == 0 ? 'SELECTED' : '');
	printf("<OPTION %s VALUE=\"1\">Min</OPTION>\n", $graph['xaxis_min'] == 1 ? 'SELECTED' : '');
	printf("</SELECT>");

	/* Max DS */
	printf("&nbsp;DS <SELECT NAME=\"max_ds\">\n");
	for ($i = 1; $i <= 20; $i++) {
		printf("<OPTION %s VALUE=\"%d\">%s</OPTION>\n", ($max_ds == $i) ? "SELECTED" : "", $i, $i);
	}
	printf("</SELECT>");

	printf("</B></TD></TR>\n");

	/* Loop though DSs */
	for ($i = 0; $i < $max_ds; $i++) {
		printf("<TR BGCOLOR=%s><TD NOWRAP><B>&nbsp;DS%d&nbsp;</B></TD><TD NOWRAP><B>", $config['columncolors'][$i % count($config['columncolors'])], $i);

		/* SRC */
		printf("&nbsp;Source <SELECT NAME=\"src[%d]\">\n", $i);
		if ($i > 0) {
			printf("<OPTION VALUE=\"\">None</OPTION>\n");
		}
		$sql = "SELECT ip ip_raw, INET_NTOA(ip) ip, name FROM probes";
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
			if (!strcmp($line['ip'], $line['name'])) {
				printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['src'][$i] == $line['ip_raw'] ? 'SELECTED' : '', $line['ip_raw'], $line['name']);
			} else {
				printf("<OPTION %s VALUE=\"%s\">%s (%s)</OPTION>\n", $ds['src'][$i] == $line['ip_raw'] ? 'SELECTED' : '', $line['ip_raw'], $line['ip'], $line['name']);
			}
		}
		printf("</SELECT>");

		/* DST */
		printf("&nbsp;Destination <SELECT NAME=\"dst[%d]\">\n", $i);
		if ($i > 0) {
			printf("<OPTION VALUE=\"\">None</OPTION>\n");
		}
		printf("<OPTION %s VALUE=\"-1\">All</OPTION>\n", $ds['dst'][$i] == -1 ? 'SELECTED' : '');
		$sql = "SELECT ip ip_raw, INET_NTOA(ip) ip, name FROM probes";
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
			if (!strcmp($line['ip'], $line['name'])) {
				printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['dst'][$i] == $line['ip_raw'] ? 'SELECTED' : '', $line['ip_raw'], $line['name']);
			} else {
				printf("<OPTION %s VALUE=\"%s\">%s (%s)</OPTION>\n", $ds['dst'][$i] == $line['ip_raw'] ? 'SELECTED' : '', $line['ip_raw'], $line['ip'], $line['name']);
			}
		}
		printf("</SELECT>");

		/* Query database for ToS/PRI Values */
		$sql = "SELECT tos, tos >> 2 dscp, pri FROM data GROUP BY tos, pri ORDER BY tos, pri";
		if ($config['debug']) printf("SQL: %s<BR>\n", $sql);
		$result = mysql_query($sql);
		printf("&nbsp;ToS/PRI <SELECT NAME=\"tos[%d]\">\n", $i);
		printf("<OPTION %s VALUE=\"-1\">any</OPTION>\n", $ds['tos'][$i][$i] == "-1" ? 'SELECTED' : '');
		while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
			printf("<OPTION %s VALUE=\"%d:%d\">%d / %d</OPTION>\n", $ds['tos'][$i] == $line['tos'] . ':' . $line['pri'] ? 'SELECTED' : '', $line['tos'], $line['pri'], $line['tos'], $line['pri']);
		}
		printf("</SELECT>");

		/* Data point */
		printf("&nbsp;Field <SELECT NAME=\"f[%d]\">\n", $i);
		if ($i > 0) {
			printf("<OPTION VALUE=\"\">None</OPTION>\n");
		}
		printf("<OPTION %s VALUE=\"loss\">Packet Loss</OPTION>\n", $ds['f'][$i] == 'loss' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"avail\">Availability</OPTION>\n", $ds['f'][$i] == 'avail' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"r_avg\">RTT Avgerage</OPTION>\n", $ds['f'][$i] == 'r_avg' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"r_min\">RTT Minimum</OPTION>\n", $ds['f'][$i] == 'r_min' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"r_max\">RTT Maximum</OPTION>\n", $ds['f'][$i] == 'r_max' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"r_per\">RTT Percentage</OPTION>\n", $ds['f'][$i] == 'r_per' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"o_avg\">OTT Average</OPTION>\n", $ds['f'][$i] == 'o_avg' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"o_min\">OTT Minimum</OPTION>\n", $ds['f'][$i] == 'o_min' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"o_max\">OTT Maximum</OPTION>\n", $ds['f'][$i] == 'o_max' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"o_per\">OTT Percentage</OPTION>\n", $ds['f'][$i] == 'o_per' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"j_avg\">Jitter Average</OPTION>\n", $ds['f'][$i] == 'j_avg' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"j_min\">Jitter Minimum</OPTION>\n", $ds['f'][$i] == 'j_min' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"j_max\">Jitter Maximum</OPTION>\n", $ds['f'][$i] == 'j_max' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"j_per\">Jitter Percentage</OPTION>\n", $ds['f'][$i] == 'j_per' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"t_faz\">ToS Marking Failure A to Z</OPTION>\n", $ds['f'][$i] == 't_faz' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"t_fza\">ToS Marking Failure Z to A</OPTION>\n", $ds['f'][$i] == 't_fza' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"t_paz\">ToS Percentage Failed A to Z</OPTION>\n", $ds['f'][$i] == 't_paz' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"t_pza\">ToS Percentage Failed Z to A</OPTION>\n", $ds['f'][$i] == 't_pza' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"p_faz\">Priority Marking Failure A to Z</OPTION>\n", $ds['f'][$i] == 'p_faz' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"p_fza\">Priority Marking Failure Z to A</OPTION>\n", $ds['f'][$i] == 'p_fza' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"p_paz\">Priority Percentage Failed A to Z</OPTION>\n", $ds['f'][$i] == 'p_paz' ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"p_pza\">Priority Percentage Failed Z to A</OPTION>\n", $ds['f'][$i] == 'p_pza' ? 'SELECTED' : '');
		printf("</SELECT>");
		printf("</TD></TR>\n");

		/* Visuals line 1 */
		printf("<TR BGCOLOR=%s><TD>&nbsp;</TD><TD NOWRAP ALIGN=right><FONT SIZE=-2>", $config['columncolors'][$i % count($config['columncolors'])]);

		/* Type */
		printf("&nbsp;Type <SELECT NAME=\"type[%d]\">\n", $i, $i);
		if ($i > 0) {
			printf("<OPTION VALUE=\"\">None</OPTION>\n");
		}
		reset($config['types']);
		while (list(,$type) = each($config['types'])) {
			printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['type'][$i] == $type ? 'SELECTED' : '', $type, $type);
		}
		printf("</SELECT>");

		/* Color */
		printf("&nbsp;Color <SELECT NAME=\"color[%d]\">\n", $i);
		if ($i > 0) {
			printf("<OPTION VALUE=\"\">None</OPTION>\n");
		}
		reset($config['colors']);
		while (list(,$color) = each($config['colors'])) {
			printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['color'][$i] == $color ? 'SELECTED' : '', $color, $color);
		}
		printf("</SELECT>");

		/* Weight */
		printf("&nbsp;Weight <SELECT NAME=\"weight[%d]\">\n", $i);
		for ($j = 1; $j < 6; $j++) {
			printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['weight'][$i] == $j ? 'SELECTED' : '', $j, $j);
		}
		printf("</SELECT>");

		/* Fill Color */
		printf("&nbsp;Fill <SELECT NAME=\"fill_color[%d]\">\n", $i);
		printf("<OPTION VALUE=\"\">None</OPTION>\n");
		reset($config['colors']);
		while (list(,$color) = each($config['colors'])) {
			printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['fill_color'][$i] == $color ? 'SELECTED' : '', $color, $color);
		}
		printf("</SELECT>");

		/* Fill Shade */
		printf("&nbsp;<SELECT NAME=\"fill_shade[%d]\">\n", $i);
		for ($j = 0.0; $j <= 1.0; $j += .1) {
			$c1 = sprintf("%0.1f", $ds['fill_shade'][$i]);
			$c2 = sprintf("%0.1f", $j);
			printf("<OPTION %s VALUE=\"%0.1f\">%0.1f</OPTION>\n", $c1 == $c2 ? 'SELECTED' : '', $j, $j);
		}
		printf("</SELECT>");

		/* Mark */
		printf("&nbsp;Mark <SELECT NAME=\"mark[%d]\">\n", $i);
		printf("<OPTION VALUE=\"\">None</OPTION>\n");
		reset($config['marks']);
		while (list(,$mark) = each($config['marks'])) {
			printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['mark'][$i] == $mark ? 'SELECTED' : '', $mark, $mark);
		}
		printf("</SELECT>");

		/* Width */
		printf("&nbsp;Width <SELECT NAME=\"width[%d]\">\n", $i);
		for ($j = 1; $j < 21; $j++) {
			printf("<OPTION %s VALUE=\"%s\">%s</OPTION>\n", $ds['width'][$i] == $j ? 'SELECTED' : '', $j, $j);
		}
		printf("</SELECT>");

		/* Impuls */
		printf("&nbsp;Impuls <SELECT NAME=\"impuls[%d]\">\n", $i);
		printf("<OPTION %s VALUE=\"0\">N</OPTION>\n", $ds['impuls'][$i] == 0 ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"1\">Y</OPTION>\n", $ds['impuls'][$i] == 1 ? 'SELECTED' : '');
		printf("</SELECT>");

		/* Value */
		printf("&nbsp;Value <SELECT NAME=\"value[%d]\">\n", $i);
		printf("<OPTION %s VALUE=\"0\">N</OPTION>\n", $ds['value'][$i] == 0 ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"1\">Y</OPTION>\n", $ds['value'][$i] == 1 ? 'SELECTED' : '');
		printf("</SELECT>");

		/* Legend */
		printf("&nbsp;Legend <SELECT NAME=\"legend[%d]\">\n", $i);
		printf("<OPTION %s VALUE=\"0\">N</OPTION>\n", $ds['legend'][$i] == 0 ? 'SELECTED' : '');
		printf("<OPTION %s VALUE=\"1\">Y</OPTION>\n", $ds['legend'][$i] == 1 ? 'SELECTED' : '');
		printf("</SELECT>");

		printf("</TD></TR>\n");
	}

	printf("<TR><TD COLSPAN=2 ALIGN=\"center\"><B><INPUT NAME=\"graph_save\" VALUE=\"Save\" TYPE=\"submit\"> &nbsp; <INPUT NAME=\"graph_copy\" VALUE=\"Copy\" TYPE=\"submit\"> &nbsp; <INPUT NAME=\"graph_delete\" VALUE=\"Delete\" TYPE=\"submit\"></B></TD></TR>\n");

	if ($_REQUEST['graph'] > 0) {
		printf("<TR><TD COLSPAN=2 ALIGN=\"center\">&nbsp;</TR>\n");
		printf("<TR><TD COLSPAN=2 ALIGN=\"center\">Preview of &quot;%s&quot;</TD></TR>\n", $graph['name']);
		printf("<TR><TD COLSPAN=2 ALIGN=\"center\"><IMG SRC=\"%s?func=graph&graph=%d&height=%d&width=%d\"></TD></TR>\n", $_SERVER['PHP_SELF'], $_REQUEST['graph'], $config['height'], $config['width']);
	}

	printf("</TABLE></FORM>\n");
}

function del() {
	printf("Del");

}

function head() {
	printf("<HTML>\n<HEAD><TITLE>CBLM Graph View</TITLE>");
	if (isset($_REQUEST['refresh']) && $_REQUEST['refresh'] >= 5) {
		$refresh = $_REQUEST['refresh'];
		printf("<META HTTP-EQUIV=\"Refresh\" CONTENT=%d>\n", $refresh);
	}
	printf("</HEAD>\n<BODY bgcolor=\"#FFFFFF\">\n");
	menu();
}

function foot() {
	global $config;

	printf("<DIV ALIGN=\"right\"><A HREF=\"%s\">%s %s</A></DIV>\n", $config['url'], $config['program'], $config['version']);
	printf("</BODY>\n</HTML>\n");
}

/*
 * Local Variables:
 * c-basic-offset: 3
 * tab-width: 3
 * End:
 * vim: noet ts=3 sw=3 sts=3
 */

?>
