Beispiel #1
0
function rrdtool_function_graph($local_graph_id, $rra_id, $graph_data_array, $rrd_struc = array()) {
	global $config, $consolidation_functions;

	include_once($config["library_path"] . "/cdef.php");
	include_once($config["library_path"] . "/graph_variables.php");
	include($config["include_path"] . "/global_arrays.php");

	/* set the rrdtool default font */
	if (read_config_option("path_rrdtool_default_font")) {
		putenv("RRD_DEFAULT_FONT=" . read_config_option("path_rrdtool_default_font"));
	}

	/* before we do anything; make sure the user has permission to view this graph,
	if not then get out */
	if ((read_config_option("auth_method") != 0) && (isset($_SESSION["sess_user_id"]))) {
		$access_denied = !(is_graph_allowed($local_graph_id));

		if ($access_denied == true) {
			return "GRAPH ACCESS DENIED";
		}
	}

	/* find the step and how often this graph is updated with new data */
	$ds_step = db_fetch_cell("select
		data_template_data.rrd_step
		from (data_template_data,data_template_rrd,graph_templates_item)
		where graph_templates_item.task_item_id=data_template_rrd.id
		and data_template_rrd.local_data_id=data_template_data.local_data_id
		and graph_templates_item.local_graph_id=$local_graph_id
		limit 0,1");
	$ds_step = empty($ds_step) ? 300 : $ds_step;

	/* if no rra was specified, we need to figure out which one RRDTool will choose using
	 * "best-fit" resolution fit algorithm */
	if (empty($rra_id)) {
		if ((empty($graph_data_array["graph_start"])) || (empty($graph_data_array["graph_end"]))) {
			$rra["rows"] = 600;
			$rra["steps"] = 1;
			$rra["timespan"] = 86400;
		}else{
			/* get a list of RRAs related to this graph */
			$rras = get_associated_rras($local_graph_id);

			if (sizeof($rras) > 0) {
				foreach ($rras as $unchosen_rra) {
					/* the timespan specified in the RRA "timespan" field may not be accurate */
					$real_timespan = ($ds_step * $unchosen_rra["steps"] * $unchosen_rra["rows"]);

					/* make sure the current start/end times fit within each RRA's timespan */
					if ( (($graph_data_array["graph_end"] - $graph_data_array["graph_start"]) <= $real_timespan) && ((time() - $graph_data_array["graph_start"]) <= $real_timespan) ) {
						/* is this RRA better than the already chosen one? */
						if ((isset($rra)) && ($unchosen_rra["steps"] < $rra["steps"])) {
							$rra = $unchosen_rra;
						}else if (!isset($rra)) {
							$rra = $unchosen_rra;
						}
					}
				}
			}

			if (!isset($rra)) {
				$rra["rows"] = 600;
				$rra["steps"] = 1;
			}
		}
	}else{
		$rra = db_fetch_row("select timespan,rows,steps from rra where id=$rra_id");
	}

	$seconds_between_graph_updates = ($ds_step * $rra["steps"]);

	$graph = db_fetch_row("select
		graph_local.host_id,
		graph_local.snmp_query_id,
		graph_local.snmp_index,
		graph_templates_graph.title_cache,
		graph_templates_graph.vertical_label,
		graph_templates_graph.slope_mode,
		graph_templates_graph.auto_scale,
		graph_templates_graph.auto_scale_opts,
		graph_templates_graph.auto_scale_log,
		graph_templates_graph.scale_log_units,
		graph_templates_graph.auto_scale_rigid,
		graph_templates_graph.auto_padding,
		graph_templates_graph.base_value,
		graph_templates_graph.upper_limit,
		graph_templates_graph.lower_limit,
		graph_templates_graph.height,
		graph_templates_graph.width,
		graph_templates_graph.image_format_id,
		graph_templates_graph.unit_value,
		graph_templates_graph.unit_exponent_value,
		graph_templates_graph.export
		from (graph_templates_graph,graph_local)
		where graph_local.id=graph_templates_graph.local_graph_id
		and graph_templates_graph.local_graph_id=$local_graph_id");

	/* lets make that sql query... */
	$graph_items = db_fetch_assoc("select
		graph_templates_item.id as graph_templates_item_id,
		graph_templates_item.cdef_id,
		graph_templates_item.text_format,
		graph_templates_item.value,
		graph_templates_item.hard_return,
		graph_templates_item.consolidation_function_id,
		graph_templates_item.graph_type_id,
		graph_templates_gprint.gprint_text,
		colors.hex,
		graph_templates_item.alpha,
		data_template_rrd.id as data_template_rrd_id,
		data_template_rrd.local_data_id,
		data_template_rrd.rrd_minimum,
		data_template_rrd.rrd_maximum,
		data_template_rrd.data_source_name,
		data_template_rrd.local_data_template_rrd_id
		from graph_templates_item
		left join data_template_rrd on (graph_templates_item.task_item_id=data_template_rrd.id)
		left join colors on (graph_templates_item.color_id=colors.id)
		left join graph_templates_gprint on (graph_templates_item.gprint_id=graph_templates_gprint.id)
		where graph_templates_item.local_graph_id=$local_graph_id
		order by graph_templates_item.sequence");

	/* +++++++++++++++++++++++ GRAPH OPTIONS +++++++++++++++++++++++ */

	/* define some variables */
	$scale = "";
	$rigid = "";
	$unit_value = "";
	$unit_exponent_value = "";
	$graph_legend = "";
	$graph_defs = "";
	$txt_graph_items = "";
	$text_padding = "";
	$greatest_text_format = 0;
	$last_graph_type = "";

	if ($graph["auto_scale"] == "on") {
		switch ($graph["auto_scale_opts"]) {
			case "1": /* autoscale ignores lower, upper limit */
				$scale = "--alt-autoscale" . RRD_NL;
				break;
			case "2": /* autoscale-max, accepts a given lower limit */
				$scale = "--alt-autoscale-max" . RRD_NL;
				if ( is_numeric($graph["lower_limit"])) {
					$scale .= "--lower-limit=" . $graph["lower_limit"] . RRD_NL;
				}
				break;
			case "3": /* autoscale-min, accepts a given upper limit */
				if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
					$scale = "--alt-autoscale-min" . RRD_NL;
					if ( is_numeric($graph["upper_limit"])) {
						$scale .= "--upper-limit=" . $graph["upper_limit"] . RRD_NL;
					}
				}
				break;
			case "4": /* auto_scale with limits */
				$scale = "--alt-autoscale" . RRD_NL;
				if ( is_numeric($graph["upper_limit"])) {
					$scale .= "--upper-limit=" . $graph["upper_limit"] . RRD_NL;
				}
				if ( is_numeric($graph["lower_limit"])) {
					$scale .= "--lower-limit=" . $graph["lower_limit"] . RRD_NL;
				}
				break;
		}
	}else{
		$scale =  "--upper-limit=" . $graph["upper_limit"] . RRD_NL;
		$scale .= "--lower-limit=" . $graph["lower_limit"] . RRD_NL;
	}

	if ($graph["auto_scale_log"] == "on") {
		$scale .= "--logarithmic" . RRD_NL;
	}

	/* --units=si only defined for logarithmic y-axis scaling, even if it doesn't hurt on linear graphs */
	if (($graph["scale_log_units"] == "on") &&
		($graph["auto_scale_log"] == "on")) {
		$scale .= "--units=si" . RRD_NL;
	}

	if ($graph["auto_scale_rigid"] == "on") {
		$rigid = "--rigid" . RRD_NL;
	}

	if (!empty($graph["unit_value"])) {
		if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
			$unit_value = "--y-grid=" . $graph["unit_value"] . RRD_NL;
		}else{
			$unit_value = "--unit=" . $graph["unit_value"] . RRD_NL;
		}
	}

	if (ereg("^[0-9]+$", $graph["unit_exponent_value"])) {
		$unit_exponent_value = "--units-exponent=" . $graph["unit_exponent_value"] . RRD_NL;
	}

	/*
	 * optionally you can specify and array that overrides some of the db's values, lets set
	 * that all up here
	 */

	/* override: graph start time */
	if ((!isset($graph_data_array["graph_start"])) || ($graph_data_array["graph_start"] == "0")) {
		$graph_start = -($rra["timespan"]);
	}else{
		$graph_start = $graph_data_array["graph_start"];
	}

	/* override: graph end time */
	if ((!isset($graph_data_array["graph_end"])) || ($graph_data_array["graph_end"] == "0")) {
		$graph_end = -($seconds_between_graph_updates);
	}else{
		$graph_end = $graph_data_array["graph_end"];
	}

	/* override: graph height (in pixels) */
	if (isset($graph_data_array["graph_height"])) {
		$graph_height = $graph_data_array["graph_height"];
	}else{
		$graph_height = $graph["height"];
	}

	/* override: graph width (in pixels) */
	if (isset($graph_data_array["graph_width"])) {
		$graph_width = $graph_data_array["graph_width"];
	}else{
		$graph_width = $graph["width"];
	}

	/* override: skip drawing the legend? */
	if (isset($graph_data_array["graph_nolegend"])) {
		$graph_legend = "--no-legend" . RRD_NL;
	}else{
		$graph_legend = "";
	}

	/* export options */
	if (isset($graph_data_array["export"])) {
		$graph_opts = read_config_option("path_html_export") . "/" . $graph_data_array["export_filename"] . RRD_NL;
	}else{
		if (empty($graph_data_array["output_filename"])) {
				$graph_opts = "-" . RRD_NL;
		}else{
			$graph_opts = $graph_data_array["output_filename"] . RRD_NL;
		}
	}

	/* setup date format */
	$date_fmt = read_graph_config_option("default_date_format");
	$datechar = read_graph_config_option("default_datechar");

	if ($datechar == GDC_HYPHEN) {
		$datechar = "-";
	}else {
		$datechar = "/";
	}

	switch ($date_fmt) {
		case GD_MO_D_Y:
			$graph_date = "m" . $datechar . "d" . $datechar . "Y H:i:s";
			break;
		case GD_MN_D_Y:
			$graph_date = "M" . $datechar . "d" . $datechar . "Y H:i:s";
			break;
		case GD_D_MO_Y:
			$graph_date = "d" . $datechar . "m" . $datechar . "Y H:i:s";
			break;
		case GD_D_MN_Y:
			$graph_date = "d" . $datechar . "M" . $datechar . "Y H:i:s";
			break;
		case GD_Y_MO_D:
			$graph_date = "Y" . $datechar . "m" . $datechar . "d H:i:s";
			break;
		case GD_Y_MN_D:
			$graph_date = "Y" . $datechar . "M" . $datechar . "d H:i:s";
			break;
	}

	/* display the timespan for zoomed graphs */
	if ((isset($graph_data_array["graph_start"])) && (isset($graph_data_array["graph_end"]))) {
		if (($graph_data_array["graph_start"] < 0) && ($graph_data_array["graph_end"] < 0)) {
			if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
				$graph_legend .= "COMMENT:\"From " . str_replace(":", "\:", date($graph_date, time()+$graph_data_array["graph_start"])) . " To " . str_replace(":", "\:", date($graph_date, time()+$graph_data_array["graph_end"])) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}else {
				$graph_legend .= "COMMENT:\"From " . date($graph_date, time()+$graph_data_array["graph_start"]) . " To " . date($graph_date, time()+$graph_data_array["graph_end"]) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}
		}else if (($graph_data_array["graph_start"] >= 0) && ($graph_data_array["graph_end"] >= 0)) {
			if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
				$graph_legend .= "COMMENT:\"From " . str_replace(":", "\:", date($graph_date, $graph_data_array["graph_start"])) . " To " . str_replace(":", "\:", date($graph_date, $graph_data_array["graph_end"])) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}else {
				$graph_legend .= "COMMENT:\"From " . date($graph_date, $graph_data_array["graph_start"]) . " To " . date($graph_date, $graph_data_array["graph_end"]) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}
		}
	}

	/* basic graph options */
	$graph_opts .=
		"--imgformat=" . $image_types{$graph["image_format_id"]} . RRD_NL .
		"--start=$graph_start" . RRD_NL .
		"--end=$graph_end" . RRD_NL .
		"--title=\"" . str_replace("\"", "\\\"", $graph["title_cache"]) . "\"" . RRD_NL .
		"$rigid" .
		"--base=" . $graph["base_value"] . RRD_NL .
		"--height=$graph_height" . RRD_NL .
		"--width=$graph_width" . RRD_NL .
		"$scale" .
		"$unit_value" .
		"$unit_exponent_value" .
		"$graph_legend" .
		"--vertical-label=\"" . $graph["vertical_label"] . "\"" . RRD_NL;

	/* rrdtool 1.2.x does not provide smooth lines, let's force it */
	if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
		if ($graph["slope_mode"] == "on") {
			$graph_opts .= "--slope-mode" . RRD_NL;
		}
	}

	/* rrdtool 1.2 font options */
	if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
		/* title fonts */
		$graph_opts .= rrdtool_set_font("title", ((!empty($graph_data_array["graph_nolegend"])) ? $graph_data_array["graph_nolegend"] : ""));

		/* axis fonts */
		$graph_opts .= rrdtool_set_font("axis");

		/* legend fonts */
		$graph_opts .= rrdtool_set_font("legend");

		/* unit fonts */
		$graph_opts .= rrdtool_set_font("unit");
	}

	$i = 0; $j = 0;
	$last_graph_cf = array();
	if (sizeof($graph_items) > 0) {

		/* we need to add a new column "cf_reference", so unless PHP 5 is used, this foreach syntax is required */
		foreach ($graph_items as $key => $graph_item) {
			/* mimic the old behavior: LINE[123], AREA and STACK items use the CF specified in the graph item */
			if (($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1) ||
				($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2) ||
				($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3) ||
				($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREA)  ||
				($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_STACK)) {
				$graph_cf = $graph_item["consolidation_function_id"];
				/* remember the last CF for this data source for use with GPRINT
				 * if e.g. an AREA/AVERAGE and a LINE/MAX is used
				 * we will have AVERAGE first and then MAX, depending on GPRINT sequence */
				$last_graph_cf["data_source_name"]["local_data_template_rrd_id"] = $graph_cf;
				/* remember this for second foreach loop */
				$graph_items[$key]["cf_reference"] = $graph_cf;
			}elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT) {
				/* ATTENTION!
				 * the "CF" given on graph_item edit screen for GPRINT is indeed NOT a real "CF",
				 * but an aggregation function
				 * see "man rrdgraph_data" for the correct VDEF based notation
				 * so our task now is to "guess" the very graph_item, this GPRINT is related to
				 * and to use that graph_item's CF */
				if (isset($last_graph_cf["data_source_name"]["local_data_template_rrd_id"])) {
					$graph_cf = $last_graph_cf["data_source_name"]["local_data_template_rrd_id"];
					/* remember this for second foreach loop */
					$graph_items[$key]["cf_reference"] = $graph_cf;
				} else {
					$graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
					/* remember this for second foreach loop */
					$graph_items[$key]["cf_reference"] = $graph_cf;
				}
			}else{
				/* all other types are based on the best matching CF */
				$graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
				/* remember this for second foreach loop */
				$graph_items[$key]["cf_reference"] = $graph_cf;
			}

			if ((!empty($graph_item["local_data_id"])) && (!isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$graph_cf]))) {
				/* use a user-specified ds path if one is entered */
				$data_source_path = get_data_source_path($graph_item["local_data_id"], true);

				/* FOR WIN32: Escape all colon for drive letters (ex. D\:/path/to/rra) */
				$data_source_path = str_replace(":", "\:", $data_source_path);

				if (!empty($data_source_path)) {
					/* NOTE: (Update) Data source DEF names are created using the graph_item_id; then passed
					to a function that matches the digits with letters. rrdtool likes letters instead
					of numbers in DEF names; especially with CDEF's. cdef's are created
					the same way, except a 'cdef' is put on the beginning of the hash */
					$graph_defs .= "DEF:" . generate_graph_def_name(strval($i)) . "=\"$data_source_path\":" . $graph_item["data_source_name"] . ":" . $consolidation_functions[$graph_cf] . RRD_NL;

					$cf_ds_cache{$graph_item["data_template_rrd_id"]}[$graph_cf] = "$i";

					$i++;
				}
			}

			/* cache cdef value here to support data query variables in the cdef string */
			if (empty($graph_item["cdef_id"])) {
				$graph_item["cdef_cache"] = "";
				$graph_items[$j]["cdef_cache"] = "";
			}else{
				$graph_item["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
				$graph_items[$j]["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
			}

			/* +++++++++++++++++++++++ LEGEND: TEXT SUBSITUTION (<>'s) +++++++++++++++++++++++ */

			/* note the current item_id for easy access */
			$graph_item_id = $graph_item["graph_templates_item_id"];

			/* the following fields will be searched for graph variables */
			$variable_fields = array(
				"text_format" => array(
					"process_no_legend" => false
					),
				"value" => array(
					"process_no_legend" => true
					),
				"cdef_cache" => array(
					"process_no_legend" => true
					)
				);

			/* loop through each field that we want to substitute values for:
			currently: text format and value */
			while (list($field_name, $field_array) = each($variable_fields)) {
				/* certain fields do not require values when the legend is not to be shown */
				if (($field_array["process_no_legend"] == false) && (isset($graph_data_array["graph_nolegend"]))) {
					continue;
				}

				$graph_variables[$field_name][$graph_item_id] = $graph_item[$field_name];

				/* date/time substitution */
				if (strstr($graph_variables[$field_name][$graph_item_id], "|date_time|")) {
					$graph_variables[$field_name][$graph_item_id] = str_replace("|date_time|", date('D d M H:i:s T Y', strtotime(db_fetch_cell("select value from settings where name='date'"))), $graph_variables[$field_name][$graph_item_id]);
				}

				/* data source title substitution */
				if (strstr($graph_variables[$field_name][$graph_item_id], "|data_source_title|")) {
					$graph_variables[$field_name][$graph_item_id] = str_replace("|data_source_title|", get_data_source_title($graph_item["local_data_id"]), $graph_variables[$field_name][$graph_item_id]);
				}

				/* data query variables */
				$graph_variables[$field_name][$graph_item_id] = rrd_substitute_host_query_data($graph_variables[$field_name][$graph_item_id], $graph, $graph_item);

				/* Nth percentile */
				if (preg_match_all("/\|([0-9]{1,2}):(bits|bytes):(\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\d)?\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
					foreach ($matches as $match) {
						$graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_nth_percentile($match, $graph_item, $graph_items, $graph_start, $graph_end), $graph_variables[$field_name][$graph_item_id]);
					}
				}

				/* bandwidth summation */
				if (preg_match_all("/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
					foreach ($matches as $match) {
						$graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_bandwidth_summation($match, $graph_item, $graph_items, $graph_start, $graph_end, $rra["steps"], $ds_step), $graph_variables[$field_name][$graph_item_id]);
					}
				}
			}

			/* if we are not displaying a legend there is no point in us even processing the auto padding,
			text format stuff. */
			if (!isset($graph_data_array["graph_nolegend"])) {
				/* set hard return variable if selected (\n) */
				if ($graph_item["hard_return"] == "on") {
					$hardreturn[$graph_item_id] = "\\n";
				}else{
					$hardreturn[$graph_item_id] = "";
				}

				/* +++++++++++++++++++++++ LEGEND: AUTO PADDING (<>'s) +++++++++++++++++++++++ */

				/* PADDING: remember this is not perfect! its main use is for the basic graph setup of:
				AREA - GPRINT-CURRENT - GPRINT-AVERAGE - GPRINT-MAXIMUM \n
				of course it can be used in other situations, however may not work as intended.
				If you have any additions to this small peice of code, feel free to send them to me. */
				if ($graph["auto_padding"] == "on") {
					/* only applies to AREA, STACK and LINEs */
					if (ereg("(AREA|STACK|LINE[123])", $graph_item_types{$graph_item["graph_type_id"]})) {
						$text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);

						if ($text_format_length > $greatest_text_format) {
							$greatest_text_format = $text_format_length;
						}
					}
				}
			}

			$j++;
		}
	}

	/* +++++++++++++++++++++++ GRAPH ITEMS: CDEF's +++++++++++++++++++++++ */

	$i = 0;
	reset($graph_items);

	/* hack for rrdtool 1.2.x support */
	$graph_item_stack_type = "";

	if (sizeof($graph_items) > 0) {
	foreach ($graph_items as $graph_item) {
		/* first we need to check if there is a DEF for the current data source/cf combination. if so,
		we will use that */
		if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}{$graph_item["consolidation_function_id"]})) {
			$cf_id = $graph_item["consolidation_function_id"];
		}else{
		/* if there is not a DEF defined for the current data source/cf combination, then we will have to
		improvise. choose the first available cf in the following order: AVERAGE, MAX, MIN, LAST */
			if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[1])) {
				$cf_id = 1; /* CF: AVERAGE */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[3])) {
				$cf_id = 3; /* CF: MAX */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[2])) {
				$cf_id = 2; /* CF: MIN */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[4])) {
				$cf_id = 4; /* CF: LAST */
			}else{
				$cf_id = 1; /* CF: AVERAGE */
			}
		}
		/* now remember the correct CF reference */
		$cf_id = $graph_item["cf_reference"];

		/* make cdef string here; a note about CDEF's in cacti. A CDEF is neither unique to a
		data source of global cdef, but is unique when those two variables combine. */
		$cdef_graph_defs = "";

		if ((!empty($graph_item["cdef_id"])) && (!isset($cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]))) {

			$cdef_string 	= $graph_variables["cdef_cache"]{$graph_item["graph_templates_item_id"]};
			$magic_item 	= array();
			$already_seen	= array();
			$sources_seen	= array();
			$count_all_ds_dups = 0;
			$count_all_ds_nodups = 0;
			$count_similar_ds_dups = 0;
			$count_similar_ds_nodups = 0;

			/* if any of those magic variables are requested ... */
			if (ereg("(ALL_DATA_SOURCES_(NO)?DUPS|SIMILAR_DATA_SOURCES_(NO)?DUPS)", $cdef_string) ||
				ereg("(COUNT_ALL_DS_(NO)?DUPS|COUNT_SIMILAR_DS_(NO)?DUPS)", $cdef_string)) {

				/* now walk through each case to initialize array*/
				if (ereg("ALL_DATA_SOURCES_DUPS", $cdef_string)) {
					$magic_item["ALL_DATA_SOURCES_DUPS"] = "";
				}
				if (ereg("ALL_DATA_SOURCES_NODUPS", $cdef_string)) {
					$magic_item["ALL_DATA_SOURCES_NODUPS"] = "";
				}
				if (ereg("SIMILAR_DATA_SOURCES_DUPS", $cdef_string)) {
					$magic_item["SIMILAR_DATA_SOURCES_DUPS"] = "";
				}
				if (ereg("SIMILAR_DATA_SOURCES_NODUPS", $cdef_string)) {
					$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] = "";
				}
				if (ereg("COUNT_ALL_DS_DUPS", $cdef_string)) {
					$magic_item["COUNT_ALL_DS_DUPS"] = "";
				}
				if (ereg("COUNT_ALL_DS_NODUPS", $cdef_string)) {
					$magic_item["COUNT_ALL_DS_NODUPS"] = "";
				}
				if (ereg("COUNT_SIMILAR_DS_DUPS", $cdef_string)) {
					$magic_item["COUNT_SIMILAR_DS_DUPS"] = "";
				}
				if (ereg("COUNT_SIMILAR_DS_NODUPS", $cdef_string)) {
					$magic_item["COUNT_SIMILAR_DS_NODUPS"] = "";
				}

				/* loop over all graph items */
				for ($t=0;($t<count($graph_items));$t++) {

					/* don't count any entry where a magic item was entered */
					if (ereg("(ALL_DATA_SOURCES_(NO)?DUPS|SIMILAR_DATA_SOURCES_(NO)?DUPS)", $graph_items[$t]["cdef_cache"]) ||
						ereg("(COUNT_ALL_DS_(NO)?DUPS|COUNT_SIMILAR_DS_(NO)?DUPS)", $graph_items[$t]["cdef_cache"])) {
						continue;
					}

					/* only work on graph items, omit GRPINTs, COMMENTs and stuff */
					if ((ereg("(AREA|STACK|LINE[123])", $graph_item_types{$graph_items[$t]["graph_type_id"]})) && (!empty($graph_items[$t]["data_template_rrd_id"]))) {
						/* if the user screws up CF settings, PHP will generate warnings if left unchecked */

						/* matching consolidation function? */
						if (isset($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id])) {
							$def_name = generate_graph_def_name(strval($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id]));

							/* do we need ALL_DATA_SOURCES_DUPS? */
							if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
								$magic_item["ALL_DATA_SOURCES_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
							}

							/* do we need COUNT_ALL_DS_DUPS? */
							if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
								$magic_item["COUNT_ALL_DS_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
							}

							$count_all_ds_dups++;

							/* check if this item also qualifies for NODUPS  */
							if(!isset($already_seen[$def_name])) {
								if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
									$magic_item["ALL_DATA_SOURCES_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
								}
								if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
									$magic_item["COUNT_ALL_DS_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
								}
								$count_all_ds_nodups++;
								$already_seen[$def_name]=TRUE;
							}

							/* check for SIMILAR data sources */
							if ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {

								/* do we need SIMILAR_DATA_SOURCES_DUPS? */
								if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"]) && ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"])) {
									$magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
								}

								/* do we need COUNT_SIMILAR_DS_DUPS? */
								if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"]) && ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"])) {
									$magic_item["COUNT_SIMILAR_DS_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
								}

								$count_similar_ds_dups++;

								/* check if this item also qualifies for NODUPS  */
								if(!isset($sources_seen{$graph_items[$t]["data_template_rrd_id"]})) {
									if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
										$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
									}
									if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"]) && ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"])) {
										$magic_item["COUNT_SIMILAR_DS_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
									}
									$count_similar_ds_nodups++;
									$sources_seen{$graph_items[$t]["data_template_rrd_id"]} = TRUE;
								}
							} # SIMILAR data sources
						} # matching consolidation function?
					} # only work on graph items, omit GRPINTs, COMMENTs and stuff
				} #  loop over all graph items

				/* if there is only one item to total, don't even bother with the summation.
				 * Otherwise cdef=a,b,c,+,+ is fine. */
				if ($count_all_ds_dups > 1 && isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
					$magic_item["ALL_DATA_SOURCES_DUPS"] .= str_repeat(",+", ($count_all_ds_dups - 2)) . ",+";
				}
				if ($count_all_ds_nodups > 1 && isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
					$magic_item["ALL_DATA_SOURCES_NODUPS"] .= str_repeat(",+", ($count_all_ds_nodups - 2)) . ",+";
				}
				if ($count_similar_ds_dups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
					$magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= str_repeat(",+", ($count_similar_ds_dups - 2)) . ",+";
				}
				if ($count_similar_ds_nodups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
					$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= str_repeat(",+", ($count_similar_ds_nodups - 2)) . ",+";
				}
				if ($count_all_ds_dups > 1 && isset($magic_item["COUNT_ALL_DS_DUPS"])) {
					$magic_item["COUNT_ALL_DS_DUPS"] .= str_repeat(",+", ($count_all_ds_dups - 2)) . ",+";
				}
				if ($count_all_ds_nodups > 1 && isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
					$magic_item["COUNT_ALL_DS_NODUPS"] .= str_repeat(",+", ($count_all_ds_nodups - 2)) . ",+";
				}
				if ($count_similar_ds_dups > 1 && isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
					$magic_item["COUNT_SIMILAR_DS_DUPS"] .= str_repeat(",+", ($count_similar_ds_dups - 2)) . ",+";
				}
				if ($count_similar_ds_nodups > 1 && isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
					$magic_item["COUNT_SIMILAR_DS_NODUPS"] .= str_repeat(",+", ($count_similar_ds_nodups - 2)) . ",+";
				}
			}

			$cdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval((isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id]) ? $cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id] : "0"))), $cdef_string);

			/* ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
			if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
				$cdef_string = str_replace("ALL_DATA_SOURCES_DUPS", $magic_item["ALL_DATA_SOURCES_DUPS"], $cdef_string);
			}
			if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
				$cdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $magic_item["ALL_DATA_SOURCES_NODUPS"], $cdef_string);
			}
			if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
				$cdef_string = str_replace("SIMILAR_DATA_SOURCES_DUPS", $magic_item["SIMILAR_DATA_SOURCES_DUPS"], $cdef_string);
			}
			if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
				$cdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $magic_item["SIMILAR_DATA_SOURCES_NODUPS"], $cdef_string);
			}

			/* COUNT_ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
			if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
				$cdef_string = str_replace("COUNT_ALL_DS_DUPS", $magic_item["COUNT_ALL_DS_DUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
				$cdef_string = str_replace("COUNT_ALL_DS_NODUPS", $magic_item["COUNT_ALL_DS_NODUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
				$cdef_string = str_replace("COUNT_SIMILAR_DS_DUPS", $magic_item["COUNT_SIMILAR_DS_DUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
				$cdef_string = str_replace("COUNT_SIMILAR_DS_NODUPS", $magic_item["COUNT_SIMILAR_DS_NODUPS"], $cdef_string);
			}

			/* data source item variables */
			$cdef_string = str_replace("CURRENT_DS_MINIMUM_VALUE", (empty($graph_item["rrd_minimum"]) ? "0" : $graph_item["rrd_minimum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_DS_MAXIMUM_VALUE", (empty($graph_item["rrd_maximum"]) ? "0" : $graph_item["rrd_maximum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MINIMUM_VALUE", (empty($graph["lower_limit"]) ? "0" : $graph["lower_limit"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MAXIMUM_VALUE", (empty($graph["upper_limit"]) ? "0" : $graph["upper_limit"]), $cdef_string);

			/* replace query variables in cdefs */
			$cdef_string = rrd_substitute_host_query_data($cdef_string, $graph, $graph_item);

			/* make the initial "virtual" cdef name: 'cdef' + [a,b,c,d...] */
			$cdef_graph_defs .= "CDEF:cdef" . generate_graph_def_name(strval($i)) . "=";
			$cdef_graph_defs .= $cdef_string;
			$cdef_graph_defs .= " \\\n";

			/* the CDEF cache is so we do not create duplicate CDEF's on a graph */
			$cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id] = "$i";
		}

		/* add the cdef string to the end of the def string */
		$graph_defs .= $cdef_graph_defs;

		/* note the current item_id for easy access */
		$graph_item_id = $graph_item["graph_templates_item_id"];

		/* if we are not displaying a legend there is no point in us even processing the auto padding,
		text format stuff. */
		if ((!isset($graph_data_array["graph_nolegend"])) && ($graph["auto_padding"] == "on")) {
			/* only applies to AREA, STACK and LINEs */
			if (ereg("(AREA|STACK|LINE[123])", $graph_item_types{$graph_item["graph_type_id"]})) {
				$text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);

				/* we are basing how much to pad on area and stack text format,
				not gprint. but of course the padding has to be displayed in gprint,
				how fun! */

				$pad_number = ($greatest_text_format - $text_format_length);
				//cacti_log("MAX: $greatest_text_format, CURR: $text_format_lengths[$item_dsid], DSID: $item_dsid");
				$text_padding = str_pad("", $pad_number);

			/* two GPRINT's in a row screws up the padding, lets not do that */
			} else if (($graph_item_types{$graph_item["graph_type_id"]} == "GPRINT") && ($last_graph_type == "GPRINT")) {
				$text_padding = "";
			}

			$last_graph_type = $graph_item_types{$graph_item["graph_type_id"]};
		}

		/* we put this in a variable so it can be manipulated before mainly used
		if we want to skip it, like below */
		$current_graph_item_type = $graph_item_types{$graph_item["graph_type_id"]};

		/* IF this graph item has a data source... get a DEF name for it, or the cdef if that applies
		to this graph item */
		if ($graph_item["cdef_id"] == "0") {
			if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id])) {
				$data_source_name = generate_graph_def_name(strval($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id]));
			}else{
				$data_source_name = "";
			}
		}else{
			$data_source_name = "cdef" . generate_graph_def_name(strval($cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]));
		}

		/* to make things easier... if there is no text format set; set blank text */
		if (!isset($graph_variables["text_format"][$graph_item_id])) {
			$graph_variables["text_format"][$graph_item_id] = "";
		}

		if (!isset($hardreturn[$graph_item_id])) {
			$hardreturn[$graph_item_id] = "";
		}

		/* +++++++++++++++++++++++ GRAPH ITEMS +++++++++++++++++++++++ */

		/* most of the calculations have been done above. now we have for print everything out
		in an RRDTool-friendly fashion */

		$need_rrd_nl = TRUE;

		if ($graph_item_types{$graph_item["graph_type_id"]} == "COMMENT") {
			if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
				$comment_string = $graph_item_types{$graph_item["graph_type_id"]} . ":\"" . str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]) . $hardreturn[$graph_item_id] . "\" ";
				if (trim($comment_string) == 'COMMENT:"\n"') {
					$txt_graph_items .= 'COMMENT:" \n"'; # rrdtool will skip a COMMENT that holds a NL only; so add a blank to make NL work
				} else if (trim($comment_string) != "COMMENT:\"\"") {
					$txt_graph_items .= rrd_substitute_host_query_data($comment_string, $graph, $graph_item);
				}
			}else {
				$comment_string = $graph_item_types{$graph_item["graph_type_id"]} . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
				if (trim($comment_string) == 'COMMENT:"\n"') {
					$txt_graph_items .= 'COMMENT:" \n"'; # rrdtool will skip a COMMENT that holds a NL only; so add a blank to make NL work
				} else if (trim($comment_string) != "COMMENT:\"\"") {
					$txt_graph_items .= rrd_substitute_host_query_data($comment_string, $graph, $graph_item);
				}
			}
		}elseif (($graph_item_types{$graph_item["graph_type_id"]} == "GPRINT") && (!isset($graph_data_array["graph_nolegend"]))) {
			$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
			$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . ":" . $consolidation_functions{$graph_item["consolidation_function_id"]} . ":\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
		}elseif (ereg("^(AREA|LINE[123]|STACK|HRULE|VRULE)$", $graph_item_types{$graph_item["graph_type_id"]})) {

			/* initialize any color syntax for graph item */
			if (empty($graph_item["hex"])) {
				$graph_item_color_code = "";
			}else{
				$graph_item_color_code = "#" . $graph_item["hex"];
				if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
					$graph_item_color_code .= $graph_item["alpha"];
				}
			}

			if (ereg("^(AREA|LINE[123])$", $graph_item_types{$graph_item["graph_type_id"]})) {
				$graph_item_stack_type = $graph_item_types{$graph_item["graph_type_id"]};
				$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
				$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
			}elseif ($graph_item_types{$graph_item["graph_type_id"]} == "STACK") {
				if (read_config_option("rrdtool_version") != "rrd-1.0.x") {
					$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
					$txt_graph_items .= $graph_item_stack_type . ":" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\":STACK";
				}else {
					$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
					$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
				}
			}elseif ($graph_item_types{$graph_item["graph_type_id"]} == "HRULE") {
				$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */
				$graph_variables["value"][$graph_item_id] = str_replace(":", "\:", $graph_variables["value"][$graph_item_id]); /* escape colons */
				/* perform variable substitution; if this does not return a number, rrdtool will FAIL! */
				$substitute = rrd_substitute_host_query_data($graph_variables["value"][$graph_item_id], $graph, $graph_item);
				if (is_numeric($substitute)) {
					$graph_variables["value"][$graph_item_id] = $substitute;
				}
				$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $graph_variables["value"][$graph_item_id] . $graph_item_color_code . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
			}elseif ($graph_item_types{$graph_item["graph_type_id"]} == "VRULE") {
				$graph_variables["text_format"][$graph_item_id] = str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]); /* escape colons */

				if (substr_count($graph_item["value"], ":")) {
					$value_array = explode(":", $graph_item["value"]);

					if ($value_array[0] < 0) {
						$value = date("U") - (-3600 * $value_array[0]) - 60 * $value_array[1];
					}else{
						$value = date("U", mktime($value_array[0],$value_array[1],0));
					}
				}else if (is_numeric($graph_item["value"])) {
					$value = $graph_item["value"];
				}

				$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $value . $graph_item_color_code . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
			}
		}else{
			$need_rrd_nl = FALSE;
		}

		$i++;

		if (($i < sizeof($graph_items)) && ($need_rrd_nl)) {
			$txt_graph_items .= RRD_NL;
		}
	}
	}

	/* either print out the source or pass the source onto rrdtool to get us a nice PNG */
	if (isset($graph_data_array["print_source"])) {
		print "<PRE>" . read_config_option("path_rrdtool") . " graph $graph_opts$graph_defs$txt_graph_items</PRE>";
	}else{
		if (isset($graph_data_array["export"])) {
			rrdtool_execute("graph $graph_opts$graph_defs$txt_graph_items", false, RRDTOOL_OUTPUT_NULL, $rrd_struc);
			return 0;
		}else{
			if (isset($graph_data_array["output_flag"])) {
				$output_flag = $graph_data_array["output_flag"];
			}else{
				$output_flag = RRDTOOL_OUTPUT_GRAPH_DATA;
			}

			return rrdtool_execute("graph $graph_opts$graph_defs$txt_graph_items", false, $output_flag, $rrd_struc);
		}
	}
}
Beispiel #2
0
function thold_data_source_action_prepare($save)
{
    global $colors, $config;
    if ($save["drp_action"] == "plugin_thold_create") {
        /* get the valid thold templates
         * remove those hosts that do not have any valid templates
         */
        $templates = "";
        $found_list = "";
        $not_found = "";
        if (sizeof($save["ds_array"])) {
            foreach ($save["ds_array"] as $item) {
                $data_template_id = db_fetch_cell("SELECT data_template_id FROM data_local WHERE id={$item}");
                if ($data_template_id != "") {
                    if (sizeof(db_fetch_assoc("SELECT id FROM thold_template WHERE data_template_id={$data_template_id}"))) {
                        $found_list .= "<li>" . get_data_source_title($item) . "</li>";
                        if (strlen($templates)) {
                            $templates .= ", {$data_template_id}";
                        } else {
                            $templates = "{$data_template_id}";
                        }
                    } else {
                        $not_found .= "<li>" . get_data_source_title($item) . "</li>";
                    }
                } else {
                    $not_found .= "<li>" . get_data_source_title($item) . "</li>";
                }
            }
        }
        if (strlen($templates)) {
            $sql = "SELECT id, name FROM thold_template WHERE data_template_id IN (" . $templates . ") ORDER BY name";
        } else {
            $sql = "SELECT id, name FROM thold_template ORDER BY name";
        }
        print "\t<tr>\r\n\t\t\t\t<td colspan='2' class='textArea' bgcolor='#" . $colors["form_alternate1"] . "'>";
        if (strlen($found_list)) {
            if (strlen($not_found)) {
                print "<p>The following Data Sources have no Threshold Templates associated with them</p>";
                print "<ul>" . $not_found . "</ul>";
            }
            print "<p>Are you sure you wish to create Thresholds for these Data Sources?</p>\r\n\t\t\t\t\t<ul>" . $found_list . "</ul>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\n\r\n\t\t\t\t";
            $form_array = array('general_header' => array('friendly_name' => 'Available Threshold Templates', 'method' => 'spacer'), 'thold_template_id' => array('method' => 'drop_sql', 'friendly_name' => 'Select a Threshold Template', 'description' => '', 'none_value' => 'None', 'value' => 'None', 'sql' => $sql));
            draw_edit_form(array("config" => array("no_form_tag" => true), "fields" => $form_array));
        } else {
            if (strlen($not_found)) {
                print "<p>There are no Threshold Templates associated with the following Data Sources</p>";
                print "<ul>" . $not_found . "</ul>";
            }
        }
    } else {
        return $save;
    }
}
Beispiel #3
0
function update_data_source_title_cache($local_data_id) {
	db_execute("update data_template_data set name_cache='" . addslashes(get_data_source_title($local_data_id)) . "' where local_data_id=$local_data_id");
}
Beispiel #4
0
function update_data_source_title_cache($local_data_id)
{
    db_execute_prepared('UPDATE data_template_data SET name_cache = ? WHERE local_data_id = ?', array(get_data_source_title($local_data_id), $local_data_id));
    api_plugin_hook_function('update_data_source_title_cache', $local_data_id);
}
function ds_edit()
{
    global $colors, $struct_data_source, $struct_data_source_item, $data_source_types;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var("id"));
    /* ==================================================== */
    $use_data_template = true;
    $host_id = 0;
    if (!empty($_GET["id"])) {
        $data_local = db_fetch_row("select host_id,data_template_id from data_local where id='" . $_GET["id"] . "'");
        $data = db_fetch_row("select * from data_template_data where local_data_id='" . $_GET["id"] . "'");
        if (isset($data_local["data_template_id"]) && $data_local["data_template_id"] >= 0) {
            $data_template = db_fetch_row("select id,name from data_template where id='" . $data_local["data_template_id"] . "'");
            $data_template_data = db_fetch_row("select * from data_template_data where data_template_id='" . $data_local["data_template_id"] . "' and local_data_id=0");
        } else {
            $_SESSION["sess_messages"] = 'Data Source "' . $_GET["id"] . '" does not exist.';
            header("Location: data_sources.php");
            exit;
        }
        $header_label = "[edit: " . get_data_source_title($_GET["id"]) . "]";
        if (empty($data_local["data_template_id"])) {
            $use_data_template = false;
        }
    } else {
        $header_label = "[new]";
        $use_data_template = false;
    }
    /* handle debug mode */
    if (isset($_GET["debug"])) {
        if ($_GET["debug"] == "0") {
            kill_session_var("ds_debug_mode");
        } elseif ($_GET["debug"] == "1") {
            $_SESSION["ds_debug_mode"] = true;
        }
    }
    include_once "./include/top_header.php";
    if (!empty($_GET["id"])) {
        ?>
		<table width="100%" align="center">
			<tr>
				<td class="textInfo" colspan="2" valign="top">
					<?php 
        print get_data_source_title($_GET["id"]);
        ?>
				</td>
				<td class="textInfo" align="right" valign="top">
					<span style="color: #c16921;">*<a href='data_sources.php?action=ds_edit&id=<?php 
        print isset($_GET["id"]) ? $_GET["id"] : 0;
        ?>
&debug=<?php 
        print isset($_SESSION["ds_debug_mode"]) ? "0" : "1";
        ?>
'>Turn <strong><?php 
        print isset($_SESSION["ds_debug_mode"]) ? "Off" : "On";
        ?>
</strong> Data Source Debug Mode.</a>
				</td>
			</tr>
		</table>
		<br>
		<?php 
    }
    html_start_box("<strong>Data Template Selection</strong> {$header_label}", "100%", $colors["header"], "3", "center", "");
    $form_array = array("data_template_id" => array("method" => "drop_sql", "friendly_name" => "Selected Data Template", "description" => "The name given to this data template.", "value" => isset($data_template) ? $data_template["id"] : "0", "none_value" => "None", "sql" => "select id,name from data_template order by name"), "host_id" => array("method" => "drop_sql", "friendly_name" => "Host", "description" => "Choose the host that this graph belongs to.", "value" => isset($_GET["host_id"]) ? $_GET["host_id"] : $data_local["host_id"], "none_value" => "None", "sql" => "select id,CONCAT_WS('',description,' (',hostname,')') as name from host order by description,hostname"), "_data_template_id" => array("method" => "hidden", "value" => isset($data_template) ? $data_template["id"] : "0"), "_host_id" => array("method" => "hidden", "value" => empty($data_local["host_id"]) ? isset($_GET["host_id"]) ? $_GET["host_id"] : "0" : $data_local["host_id"]), "_data_input_id" => array("method" => "hidden", "value" => isset($data["data_input_id"]) ? $data["data_input_id"] : "0"), "data_template_data_id" => array("method" => "hidden", "value" => isset($data) ? $data["id"] : "0"), "local_data_template_data_id" => array("method" => "hidden", "value" => isset($data) ? $data["local_data_template_data_id"] : "0"), "local_data_id" => array("method" => "hidden", "value" => isset($data) ? $data["local_data_id"] : "0"));
    draw_edit_form(array("config" => array(), "fields" => $form_array));
    html_end_box();
    /* only display the "inputs" area if we are using a data template for this data source */
    if (!empty($data["data_template_id"])) {
        $template_data_rrds = db_fetch_assoc("select * from data_template_rrd where local_data_id=" . $_GET["id"] . " order by data_source_name");
        html_start_box("<strong>Supplemental Data Template Data</strong>", "100%", $colors["header"], "3", "center", "");
        draw_nontemplated_fields_data_source($data["data_template_id"], $data["local_data_id"], $data, "|field|", "<strong>Data Source Fields</strong>", true, true, 0);
        draw_nontemplated_fields_data_source_item($data["data_template_id"], $template_data_rrds, "|field|_|id|", "<strong>Data Source Item Fields</strong>", true, true, true, 0);
        draw_nontemplated_fields_custom_data($data["id"], "value_|id|", "<strong>Custom Data</strong>", true, true, 0);
        form_hidden_box("save_component_data", "1", "");
        html_end_box();
    }
    if ((isset($_GET["id"]) || isset($_GET["new"])) && empty($data["data_template_id"])) {
        html_start_box("<strong>Data Source</strong>", "100%", $colors["header"], "3", "center", "");
        $form_array = array();
        while (list($field_name, $field_array) = each($struct_data_source)) {
            $form_array += array($field_name => $struct_data_source[$field_name]);
            if (!($use_data_template == false || !empty($data_template_data["t_" . $field_name]) || $field_array["flags"] == "NOTEMPLATE")) {
                $form_array[$field_name]["description"] = "";
            }
            $form_array[$field_name]["value"] = isset($data[$field_name]) ? $data[$field_name] : "";
            $form_array[$field_name]["form_id"] = empty($data["id"]) ? "0" : $data["id"];
            if (!($use_data_template == false || !empty($data_template_data["t_" . $field_name]) || $field_array["flags"] == "NOTEMPLATE")) {
                $form_array[$field_name]["method"] = "template_" . $form_array[$field_name]["method"];
            }
        }
        draw_edit_form(array("config" => array("no_form_tag" => true), "fields" => inject_form_variables($form_array, isset($data) ? $data : array())));
        html_end_box();
        /* fetch ALL rrd's for this data source */
        if (!empty($_GET["id"])) {
            $template_data_rrds = db_fetch_assoc("select id,data_source_name from data_template_rrd where local_data_id=" . $_GET["id"] . " order by data_source_name");
        }
        /* select the first "rrd" of this data source by default */
        if (empty($_GET["view_rrd"])) {
            $_GET["view_rrd"] = isset($template_data_rrds[0]["id"]) ? $template_data_rrds[0]["id"] : "0";
        }
        /* get more information about the rrd we chose */
        if (!empty($_GET["view_rrd"])) {
            $local_data_template_rrd_id = db_fetch_cell("select local_data_template_rrd_id from data_template_rrd where id=" . $_GET["view_rrd"]);
            $rrd = db_fetch_row("select * from data_template_rrd where id=" . $_GET["view_rrd"]);
            $rrd_template = db_fetch_row("select * from data_template_rrd where id={$local_data_template_rrd_id}");
            $header_label = "[edit: " . $rrd["data_source_name"] . "]";
        } else {
            $header_label = "";
        }
        $i = 0;
        if (isset($template_data_rrds)) {
            if (sizeof($template_data_rrds) > 1) {
                /* draw the data source tabs on the top of the page */
                print "\t<table class='tabs' width='100%' cellspacing='0' cellpadding='3' align='center'>\n\t\t\t\t\t<tr>\n";
                foreach ($template_data_rrds as $template_data_rrd) {
                    $i++;
                    print "\t<td " . ($template_data_rrd["id"] == $_GET["view_rrd"] ? "bgcolor='silver'" : "bgcolor='#DFDFDF'") . " nowrap='nowrap' width='" . (strlen($template_data_rrd["data_source_name"]) * 9 + 50) . "' align='center' class='tab'>\n\t\t\t\t\t\t\t\t<span class='textHeader'><a href='data_sources.php?action=ds_edit&id=" . $_GET["id"] . "&view_rrd=" . $template_data_rrd["id"] . "'>{$i}: " . $template_data_rrd["data_source_name"] . "</a>" . ($use_data_template == false ? " <a href='data_sources.php?action=rrd_remove&id=" . $template_data_rrd["id"] . "&local_data_id=" . $_GET["id"] . "'><img src='images/delete_icon.gif' border='0' alt='Delete'></a>" : "") . "</span>\n\t\t\t\t\t\t\t</td>\n\n\t\t\t\t\t\t\t<td width='1'></td>\n";
                }
                print "\n\t\t\t\t\t<td></td>\n\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n";
            } elseif (sizeof($template_data_rrds) == 1) {
                $_GET["view_rrd"] = $template_data_rrds[0]["id"];
            }
        }
        html_start_box("", "100%", $colors["header"], "3", "center", "");
        print "\t<tr>\n\t\t\t\t<td bgcolor='#" . $colors["header"] . "' class='textHeaderDark'>\n\t\t\t\t\t<strong>Data Source Item</strong> {$header_label}\n\t\t\t\t</td>\n\t\t\t\t<td class='textHeaderDark' align='right' bgcolor='" . $colors["header"] . "'>\n\t\t\t\t\t" . (!empty($_GET["id"]) && empty($data_template["id"]) ? "<strong><a class='linkOverDark' href='data_sources.php?action=rrd_add&id=" . $_GET["id"] . "'>New</a>&nbsp;</strong>" : "") . "\n\t\t\t\t</td>\n\t\t\t</tr>\n";
        /* data input fields list */
        if (empty($data["data_input_id"]) || db_fetch_cell("select type_id from data_input where id=" . $data["data_input_id"]) > "1") {
            unset($struct_data_source_item["data_input_field_id"]);
        } else {
            $struct_data_source_item["data_input_field_id"]["sql"] = "select id,CONCAT(data_name,' - ',name) as name from data_input_fields where data_input_id=" . $data["data_input_id"] . " and input_output='out' and update_rra='on' order by data_name,name";
        }
        $form_array = array();
        while (list($field_name, $field_array) = each($struct_data_source_item)) {
            $form_array += array($field_name => $struct_data_source_item[$field_name]);
            if (!($use_data_template == false || $rrd_template["t_" . $field_name] == "on")) {
                $form_array[$field_name]["description"] = "";
            }
            $form_array[$field_name]["value"] = isset($rrd) ? $rrd[$field_name] : "";
            if (!($use_data_template == false || $rrd_template["t_" . $field_name] == "on")) {
                $form_array[$field_name]["method"] = "template_" . $form_array[$field_name]["method"];
            }
        }
        draw_edit_form(array("config" => array("no_form_tag" => true), "fields" => array("data_template_rrd_id" => array("method" => "hidden", "value" => isset($rrd) ? $rrd["id"] : "0"), "local_data_template_rrd_id" => array("method" => "hidden", "value" => isset($rrd) ? $rrd["local_data_template_rrd_id"] : "0")) + $form_array));
        html_end_box();
        /* data source data goes here */
        data_edit();
        form_hidden_box("current_rrd", $_GET["view_rrd"], "0");
    }
    /* display the debug mode box if the user wants it */
    if (isset($_SESSION["ds_debug_mode"]) && isset($_GET["id"])) {
        ?>
		<table width="100%" align="center">
			<tr>
				<td>
					<span class="textInfo">Data Source Debug</span><br>
					<pre><?php 
        print rrdtool_function_create($_GET["id"], true, array());
        ?>
</pre>
				</td>
			</tr>
		</table>
		<?php 
    }
    if (isset($_GET["id"]) || isset($_GET["new"])) {
        form_hidden_box("save_component_data_source", "1", "");
    } else {
        form_hidden_box("save_component_data_source_new", "1", "");
    }
    form_save_button("data_sources.php");
    include_once "./include/bottom_footer.php";
}
Beispiel #6
0
function data_source_edit() {
	global $colors;
	require_once(CACTI_BASE_PATH . "/lib/data_source/data_source_info.php");

	/* ================= input validation ================= */
	input_validate_input_number(get_request_var("id"));
	/* ==================================================== */

	$use_data_template = true;
	$device_id = 0;

	if (!empty($_GET["id"])) {
		$data_local 		= db_fetch_row("select device_id,data_template_id from data_local where id='" . $_GET["id"] . "'");
		$data       		= db_fetch_row("select * from data_template_data where local_data_id='" . $_GET["id"] . "'");
		$data_source_items 	= db_fetch_assoc("select * from data_template_rrd where local_data_id=" . $_GET["id"] . " order by data_source_name");

		if (isset($data_local["data_template_id"]) && $data_local["data_template_id"] >= 0) {
			$data_template      = db_fetch_row("select id,name from data_template where id='" . $data_local["data_template_id"] . "'");
			$data_template_data = db_fetch_row("select * from data_template_data where data_template_id='" . $data_local["data_template_id"] . "' and local_data_id=0");
		} else {
			$_SESSION["sess_messages"] = 'Data Source "' . $_GET["id"] . '" does not exist.';
			header ("Location: data_sources.php");
			exit;
		}

		$header_label = __("[edit: ") . get_data_source_title($_GET["id"]) . "]";

		if (empty($data_local["data_template_id"])) {
			$use_data_template = false;
		}
	}else{
		$header_label = __("[new]");

		$use_data_template = false;
	}

	/* handle debug mode */
	if (isset($_GET["debug"])) {
		if (get_request_var("debug") == "0") {
			kill_session_var("ds_debug_mode");
		}elseif (get_request_var("debug") == "1") {
			$_SESSION["ds_debug_mode"] = true;
		}
	}

	/* handle info mode */
	if (isset($_GET["info"])) {
		if (get_request_var("info") == "0") {
			kill_session_var("ds_info_mode");
		}elseif (get_request_var("info") == "1") {
			$_SESSION["ds_info_mode"] = true;
		}
	}

	include_once(CACTI_BASE_PATH . "/include/top_header.php");

	$tip_text = "";
	if (isset($data)) {
		$tip_text .= "<tr><td align=\\'right\\'><a class=\\'popup_item\\' id=\\'changeDSState\\' onClick=\\'changeDSState()\\' href=\\'#\\'>Unlock/Lock</a></td></tr>";
		$tip_text .= "<tr><td align=\\'right\\'><a class=\\'popup_item\\' href=\\'" . htmlspecialchars('data_sources.php?action=data_source_toggle_status&id=' . (isset($_GET["id"]) ? $_GET["id"] : 0) . '&newstate=' . (($data["active"] == CHECKED) ? "0" : "1")) . "\\'>" . (($data["active"] == CHECKED) ? __("Disable") : __("Enable")) . "</a></td></tr>";
		$tip_text .= "<tr><td align=\\'right\\'><a class=\\'popup_item\\' href=\\'" . htmlspecialchars('data_sources.php?action=data_source_edit&id=' . (isset($_GET["id"]) ? $_GET["id"] : 0) . '&debug=' . (isset($_SESSION["ds_debug_mode"]) ? "0" : "1")) . "\\'>" . __("Turn") . " <strong>" . (isset($_SESSION["ds_debug_mode"]) ? __("Off") : __(CHECKED)) . "</strong> " . __("Debug Mode") . "</a></td></tr>";
		$tip_text .= "<tr><td align=\\'right\\'><a class=\\'popup_item\\' href=\\'" . htmlspecialchars('data_sources.php?action=data_source_edit&id=' . (isset($_GET["id"]) ? $_GET["id"] : 0) . '&info=' . (isset($_SESSION["ds_info_mode"]) ? "0" : "1")) . "\\'>" . __("Turn") . " <strong>" . (isset($_SESSION["ds_info_mode"]) ? __("Off") : __(CHECKED)) . "</strong> " . __("RRD Info Mode") . "</a><td></tr>";
	}
	if (!empty($data_template["id"])) {
		$tip_text .= "<tr><td align=\\'right\\'><a class=\\'popup_item\\' href=\\'" . htmlspecialchars('data_templates.php?action=template_edit&id=' . (isset($data_template["id"]) ? $data_template["id"] : "0")) . "\\'>" . __("Edit Data Source Template") . "<br></a></td></td>";
	}
	if (!empty($_GET["device_id"]) || !empty($data_local["device_id"])) {
		$tip_text .= "<tr><td align=\\'right\\'><a class=\\'popup_item\\' href=\\'" . htmlspecialchars('devices.php?action=edit&id=' . (isset($_GET["device_id"]) ? $_GET["device_id"] : $data_local["device_id"])) . "\\'>" . __("Edit Host") . "</a></td></tr>";
	}

	if (!empty($_GET["id"])) {
		?>
		<script type="text/javascript">
		<!--
		var disabled = true;

		$().ready(function() {
			$("input").attr("disabled","disabled")
			$("select").attr("disabled","disabled")
			$("#cancel").removeAttr("disabled");
		});

		function changeDSState() {
			if (disabled) {
				$("input").removeAttr("disabled");
				$("select").removeAttr("disabled");
				$("#cancel").removeAttr("disabled");
				disabled = false;
			}else{
				$("input").attr("disabled","disabled")
				$("select").attr("disabled","disabled")
				disabled = true;
			}
		}
		-->
		</script>
		<table width="100%" align="center">
			<tr>
				<td class="textInfo" colspan="2" valign="top">
					<?php print get_data_source_title(get_request_var("id"));?>
				</td>
				<td style="white-space:nowrap;" align="right" class="w1"><a id='tooltip' class='popup_anchor' href='#' onMouseOver="Tip('<?php print $tip_text;?>', BGCOLOR, '#EEEEEE', FIX, ['tooltip', -20, 0], STICKY, true, SHADOW, true, CLICKCLOSE, true, FADEOUT, 400, TEXTALIGN, 'right', BORDERCOLOR, '#F5F5F5')" onMouseOut="UnTip()">Data Source Options</a></td>
			</tr>
		</table>
		<?php
	}

	print "<form method='post' action='" .  basename($_SERVER["PHP_SELF"]) . "' name='data_source_edit'>\n";
	html_start_box("<strong>" . __("Data Source Template Selection") . "</strong> $header_label", "100", $colors["header"], 0, "center", "");
	$header_items = array(__("Field"), __("Value"));
	print "<tr><td>";
	html_header($header_items, 1, true, 'template');

	$form_array = fields_data_source_form_list();
	$form_array["data_template_id"]["id"] = (isset($data_template["id"]) ? $data_template["id"] : "0");
	$form_array["data_template_id"]["name"] = db_fetch_cell("SELECT name FROM data_template WHERE id=" . $form_array["data_template_id"]["id"]);
	$form_array["device_id"]["id"] = (isset($_GET["device_id"]) ? $_GET["device_id"] : $data_local["device_id"]);
	$form_array["device_id"]["name"] = db_fetch_cell("SELECT CONCAT_WS('',description,' (',hostname,')') FROM device WHERE id=" . $form_array["device_id"]["id"]);

	draw_edit_form(
		array(
			"config" => array(),
			"fields" => $form_array
			)
		);

	print "</table></td></tr>";		/* end of html_header */
	html_end_box();
	form_hidden_box("hidden_data_template_id", (isset($data_template["id"]) ? $data_template["id"] : "0"), "");
	form_hidden_box("hidden_device_id", (empty($data_local["device_id"]) ? (isset($_GET["device_id"]) ? $_GET["device_id"] : "0") : $data_local["device_id"]), "");
	form_hidden_box("hidden_data_input_id", (isset($data["data_input_id"]) ? $data["data_input_id"] : "0"), "");
	form_hidden_box("data_template_data_id", (isset($data) ? $data["id"] : "0"), "");
	form_hidden_box("local_data_template_data_id", (isset($data) ? $data["local_data_template_data_id"] : "0"), "");
	form_hidden_box("local_data_id", (isset($data) ? $data["local_data_id"] : "0"), "");

	/* only display the "inputs" area if we are using a data template for this data source */
	if (!empty($data["data_template_id"])) {

		html_start_box("<strong>" . __("Supplemental Data Source Template Data") . "</strong>", "100", $colors["header"], 0, "center", "");

		draw_nontemplated_fields_data_source($data["data_template_id"], $data["local_data_id"], $data, "|field|", "<strong>" . __("Data Source Fields") . "</strong>", true, true, 0);
		draw_nontemplated_fields_data_source_item($data["data_template_id"], $data_source_items, "|field|_|id|", "<strong>" . __("Data Source Item Fields") . "</strong>", true, true, true, 0);
		draw_nontemplated_fields_custom_data($data["id"], "value_|id|", "<strong>" . __("Custom Data") . "</strong>", true, true, 0);

		html_end_box();

		form_hidden_box("save_component_data","1","");
	}

	if (((isset($_GET["id"])) || (isset($_GET["new"]))) && (empty($data["data_template_id"]))) {
		html_start_box("<strong>" . __("Data Source") . "</strong>", "100", $colors["header"], "3", "center", "");

		$form_array = array();

		$struct_data_source = data_source_form_list();
		while (list($field_name, $field_array) = each($struct_data_source)) {
			$form_array += array($field_name => $struct_data_source[$field_name]);

			$form_array[$field_name]["value"] = (isset($data[$field_name]) ? $data[$field_name] : "");
			$form_array[$field_name]["form_id"] = (empty($data["id"]) ? "0" : $data["id"]);

			if (!(($use_data_template == false) || (!empty($data_template_data{"t_" . $field_name})) || ($field_array["flags"] == "NOTEMPLATE"))) {
				$form_array[$field_name]["method"] = "template_" . $form_array[$field_name]["method"];
			}
		}

		draw_edit_form(
			array(
				"config" => array("no_form_tag" => true),
				"fields" => inject_form_variables($form_array, (isset($data) ? $data : array()))
				)
			);

		html_end_box();


		if (!empty($_GET["id"])) {

			html_start_box("<strong>" . __("Data Source Items") . "</strong>", "100", $colors["header"], "0", "center", "data_sources_items.php?action=item_edit&local_data_id=" . $_GET["id"], true);
			draw_data_template_items_list($data_source_items, "data_sources_items.php", "local_data_id=" . $_GET["id"], $use_data_template);
			html_end_box(false);
		}

		/* data source data goes here */
		data_source_data_edit();
	}

	/* display the debug mode box if the user wants it */
	if ((isset($_SESSION["ds_debug_mode"])) && (isset($_GET["id"]))) {
		?>
		<table width="100%" align="center">
			<tr>
				<td>
					<span class="textInfo"><?php print __("Data Source Debug");?></span><br>
					<pre><?php print rrdtool_function_create(get_request_var("id"), true, array());?></pre>
				</td>
			</tr>
		</table>
		<?php
	}

	if ((isset($_SESSION["ds_info_mode"])) && (isset($_GET["id"]))) {
		$rrd_info = rrdtool_function_info($_GET["id"]);

		if (sizeof($rrd_info["rra"])) {
			$diff = rrdtool_cacti_compare($_GET["id"], $rrd_info);
			rrdtool_info2html($rrd_info, $diff);
			rrdtool_tune($rrd_info["filename"], $diff, true);
		}
	}

	if ((isset($_GET["id"])) || (isset($_GET["new"]))) {
		form_hidden_box("save_component_data_source","1","");
	}else{
		form_hidden_box("save_component_data_source_new","1","");
	}

	form_save_button_alt();

	include_once(CACTI_BASE_PATH . "/access/js/data_source_item.js");
	include_once(CACTI_BASE_PATH . "/include/bottom_footer.php");
}
Beispiel #7
0
function rrdtool_function_graph($local_graph_id, $rra_id, $graph_data_array, $rrdtool_pipe = "", &$xport_meta = array())
{
    global $config, $consolidation_functions;
    include_once $config["library_path"] . "/cdef.php";
    include_once $config["library_path"] . "/graph_variables.php";
    include_once $config['library_path'] . '/boost.php';
    include_once $config['library_path'] . '/xml.php';
    include $config["include_path"] . "/global_arrays.php";
    /* prevent command injection
     * This function prepares an rrdtool graph statement to be executed by the web server.
     * We have to take care, that the attacker does not insert shell code.
     * As some rrdtool parameters accept "Cacti variables", we have to perform the
     * variable substitution prior to vulnerability checks.
     * We will enclose all parameters in quotes and substitute quotation marks within
     * those parameters. 
     */
    /* rrdtool fetches the default font from it's execution environment
     * you won't find that default font on the rrdtool statement itself!
     * set the rrdtool default font via environment variable */
    if (!isset($graph_data_array['export_csv'])) {
        if (read_config_option("path_rrdtool_default_font")) {
            putenv("RRD_DEFAULT_FONT=" . read_config_option("path_rrdtool_default_font"));
        }
    }
    /* before we do anything; make sure the user has permission to view this graph,
    	if not then get out */
    if (!is_graph_allowed($local_graph_id)) {
        return "GRAPH ACCESS DENIED";
    }
    /* check the boost image cache and if we find a live file there return it instead */
    if (!isset($graph_data_array['export_csv']) && !isset($graph_data_array['export_realtime'])) {
        $graph_data = boost_graph_cache_check($local_graph_id, $rra_id, $rrdtool_pipe, $graph_data_array, false);
        if ($graph_data != false) {
            return $graph_data;
        }
    }
    /* find the step and how often this graph is updated with new data */
    $ds_step = db_fetch_cell("SELECT\n\t\tdata_template_data.rrd_step\n\t\tFROM (data_template_data,data_template_rrd,graph_templates_item)\n\t\tWHERE graph_templates_item.task_item_id=data_template_rrd.id\n\t\tAND data_template_rrd.local_data_id=data_template_data.local_data_id\n\t\tAND graph_templates_item.local_graph_id={$local_graph_id}\n\t\tLIMIT 0,1");
    $ds_step = empty($ds_step) ? 300 : $ds_step;
    /* if no rra was specified, we need to figure out which one RRDTool will choose using
     * "best-fit" resolution fit algorithm */
    if (empty($rra_id)) {
        if (empty($graph_data_array["graph_start"]) || empty($graph_data_array["graph_end"])) {
            $rra["rows"] = 600;
            $rra["steps"] = 1;
            $rra["timespan"] = 86400;
        } else {
            /* get a list of RRAs related to this graph */
            $rras = get_associated_rras($local_graph_id);
            if (sizeof($rras) > 0) {
                foreach ($rras as $unchosen_rra) {
                    /* the timespan specified in the RRA "timespan" field may not be accurate */
                    $real_timespan = $ds_step * $unchosen_rra["steps"] * $unchosen_rra["rows"];
                    /* make sure the current start/end times fit within each RRA's timespan */
                    if ($graph_data_array["graph_end"] - $graph_data_array["graph_start"] <= $real_timespan && time() - $graph_data_array["graph_start"] <= $real_timespan) {
                        /* is this RRA better than the already chosen one? */
                        if (isset($rra) && $unchosen_rra["steps"] < $rra["steps"]) {
                            $rra = $unchosen_rra;
                        } else {
                            if (!isset($rra)) {
                                $rra = $unchosen_rra;
                            }
                        }
                    }
                }
            }
            if (!isset($rra)) {
                $rra["rows"] = 600;
                $rra["steps"] = 1;
            }
        }
    } else {
        $rra = db_fetch_row("SELECT timespan,rows,steps FROM rra WHERE id={$rra_id}");
    }
    if (!isset($graph_data_array['export_realtime'])) {
        $seconds_between_graph_updates = $ds_step * $rra["steps"];
    } else {
        $seconds_between_graph_updates = 5;
    }
    $graph = db_fetch_row("SELECT gl.id AS local_graph_id, gl.host_id,\n\t\tgl.snmp_query_id, gl.snmp_index, gtg.title_cache, gtg.vertical_label,\n\t\tgtg.slope_mode, gtg.auto_scale, gtg.auto_scale_opts, gtg.auto_scale_log,\n\t\tgtg.scale_log_units, gtg.auto_scale_rigid, gtg.auto_padding, gtg.base_value,\n\t\tgtg.upper_limit, gtg.lower_limit, gtg.height, gtg.width, gtg.image_format_id,\n\t\tgtg.unit_value, gtg.unit_exponent_value, gtg.export\n\t\tFROM graph_templates_graph AS gtg\n\t\tINNER JOIN graph_local AS gl\n\t\tON gl.id=gtg.local_graph_id\n\t\tWHERE gtg.local_graph_id={$local_graph_id}");
    /* lets make that sql query... */
    $graph_items = db_fetch_assoc("SELECT gti.id AS graph_templates_item_id,\n\t\tgti.cdef_id, gti.text_format, gti.value, gti.hard_return,\n\t\tgti.consolidation_function_id, gti.graph_type_id, gtgp.gprint_text,\n\t\tcolors.hex, gti.alpha, dtr.id AS data_template_rrd_id, dtr.local_data_id,\n\t\tdtr.rrd_minimum, dtr.rrd_maximum, dtr.data_source_name, dtr.local_data_template_rrd_id\n\t\tFROM graph_templates_item AS gti\n\t\tLEFT JOIN data_template_rrd AS dtr\n\t\tON gti.task_item_id=dtr.id\n\t\tLEFT JOIN colors \n\t\tON gti.color_id=colors.id\n\t\tLEFT JOIN graph_templates_gprint AS gtgp\n\t\tON gti.gprint_id=gtgp.id\n\t\tWHERE gti.local_graph_id={$local_graph_id}\n\t\tORDER BY gti.sequence");
    /* variables for use below */
    $graph_defs = "";
    $txt_graph_items = "";
    $text_padding = "";
    $padding_estimate = 0;
    $last_graph_type = "";
    /* override: graph start time */
    if (!isset($graph_data_array["graph_start"]) || $graph_data_array["graph_start"] == "0") {
        $graph_start = -$rra["timespan"];
    } else {
        $graph_start = $graph_data_array["graph_start"];
    }
    /* override: graph end time */
    if (!isset($graph_data_array["graph_end"]) || $graph_data_array["graph_end"] == "0") {
        $graph_end = -$seconds_between_graph_updates;
    } else {
        $graph_end = $graph_data_array["graph_end"];
    }
    /* +++++++++++++++++++++++ GRAPH OPTIONS +++++++++++++++++++++++ */
    if (!isset($graph_data_array['export_csv'])) {
        $graph_opts = rrd_function_process_graph_options($graph_start, $graph_end, $graph, $graph_data_array);
    } else {
        /* basic export options */
        $graph_opts = "--start=" . cacti_escapeshellarg($graph_start) . RRD_NL . "--end=" . cacti_escapeshellarg($graph_end) . RRD_NL . "--maxrows=10000" . RRD_NL;
    }
    /* +++++++++++++++++++++++ LEGEND: MAGIC +++++++++++++++++++++++ */
    $i = 0;
    $j = 0;
    $last_graph_cf = array();
    if (sizeof($graph_items)) {
        /* we need to add a new column "cf_reference", so unless PHP 5 is used, this foreach syntax is required */
        foreach ($graph_items as $key => $graph_item) {
            /* mimic the old behavior: LINE[123], AREA and STACK items use the CF specified in the graph item */
            if ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3 || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREA || $graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_STACK) {
                $graph_cf = $graph_item["consolidation_function_id"];
                /* remember the last CF for this data source for use with GPRINT
                 * if e.g. an AREA/AVERAGE and a LINE/MAX is used
                 * we will have AVERAGE first and then MAX, depending on GPRINT sequence */
                $last_graph_cf["data_source_name"]["local_data_template_rrd_id"] = $graph_cf;
                /* remember this for second foreach loop */
                $graph_items[$key]["cf_reference"] = $graph_cf;
            } elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT) {
                /* ATTENTION!
                 * the "CF" given on graph_item edit screen for GPRINT is indeed NOT a real "CF",
                 * but an aggregation function
                 * see "man rrdgraph_data" for the correct VDEF based notation
                 * so our task now is to "guess" the very graph_item, this GPRINT is related to
                 * and to use that graph_item's CF */
                if (isset($last_graph_cf["data_source_name"]["local_data_template_rrd_id"])) {
                    $graph_cf = $last_graph_cf["data_source_name"]["local_data_template_rrd_id"];
                    /* remember this for second foreach loop */
                    $graph_items[$key]["cf_reference"] = $graph_cf;
                } else {
                    $graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
                    /* remember this for second foreach loop */
                    $graph_items[$key]["cf_reference"] = $graph_cf;
                }
            } else {
                /* all other types are based on the best matching CF */
                $graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
                /* remember this for second foreach loop */
                $graph_items[$key]["cf_reference"] = $graph_cf;
            }
            if (!empty($graph_item["local_data_id"]) && !isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$graph_cf])) {
                /* use a user-specified ds path if one is entered */
                if (isset($graph_data_array['export_realtime'])) {
                    $data_source_path = read_config_option("realtime_cache_path") . "/user_" . session_id() . "_" . $graph_item["local_data_id"] . ".rrd";
                } else {
                    $data_source_path = get_data_source_path($graph_item["local_data_id"], true);
                }
                /* FOR WIN32: Escape all colon for drive letters (ex. D\:/path/to/rra) */
                $data_source_path = str_replace(":", "\\:", $data_source_path);
                if (!empty($data_source_path)) {
                    /* NOTE: (Update) Data source DEF names are created using the graph_item_id; then passed
                    			to a function that matches the digits with letters. rrdtool likes letters instead
                    			of numbers in DEF names; especially with CDEF's. cdef's are created
                    			the same way, except a 'cdef' is put on the beginning of the hash */
                    $graph_defs .= "DEF:" . generate_graph_def_name(strval($i)) . "=" . cacti_escapeshellarg($data_source_path) . ":" . cacti_escapeshellarg($graph_item["data_source_name"], true) . ":" . $consolidation_functions[$graph_cf] . RRD_NL;
                    $cf_ds_cache[$graph_item["data_template_rrd_id"]][$graph_cf] = "{$i}";
                    $i++;
                }
            }
            /* cache cdef value here to support data query variables in the cdef string */
            if (empty($graph_item["cdef_id"])) {
                $graph_item["cdef_cache"] = "";
                $graph_items[$j]["cdef_cache"] = "";
            } else {
                $graph_item["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
                $graph_items[$j]["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
            }
            /* +++++++++++++++++++++++ LEGEND: TEXT SUBSTITUTION (<>'s) +++++++++++++++++++++++ */
            /* note the current item_id for easy access */
            $graph_item_id = $graph_item["graph_templates_item_id"];
            /* the following fields will be searched for graph variables */
            $variable_fields = array("text_format" => array("process_no_legend" => false), "value" => array("process_no_legend" => true), "cdef_cache" => array("process_no_legend" => true));
            /* loop through each field that we want to substitute values for:
            			currently: text format and value */
            while (list($field_name, $field_array) = each($variable_fields)) {
                /* certain fields do not require values when the legend is not to be shown */
                if ($field_array["process_no_legend"] == false && isset($graph_data_array["graph_nolegend"])) {
                    continue;
                }
                $graph_variables[$field_name][$graph_item_id] = $graph_item[$field_name];
                /* date/time substitution */
                if (strstr($graph_variables[$field_name][$graph_item_id], "|date_time|")) {
                    $graph_variables[$field_name][$graph_item_id] = str_replace("|date_time|", date('D d M H:i:s T Y', strtotime(db_fetch_cell("SELECT value FROM settings WHERE name='date'"))), $graph_variables[$field_name][$graph_item_id]);
                }
                /* data source title substitution */
                if (strstr($graph_variables[$field_name][$graph_item_id], "|data_source_title|")) {
                    $graph_variables[$field_name][$graph_item_id] = str_replace("|data_source_title|", get_data_source_title($graph_item["local_data_id"]), $graph_variables[$field_name][$graph_item_id]);
                }
                /* data query variables */
                $graph_variables[$field_name][$graph_item_id] = rrd_substitute_host_query_data($graph_variables[$field_name][$graph_item_id], $graph, $graph_item);
                /* Nth percentile */
                if (preg_match_all("/\\|([0-9]{1,2}):(bits|bytes):(\\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\\d)?\\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
                    foreach ($matches as $match) {
                        $graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_nth_percentile($match, $graph_item, $graph_items, $graph_start, $graph_end), $graph_variables[$field_name][$graph_item_id]);
                    }
                }
                /* bandwidth summation */
                if (preg_match_all("/\\|sum:(\\d|auto):(current|total|atomic):(\\d):(\\d+|auto)\\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
                    foreach ($matches as $match) {
                        $graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_bandwidth_summation($match, $graph_item, $graph_items, $graph_start, $graph_end, $rra["steps"], $ds_step), $graph_variables[$field_name][$graph_item_id]);
                    }
                }
            }
            /* if we are not displaying a legend there is no point in us even processing the auto padding,
            			text format stuff. */
            if (!isset($graph_data_array["graph_nolegend"])) {
                /* set hard return variable if selected (\n) */
                if ($graph_item["hard_return"] == "on") {
                    $hardreturn[$graph_item_id] = "\\n";
                } else {
                    $hardreturn[$graph_item_id] = "";
                }
                /* +++++++++++++++++++++++ LEGEND: AUTO PADDING (<>'s) +++++++++++++++++++++++ */
                /* PADDING: remember this is not perfect! its main use is for the basic graph setup of:
                			AREA - GPRINT-CURRENT - GPRINT-AVERAGE - GPRINT-MAXIMUM \n
                			of course it can be used in other situations, however may not work as intended.
                			If you have any additions to this small peice of code, feel free to send them to me. */
                if ($graph["auto_padding"] == "on") {
                    /* only applies to AREA, STACK and LINEs */
                    if (preg_match("/(AREA|STACK|LINE[123])/", $graph_item_types[$graph_item["graph_type_id"]])) {
                        $text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);
                        if ($text_format_length > $padding_estimate) {
                            $padding_estimate = $text_format_length;
                        }
                    }
                }
            }
            $j++;
        }
    }
    /* +++++++++++++++++++++++ GRAPH ITEMS: CDEF's +++++++++++++++++++++++ */
    $i = 0;
    reset($graph_items);
    /* hack for rrdtool 1.2.x support */
    $graph_item_stack_type = "";
    if (sizeof($graph_items)) {
        foreach ($graph_items as $graph_item) {
            /* first we need to check if there is a DEF for the current data source/cf combination. if so,
            		we will use that */
            if (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$graph_item["consolidation_function_id"]])) {
                $cf_id = $graph_item["consolidation_function_id"];
            } else {
                /* if there is not a DEF defined for the current data source/cf combination, then we will have to
                		improvise. choose the first available cf in the following order: AVERAGE, MAX, MIN, LAST */
                if (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][1])) {
                    $cf_id = 1;
                    /* CF: AVERAGE */
                } elseif (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][3])) {
                    $cf_id = 3;
                    /* CF: MAX */
                } elseif (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][2])) {
                    $cf_id = 2;
                    /* CF: MIN */
                } elseif (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][4])) {
                    $cf_id = 4;
                    /* CF: LAST */
                } else {
                    $cf_id = 1;
                    /* CF: AVERAGE */
                }
            }
            /* now remember the correct CF reference */
            $cf_id = $graph_item["cf_reference"];
            /* make cdef string here; a note about CDEF's in cacti. A CDEF is neither unique to a
            		data source of global cdef, but is unique when those two variables combine. */
            $cdef_graph_defs = "";
            if (!empty($graph_item["cdef_id"]) && !isset($cdef_cache[$graph_item["cdef_id"]][$graph_item["data_template_rrd_id"]][$cf_id])) {
                $cdef_string = $graph_variables["cdef_cache"][$graph_item["graph_templates_item_id"]];
                $magic_item = array();
                $already_seen = array();
                $sources_seen = array();
                $count_all_ds_dups = 0;
                $count_all_ds_nodups = 0;
                $count_similar_ds_dups = 0;
                $count_similar_ds_nodups = 0;
                /* if any of those magic variables are requested ... */
                if (preg_match("/(ALL_DATA_SOURCES_(NO)?DUPS|SIMILAR_DATA_SOURCES_(NO)?DUPS)/", $cdef_string) || preg_match("/(COUNT_ALL_DS_(NO)?DUPS|COUNT_SIMILAR_DS_(NO)?DUPS)/", $cdef_string)) {
                    /* now walk through each case to initialize array*/
                    if (preg_match("/ALL_DATA_SOURCES_DUPS/", $cdef_string)) {
                        $magic_item["ALL_DATA_SOURCES_DUPS"] = "";
                    }
                    if (preg_match("/ALL_DATA_SOURCES_NODUPS/", $cdef_string)) {
                        $magic_item["ALL_DATA_SOURCES_NODUPS"] = "";
                    }
                    if (preg_match("/SIMILAR_DATA_SOURCES_DUPS/", $cdef_string)) {
                        $magic_item["SIMILAR_DATA_SOURCES_DUPS"] = "";
                    }
                    if (preg_match("/SIMILAR_DATA_SOURCES_NODUPS/", $cdef_string)) {
                        $magic_item["SIMILAR_DATA_SOURCES_NODUPS"] = "";
                    }
                    if (preg_match("/COUNT_ALL_DS_DUPS/", $cdef_string)) {
                        $magic_item["COUNT_ALL_DS_DUPS"] = "";
                    }
                    if (preg_match("/COUNT_ALL_DS_NODUPS/", $cdef_string)) {
                        $magic_item["COUNT_ALL_DS_NODUPS"] = "";
                    }
                    if (preg_match("/COUNT_SIMILAR_DS_DUPS/", $cdef_string)) {
                        $magic_item["COUNT_SIMILAR_DS_DUPS"] = "";
                    }
                    if (preg_match("/COUNT_SIMILAR_DS_NODUPS/", $cdef_string)) {
                        $magic_item["COUNT_SIMILAR_DS_NODUPS"] = "";
                    }
                    /* loop over all graph items */
                    for ($t = 0; $t < count($graph_items); $t++) {
                        /* only work on graph items, omit GRPINTs, COMMENTs and stuff */
                        if (preg_match("/(AREA|STACK|LINE[123])/", $graph_item_types[$graph_items[$t]["graph_type_id"]]) && !empty($graph_items[$t]["data_template_rrd_id"])) {
                            /* if the user screws up CF settings, PHP will generate warnings if left unchecked */
                            /* matching consolidation function? */
                            if (isset($cf_ds_cache[$graph_items[$t]["data_template_rrd_id"]][$cf_id])) {
                                $def_name = generate_graph_def_name(strval($cf_ds_cache[$graph_items[$t]["data_template_rrd_id"]][$cf_id]));
                                /* do we need ALL_DATA_SOURCES_DUPS? */
                                if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
                                    $magic_item["ALL_DATA_SOURCES_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                    /* convert unknowns to '0' first */
                                }
                                /* do we need COUNT_ALL_DS_DUPS? */
                                if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
                                    $magic_item["COUNT_ALL_DS_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                    /* convert unknowns to '0' first */
                                }
                                $count_all_ds_dups++;
                                /* check if this item also qualifies for NODUPS  */
                                if (!isset($already_seen[$def_name])) {
                                    if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
                                        $magic_item["ALL_DATA_SOURCES_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
                                        $magic_item["COUNT_ALL_DS_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    $count_all_ds_nodups++;
                                    $already_seen[$def_name] = TRUE;
                                }
                                /* check for SIMILAR data sources */
                                if ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                    /* do we need SIMILAR_DATA_SOURCES_DUPS? */
                                    if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"]) && $graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                        $magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    /* do we need COUNT_SIMILAR_DS_DUPS? */
                                    if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"]) && $graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                        $magic_item["COUNT_SIMILAR_DS_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                        /* convert unknowns to '0' first */
                                    }
                                    $count_similar_ds_dups++;
                                    /* check if this item also qualifies for NODUPS  */
                                    if (!isset($sources_seen[$graph_items[$t]["data_template_rrd_id"]])) {
                                        if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
                                            $magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,{$def_name},{$def_name},UN,0,{$def_name},IF,IF";
                                            /* convert unknowns to '0' first */
                                        }
                                        if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"]) && $graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {
                                            $magic_item["COUNT_SIMILAR_DS_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,{$def_name},UN,0,1,IF,IF";
                                            /* convert unknowns to '0' first */
                                        }
                                        $count_similar_ds_nodups++;
                                        $sources_seen[$graph_items[$t]["data_template_rrd_id"]] = TRUE;
                                    }
                                }
                                # SIMILAR data sources
                            }
                            # matching consolidation function?
                        }
                        # only work on graph items, omit GRPINTs, COMMENTs and stuff
                    }
                    #  loop over all graph items
                    /* if there is only one item to total, don't even bother with the summation.
                     * Otherwise cdef=a,b,c,+,+ is fine. */
                    if ($count_all_ds_dups > 1 && isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
                        $magic_item["ALL_DATA_SOURCES_DUPS"] .= str_repeat(",+", $count_all_ds_dups - 2) . ",+";
                    }
                    if ($count_all_ds_nodups > 1 && isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
                        $magic_item["ALL_DATA_SOURCES_NODUPS"] .= str_repeat(",+", $count_all_ds_nodups - 2) . ",+";
                    }
                    if ($count_similar_ds_dups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
                        $magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= str_repeat(",+", $count_similar_ds_dups - 2) . ",+";
                    }
                    if ($count_similar_ds_nodups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
                        $magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= str_repeat(",+", $count_similar_ds_nodups - 2) . ",+";
                    }
                    if ($count_all_ds_dups > 1 && isset($magic_item["COUNT_ALL_DS_DUPS"])) {
                        $magic_item["COUNT_ALL_DS_DUPS"] .= str_repeat(",+", $count_all_ds_dups - 2) . ",+";
                    }
                    if ($count_all_ds_nodups > 1 && isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
                        $magic_item["COUNT_ALL_DS_NODUPS"] .= str_repeat(",+", $count_all_ds_nodups - 2) . ",+";
                    }
                    if ($count_similar_ds_dups > 1 && isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
                        $magic_item["COUNT_SIMILAR_DS_DUPS"] .= str_repeat(",+", $count_similar_ds_dups - 2) . ",+";
                    }
                    if ($count_similar_ds_nodups > 1 && isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
                        $magic_item["COUNT_SIMILAR_DS_NODUPS"] .= str_repeat(",+", $count_similar_ds_nodups - 2) . ",+";
                    }
                }
                $cdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval(isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id]) ? $cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id] : "0")), $cdef_string);
                /* ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
                if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
                    $cdef_string = str_replace("ALL_DATA_SOURCES_DUPS", $magic_item["ALL_DATA_SOURCES_DUPS"], $cdef_string);
                }
                if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
                    $cdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $magic_item["ALL_DATA_SOURCES_NODUPS"], $cdef_string);
                }
                if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
                    $cdef_string = str_replace("SIMILAR_DATA_SOURCES_DUPS", $magic_item["SIMILAR_DATA_SOURCES_DUPS"], $cdef_string);
                }
                if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
                    $cdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $magic_item["SIMILAR_DATA_SOURCES_NODUPS"], $cdef_string);
                }
                /* COUNT_ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
                if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
                    $cdef_string = str_replace("COUNT_ALL_DS_DUPS", $magic_item["COUNT_ALL_DS_DUPS"], $cdef_string);
                }
                if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
                    $cdef_string = str_replace("COUNT_ALL_DS_NODUPS", $magic_item["COUNT_ALL_DS_NODUPS"], $cdef_string);
                }
                if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
                    $cdef_string = str_replace("COUNT_SIMILAR_DS_DUPS", $magic_item["COUNT_SIMILAR_DS_DUPS"], $cdef_string);
                }
                if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
                    $cdef_string = str_replace("COUNT_SIMILAR_DS_NODUPS", $magic_item["COUNT_SIMILAR_DS_NODUPS"], $cdef_string);
                }
                /* data source item variables */
                $cdef_string = str_replace("CURRENT_DS_MINIMUM_VALUE", empty($graph_item["rrd_minimum"]) ? "0" : $graph_item["rrd_minimum"], $cdef_string);
                $cdef_string = str_replace("CURRENT_DS_MAXIMUM_VALUE", empty($graph_item["rrd_maximum"]) ? "0" : $graph_item["rrd_maximum"], $cdef_string);
                $cdef_string = str_replace("CURRENT_GRAPH_MINIMUM_VALUE", empty($graph["lower_limit"]) ? "0" : $graph["lower_limit"], $cdef_string);
                $cdef_string = str_replace("CURRENT_GRAPH_MAXIMUM_VALUE", empty($graph["upper_limit"]) ? "0" : $graph["upper_limit"], $cdef_string);
                /* replace query variables in cdefs */
                $cdef_string = rrd_substitute_host_query_data($cdef_string, $graph, $graph_item);
                /* make the initial "virtual" cdef name: 'cdef' + [a,b,c,d...] */
                $cdef_graph_defs .= "CDEF:cdef" . generate_graph_def_name(strval($i)) . "=";
                /* prohibit command injection and provide platform specific quoting */
                $cdef_graph_defs .= cacti_escapeshellarg(sanitize_cdef($cdef_string), true);
                $cdef_graph_defs .= " \\\n";
                /* the CDEF cache is so we do not create duplicate CDEF's on a graph */
                $cdef_cache[$graph_item["cdef_id"]][$graph_item["data_template_rrd_id"]][$cf_id] = "{$i}";
            }
            /* add the cdef string to the end of the def string */
            $graph_defs .= $cdef_graph_defs;
            /* note the current item_id for easy access */
            $graph_item_id = $graph_item["graph_templates_item_id"];
            /* if we are not displaying a legend there is no point in us even processing the auto padding,
            		text format stuff. */
            if (!isset($graph_data_array["graph_nolegend"]) && $graph["auto_padding"] == "on") {
                /* only applies to AREA, STACK and LINEs */
                if (preg_match("/(AREA|STACK|LINE[123])/", $graph_item_types[$graph_item["graph_type_id"]])) {
                    $text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);
                    /* we are basing how much to pad on area and stack text format,
                    			not gprint. but of course the padding has to be displayed in gprint,
                    			how fun! */
                    $pad_number = $padding_estimate - $text_format_length;
                    //cacti_log("MAX: $padding_estimate, CURR: $text_format_lengths[$item_dsid], DSID: $item_dsid");
                    $text_padding = str_pad("", $pad_number);
                    /* two GPRINT's in a row screws up the padding, lets not do that */
                } else {
                    if ($graph_item_types[$graph_item["graph_type_id"]] == "GPRINT" && $last_graph_type == "GPRINT") {
                        $text_padding = "";
                    }
                }
                $last_graph_type = $graph_item_types[$graph_item["graph_type_id"]];
            }
            /* we put this in a variable so it can be manipulated before mainly used
            		if we want to skip it, like below */
            $current_graph_item_type = $graph_item_types[$graph_item["graph_type_id"]];
            /* IF this graph item has a data source... get a DEF name for it, or the cdef if that applies
            		to this graph item */
            if ($graph_item["cdef_id"] == "0") {
                if (isset($cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id])) {
                    $data_source_name = generate_graph_def_name(strval($cf_ds_cache[$graph_item["data_template_rrd_id"]][$cf_id]));
                } else {
                    $data_source_name = "";
                }
            } else {
                $data_source_name = "cdef" . generate_graph_def_name(strval($cdef_cache[$graph_item["cdef_id"]][$graph_item["data_template_rrd_id"]][$cf_id]));
            }
            /* to make things easier... if there is no text format set; set blank text */
            if (!isset($graph_variables["text_format"][$graph_item_id])) {
                $graph_variables["text_format"][$graph_item_id] = "";
            } else {
                $graph_variables["text_format"][$graph_item_id] = str_replace('"', '\\"', $graph_variables["text_format"][$graph_item_id]);
                /* escape doublequotes */
            }
            if (!isset($hardreturn[$graph_item_id])) {
                $hardreturn[$graph_item_id] = "";
            }
            /* +++++++++++++++++++++++ GRAPH ITEMS +++++++++++++++++++++++ */
            /* most of the calculations have been done above. now we have for print everything out
            		in an RRDTool-friendly fashion */
            $need_rrd_nl = TRUE;
            if (!isset($graph_data_array['export_csv'])) {
                if ($graph_item_types[$graph_item["graph_type_id"]] == "COMMENT") {
                    # perform variable substitution first (in case this will yield an empty results or brings command injection problems)
                    $comment_arg = rrd_substitute_host_query_data($graph_variables["text_format"][$graph_item_id], $graph, $graph_item);
                    # next, compute the argument of the COMMENT statement and perform injection counter measures
                    if (trim($comment_arg) == '') {
                        # an empty COMMENT must be treated with care
                        $comment_arg = cacti_escapeshellarg(' ' . $hardreturn[$graph_item_id]);
                    } else {
                        $comment_arg = cacti_escapeshellarg($comment_arg . $hardreturn[$graph_item_id]);
                    }
                    # create rrdtool specific command line
                    $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . str_replace(":", "\\:", $comment_arg) . " ";
                } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "GPRINT" && !isset($graph_data_array["graph_nolegend"])) {
                    $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                    /* escape colons */
                    $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $data_source_name . ":" . $consolidation_functions[$graph_item["consolidation_function_id"]] . ":" . cacti_escapeshellarg($text_padding . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id]) . " ";
                } elseif (preg_match("/^(AREA|LINE[123]|STACK|HRULE|VRULE)\$/", $graph_item_types[$graph_item["graph_type_id"]])) {
                    /* initialize any color syntax for graph item */
                    if (empty($graph_item["hex"])) {
                        $graph_item_color_code = "";
                    } else {
                        $graph_item_color_code = "#" . $graph_item["hex"];
                        $graph_item_color_code .= $graph_item["alpha"];
                    }
                    if (preg_match("/^(AREA|LINE[123])\$/", $graph_item_types[$graph_item["graph_type_id"]])) {
                        $graph_item_stack_type = $graph_item_types[$graph_item["graph_type_id"]];
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $data_source_name . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . " ";
                    } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "STACK") {
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        $txt_graph_items .= $graph_item_stack_type . ":" . $data_source_name . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . ":STACK";
                    } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "HRULE") {
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        $graph_variables["value"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["value"][$graph_item_id]);
                        /* escape colons */
                        /* perform variable substitution; if this does not return a number, rrdtool will FAIL! */
                        $substitute = rrd_substitute_host_query_data($graph_variables["value"][$graph_item_id], $graph, $graph_item);
                        if (is_numeric($substitute)) {
                            $graph_variables["value"][$graph_item_id] = $substitute;
                        }
                        $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $graph_variables["value"][$graph_item_id] . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . " ";
                    } elseif ($graph_item_types[$graph_item["graph_type_id"]] == "VRULE") {
                        $graph_variables["text_format"][$graph_item_id] = str_replace(":", "\\:", $graph_variables["text_format"][$graph_item_id]);
                        /* escape colons */
                        if (substr_count($graph_item["value"], ":")) {
                            $value_array = explode(":", $graph_item["value"]);
                            if ($value_array[0] < 0) {
                                $value = date("U") - -3600 * $value_array[0] - 60 * $value_array[1];
                            } else {
                                $value = date("U", mktime($value_array[0], $value_array[1], 0));
                            }
                        } else {
                            if (is_numeric($graph_item["value"])) {
                                $value = $graph_item["value"];
                            }
                        }
                        $txt_graph_items .= $graph_item_types[$graph_item["graph_type_id"]] . ":" . $value . $graph_item_color_code . ":" . cacti_escapeshellarg($graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id]) . " ";
                    }
                } else {
                    $need_rrd_nl = FALSE;
                }
            } else {
                if (preg_match("/^(AREA|LINE[123]|STACK)\$/", $graph_item_types[$graph_item["graph_type_id"]])) {
                    /* give all export items a name */
                    if (trim($graph_variables["text_format"][$graph_item_id]) == "") {
                        $legend_name = "col" . $j . "-" . $data_source_name;
                    } else {
                        $legend_name = $graph_variables["text_format"][$graph_item_id];
                    }
                    $stacked_columns["col" . $j] = $graph_item_types[$graph_item["graph_type_id"]] == "STACK" ? 1 : 0;
                    $j++;
                    $txt_graph_items .= "XPORT:" . cacti_escapeshellarg($data_source_name) . ":" . str_replace(":", "", cacti_escapeshellarg($legend_name));
                } else {
                    $need_rrd_nl = FALSE;
                }
            }
            $i++;
            if ($i < sizeof($graph_items) && $need_rrd_nl) {
                $txt_graph_items .= RRD_NL;
            }
        }
    }
    if (!isset($graph_data_array['export_csv']) || $graph_data_array['export_csv'] != true) {
        $graph_array = api_plugin_hook_function('rrd_graph_graph_options', array('graph_opts' => $graph_opts, 'graph_defs' => $graph_defs, 'txt_graph_items' => $txt_graph_items, 'graph_id' => $local_graph_id, 'start' => $graph_start, 'end' => $graph_end));
        if (!empty($graph_array)) {
            $graph_defs = $graph_array['graph_defs'];
            $txt_graph_items = $graph_array['txt_graph_items'];
            $graph_opts = $graph_array['graph_opts'];
        }
        /* either print out the source or pass the source onto rrdtool to get us a nice PNG */
        if (isset($graph_data_array["print_source"])) {
            print "<PRE>" . htmlspecialchars(read_config_option("path_rrdtool") . " graph " . $graph_opts . $graph_defs . $txt_graph_items) . "</PRE>";
        } else {
            if (isset($graph_data_array["export"])) {
                rrdtool_execute("graph {$graph_opts}{$graph_defs}{$txt_graph_items}", false, RRDTOOL_OUTPUT_NULL, $rrdtool_pipe);
                return 0;
            } elseif (isset($graph_data_array['export_realtime'])) {
                $output_flag = RRDTOOL_OUTPUT_GRAPH_DATA;
                $output = rrdtool_execute("graph {$graph_opts}{$graph_defs}{$txt_graph_items}", false, $output_flag, $rrdtool_pipe);
                //cacti_log(str_replace(RRD_NL, ' ', "rrdtool graph $graph_opts$graph_defs$txt_graph_items"));
                if ($fp = fopen($graph_data_array['export_realtime'], 'w')) {
                    fwrite($fp, $output, strlen($output));
                    fclose($fp);
                    chmod($graph_data_array['export_realtime'], 0644);
                }
                return $output;
            } else {
                $graph_data_array = boost_prep_graph_array($graph_data_array);
                if (!isset($graph_data_array["output_flag"])) {
                    $output_flag = RRDTOOL_OUTPUT_GRAPH_DATA;
                } else {
                    $output_flag = $graph_data_array["output_flag"];
                }
                $output = rrdtool_execute("graph {$graph_opts}{$graph_defs}{$txt_graph_items}", false, $output_flag, $rrdtool_pipe);
                boost_graph_set_file($output, $local_graph_id, $rra_id);
                return $output;
            }
        }
    } else {
        $output_flag = RRDTOOL_OUTPUT_STDOUT;
        $xport_array = rrdxport2array(rrdtool_execute("xport {$graph_opts}{$graph_defs}{$txt_graph_items}", false, $output_flag));
        /* add host and graph information */
        $xport_array["meta"]["stacked_columns"] = $stacked_columns;
        $xport_array["meta"]["title_cache"] = cacti_escapeshellarg($graph["title_cache"]);
        $xport_array["meta"]["vertical_label"] = cacti_escapeshellarg($graph["vertical_label"]);
        $xport_array["meta"]["local_graph_id"] = $local_graph_id;
        $xport_array["meta"]["host_id"] = $graph["host_id"];
        return $xport_array;
    }
}
		ON (data_local.data_template_id=data_template.id)
		WHERE data_local.id=data_template_data.local_data_id
		$sql_where");

/* issue warnings and start message if applicable */
print "WARNING: Do not interrupt this script.  Interrupting during rename can cause issues\n";
debug("There are '" . sizeof($data_source_list) . "' Data Sources to rename");

$i = 1;
foreach ($data_source_list as $data_source) {
	if (!$debug)
		print ".";
	debug("Data Source Name '" . $data_source["name_cache"] . "' starting");
	api_reapply_suggested_data_source_title($data_source["local_data_id"]);
	update_data_source_title_cache($data_source["local_data_id"]);
	debug("Data Source Rename Done for Data Source '" . addslashes(get_data_source_title($data_source["local_data_id"])) . "'");
	$i++;
}

/*	display_help - displays the usage of the function */
function display_help() {
	print "Cacti Reapply Data Sources Names Script 1.0, Copyright 2008 - The Cacti Group\n\n";
	print "usage: poller_data_sources_reapply_names.php --id=[host_id|All][host_id1|host_id2|...] [--filter=[search_string] [--debug] [-h] [--help] [-v] [--version]\n\n";
	print "--id=host_id        - The host_id or 'All' or a pipe delimited list of host_id's\n";
	print "--filter=search_str - A data template name or data source title to search for\n";
	print "--debug             - Display verbose output during execution\n";
	print "-v --version        - Display this help message\n";
	print "-h --help           - Display this help message\n";
}

function debug($message) {
Beispiel #9
0
function update_data_source_title_cache($local_data_id)
{
    db_execute("update data_template_data set name_cache='" . addslashes(get_data_source_title($local_data_id)) . "' where local_data_id={$local_data_id}");
    api_plugin_hook_function('update_data_source_title_cache', $local_data_id);
}
Beispiel #10
0
function ds_edit()
{
    global $struct_data_source, $struct_data_source_item, $data_source_types;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('host_id'));
    /* ==================================================== */
    api_plugin_hook('data_source_edit_top');
    $use_data_template = true;
    $host_id = 0;
    if (!empty($_REQUEST['id'])) {
        $data_local = db_fetch_row_prepared('SELECT host_id, data_template_id FROM data_local WHERE id = ?', array($_REQUEST['id']));
        $data = db_fetch_row_prepared('SELECT * FROM data_template_data WHERE local_data_id = ?', array($_REQUEST['id']));
        if (isset($data_local['data_template_id']) && $data_local['data_template_id'] >= 0) {
            $data_template = db_fetch_row_prepared('SELECT id, name FROM data_template WHERE id = ?', array($data_local['data_template_id']));
            $data_template_data = db_fetch_row_prepared('SELECT * FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', array($data_local['data_template_id']));
        } else {
            $_SESSION['sess_messages'] = 'Data Source "' . $_REQUEST['id'] . '" does not exist.';
            header('Location: data_sources.php');
            exit;
        }
        $header_label = '[edit: ' . htmlspecialchars(get_data_source_title($_REQUEST['id'])) . ']';
        if (empty($data_local['data_template_id'])) {
            $use_data_template = false;
        }
    } else {
        $header_label = '[new]';
        $use_data_template = false;
    }
    /* handle debug mode */
    if (isset($_REQUEST['debug'])) {
        if ($_REQUEST['debug'] == '0') {
            kill_session_var('ds_debug_mode');
        } elseif ($_REQUEST['debug'] == '1') {
            $_SESSION['ds_debug_mode'] = true;
        }
    }
    top_header();
    if (!empty($_REQUEST['id'])) {
        ?>
		<table width='100%' align='center'>
			<tr>
				<td class='textInfo' colspan='2' valign='top'>
					<?php 
        print htmlspecialchars(get_data_source_title($_REQUEST['id']));
        ?>
				</td>
				<td class='textInfo' align='right' valign='top'>
					<span class='linkMarker'>*<a href='<?php 
        print htmlspecialchars('data_sources.php?action=ds_edit&id=' . (isset($_REQUEST['id']) ? $_REQUEST['id'] : '0'));
        ?>
&debug=<?php 
        print isset($_SESSION['ds_debug_mode']) ? '0' : '1';
        ?>
'>Turn <strong><?php 
        print isset($_SESSION['ds_debug_mode']) ? 'Off' : 'On';
        ?>
</strong> Data Source Debug Mode.</a><br>
					<?php 
        if (!empty($data_template['id'])) {
            ?>
<span class='linkMarker'>*<a href='<?php 
            print htmlspecialchars('data_templates.php?action=template_edit&id=' . (isset($data_template['id']) ? $data_template['id'] : '0'));
            ?>
'>Edit Data Template.</a><br><?php 
        }
        if (!empty($_REQUEST['host_id']) || !empty($data_local['host_id'])) {
            ?>
<span class='linkMarker'>*<a href='<?php 
            print htmlspecialchars('host.php?action=edit&id=' . (isset($_REQUEST['host_id']) ? $_REQUEST['host_id'] : $data_local['host_id']));
            ?>
'>Edit Device.</a><br><?php 
        }
        ?>
				</td>
			</tr>
		</table>
		<br>
		<?php 
    }
    html_start_box("<strong>Data Template Selection</strong> {$header_label}", '100%', '', '3', 'center', '');
    $form_array = array('data_template_id' => array('method' => 'drop_sql', 'friendly_name' => 'Selected Data Template', 'description' => 'The name given to this data template.', 'value' => isset($data_template) ? $data_template['id'] : '0', 'none_value' => 'None', 'sql' => 'SELECT id,name FROM data_template order by name'), 'host_id' => array('method' => 'drop_sql', 'friendly_name' => 'Device', 'description' => 'Choose the host that this graph belongs to.', 'value' => isset($_REQUEST['host_id']) ? $_REQUEST['host_id'] : $data_local['host_id'], 'none_value' => 'None', 'sql' => "SELECT id,CONCAT_WS('',description,' (',hostname,')') as name FROM host order by description,hostname"), '_data_template_id' => array('method' => 'hidden', 'value' => isset($data_template) ? $data_template['id'] : '0'), '_host_id' => array('method' => 'hidden', 'value' => empty($data_local['host_id']) ? isset($_REQUEST['host_id']) ? $_REQUEST['host_id'] : '0' : $data_local['host_id']), '_data_input_id' => array('method' => 'hidden', 'value' => isset($data['data_input_id']) ? $data['data_input_id'] : '0'), 'data_template_data_id' => array('method' => 'hidden', 'value' => isset($data) ? $data['id'] : '0'), 'local_data_template_data_id' => array('method' => 'hidden', 'value' => isset($data) ? $data['local_data_template_data_id'] : '0'), 'local_data_id' => array('method' => 'hidden', 'value' => isset($data) ? $data['local_data_id'] : '0'));
    draw_edit_form(array('config' => array(), 'fields' => $form_array));
    html_end_box();
    /* only display the "inputs" area if we are using a data template for this data source */
    if (!empty($data['data_template_id'])) {
        $template_data_rrds = db_fetch_assoc_prepared('SELECT * FROM data_template_rrd WHERE local_data_id = ? ORDER BY data_source_name', array($_REQUEST['id']));
        html_start_box('<strong>Supplemental Data Template Data</strong>', '100%', '', '3', 'center', '');
        draw_nontemplated_fields_data_source($data['data_template_id'], $data['local_data_id'], $data, '|field|', '<strong>Data Source Fields</strong>', true, true, 0);
        draw_nontemplated_fields_data_source_item($data['data_template_id'], $template_data_rrds, '|field|_|id|', '<strong>Data Source Item Fields</strong>', true, true, true, 0);
        draw_nontemplated_fields_custom_data($data['id'], 'value_|id|', '<strong>Custom Data</strong>', true, true, 0);
        form_hidden_box('save_component_data', '1', '');
        html_end_box();
    }
    if ((isset($_REQUEST['id']) || isset($_REQUEST['new'])) && empty($data['data_template_id'])) {
        html_start_box('<strong>Data Source</strong>', '100%', '', '3', 'center', '');
        $form_array = array();
        while (list($field_name, $field_array) = each($struct_data_source)) {
            $form_array += array($field_name => $struct_data_source[$field_name]);
            if (!($use_data_template == false || !empty($data_template_data['t_' . $field_name]) || $field_array['flags'] == 'NOTEMPLATE')) {
                $form_array[$field_name]['description'] = '';
            }
            $form_array[$field_name]['value'] = isset($data[$field_name]) ? $data[$field_name] : '';
            $form_array[$field_name]['form_id'] = empty($data['id']) ? '0' : $data['id'];
            if (!($use_data_template == false || !empty($data_template_data['t_' . $field_name]) || $field_array['flags'] == 'NOTEMPLATE')) {
                $form_array[$field_name]['method'] = 'template_' . $form_array[$field_name]['method'];
            }
        }
        draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => inject_form_variables($form_array, isset($data) ? $data : array())));
        html_end_box();
        /* fetch ALL rrd's for this data source */
        if (!empty($_REQUEST['id'])) {
            $template_data_rrds = db_fetch_assoc_prepared('SELECT id, data_source_name FROM data_template_rrd WHERE local_data_id = ? ORDER BY data_source_name', array($_REQUEST['id']));
        }
        /* select the first "rrd" of this data source by default */
        if (empty($_REQUEST['view_rrd'])) {
            $_REQUEST['view_rrd'] = isset($template_data_rrds[0]['id']) ? $template_data_rrds[0]['id'] : '0';
        }
        /* get more information about the rrd we chose */
        if (!empty($_REQUEST['view_rrd'])) {
            $local_data_template_rrd_id = db_fetch_cell_prepared('SELECT local_data_template_rrd_id FROM data_template_rrd WHERE id = ?', array($_REQUEST['view_rrd']));
            $rrd = db_fetch_row_prepared('SELECT * FROM data_template_rrd WHERE id = ?', array($_REQUEST['view_rrd']));
            $rrd_template = db_fetch_row_prepared('SELECT * FROM data_template_rrd WHERE id = ?', array($local_data_template_rrd_id));
            $header_label = '[edit: ' . $rrd['data_source_name'] . ']';
        } else {
            $header_label = '';
        }
        $i = 0;
        if (isset($template_data_rrds)) {
            if (sizeof($template_data_rrds) > 1) {
                /* draw the data source tabs on the top of the page */
                print "\t<table class='tabs' width='100%' cellspacing='0' cellpadding='3' align='center'>\n\t\t\t\t\t<tr>\n";
                foreach ($template_data_rrds as $template_data_rrd) {
                    $i++;
                    print "\t<td " . ($template_data_rrd['id'] == $_REQUEST['view_rrd'] ? "class='even'" : "class='odd'") . " width='" . (strlen($template_data_rrd['data_source_name']) * 9 + 50) . "' align='center' class='tab'>\n\t\t\t\t\t\t\t\t<span class='textHeader'><a href='" . htmlspecialchars('data_sources.php?action=ds_edit&id=' . $_REQUEST['id'] . '&view_rrd=' . $template_data_rrd['id']) . "'>{$i}: " . htmlspecialchars($template_data_rrd['data_source_name']) . '</a>' . ($use_data_template == false ? " <a href='" . htmlspecialchars('data_sources.php?action=rrd_remove&id=' . $template_data_rrd['id'] . '&local_data_id=' . $_REQUEST['id']) . "'><img src='images/delete_icon.gif' border='0' alt='Delete'></a>" : '') . "</span>\n\t\t\t\t\t\t\t</td>\n\n\t\t\t\t\t\t\t<td width='1'></td>\n";
                }
                print "\n\t\t\t\t\t<td></td>\n\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n";
            } elseif (sizeof($template_data_rrds) == 1) {
                $_REQUEST['view_rrd'] = $template_data_rrds[0]['id'];
            }
        }
        html_start_box('', '100%', '', '3', 'center', '');
        print "\t<tr>\n\t\t\t\t<td class='textHeaderDark'>\n\t\t\t\t\t<strong>Data Source Item</strong> {$header_label}\n\t\t\t\t</td>\n\t\t\t\t<td class='textHeaderDark' align='right'>\n\t\t\t\t\t" . (!empty($_REQUEST['id']) && empty($data_template['id']) ? "<strong><a class='linkOverDark' href='" . htmlspecialchars('data_sources.php?action=rrd_add&id=' . $_REQUEST['id']) . "'>New</a>&nbsp;</strong>" : '') . "\n\t\t\t\t</td>\n\t\t\t</tr>\n";
        /* data input fields list */
        if (empty($data['data_input_id']) || db_fetch_cell_prepared('SELECT type_id FROM data_input WHERE id = ?', array($data['data_input_id'])) > '1') {
            unset($struct_data_source_item['data_input_field_id']);
        } else {
            $struct_data_source_item['data_input_field_id']['sql'] = "SELECT id,CONCAT(data_name,' - ',name) as name FROM data_input_fields WHERE data_input_id=" . $data['data_input_id'] . " and input_output='out' and update_rra='on' order by data_name,name";
        }
        $form_array = array();
        while (list($field_name, $field_array) = each($struct_data_source_item)) {
            $form_array += array($field_name => $struct_data_source_item[$field_name]);
            if (!($use_data_template == false || $rrd_template['t_' . $field_name] == 'on')) {
                $form_array[$field_name]['description'] = '';
            }
            $form_array[$field_name]['value'] = isset($rrd) ? $rrd[$field_name] : '';
            if (!($use_data_template == false || $rrd_template['t_' . $field_name] == 'on')) {
                $form_array[$field_name]['method'] = 'template_' . $form_array[$field_name]['method'];
            }
        }
        draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => array('data_template_rrd_id' => array('method' => 'hidden', 'value' => isset($rrd) ? $rrd['id'] : '0'), 'local_data_template_rrd_id' => array('method' => 'hidden', 'value' => isset($rrd) ? $rrd['local_data_template_rrd_id'] : '0')) + $form_array));
        html_end_box();
        /* data source data goes here */
        data_edit();
        form_hidden_box('current_rrd', $_REQUEST['view_rrd'], '0');
    }
    /* display the debug mode box if the user wants it */
    if (isset($_SESSION['ds_debug_mode']) && isset($_REQUEST['id'])) {
        ?>
		<table width='100%' align='center'>
			<tr>
				<td>
					<span class='textInfo'>Data Source Debug</span><br>
					<pre><?php 
        print @rrdtool_function_create($_REQUEST['id'], true);
        ?>
</pre>
				</td>
			</tr>
		</table>
		<?php 
    }
    if (isset($_REQUEST['id']) || isset($_REQUEST['new'])) {
        form_hidden_box('save_component_data_source', '1', '');
    } else {
        form_hidden_box('save_component_data_source_new', '1', '');
    }
    form_save_button('data_sources.php');
    api_plugin_hook('data_source_edit_bottom');
    bottom_footer();
}
Beispiel #11
0
function rrdtool_function_graph($local_graph_id, $rra_id, $graph_data_array, $rrd_struc = array()) {
	global $config;
	include(CACTI_BASE_PATH . "/include/global_arrays.php");
	require(CACTI_BASE_PATH . "/include/presets/preset_rra_arrays.php");
	require(CACTI_BASE_PATH . "/include/graph/graph_arrays.php");
	include_once(CACTI_BASE_PATH . "/lib/cdef.php");
	include_once(CACTI_BASE_PATH . "/lib/vdef.php");
	include_once(CACTI_BASE_PATH . "/lib/graph_variables.php");
	include_once(CACTI_BASE_PATH . "/lib/time.php");

	/* set the rrdtool default font */
	if (read_config_option("path_rrdtool_default_font")) {
		putenv("RRD_DEFAULT_FONT=" . read_config_option("path_rrdtool_default_font"));
	}

	/* before we do anything; make sure the user has permission to view this graph,
	if not then get out */
	if ((read_config_option("auth_method") != 0) && (isset($_SESSION["sess_user_id"]))) {
		$access_denied = !(is_graph_allowed($local_graph_id));

		if ($access_denied == true) {
			return "GRAPH ACCESS DENIED";
		}
	}

	$data = api_plugin_hook_function('rrdtool_function_graph_cache_check', array('local_graph_id' => $local_graph_id,'rra_id' => $rra_id,'rrd_struc' => $rrd_struc,'graph_data_array' => $graph_data_array, 'return' => false));
	if (isset($data['return']) && $data['return'] != false)
		return $data['return'];

	/* find the step and how often this graph is updated with new data */
	$ds_step = db_fetch_cell("select
		data_template_data.rrd_step
		from (data_template_data,data_template_rrd,graph_templates_item)
		where graph_templates_item.task_item_id=data_template_rrd.id
		and data_template_rrd.local_data_id=data_template_data.local_data_id
		and graph_templates_item.local_graph_id=$local_graph_id
		limit 0,1");
	$ds_step = empty($ds_step) ? 300 : $ds_step;

	/* if no rra was specified, we need to figure out which one RRDTool will choose using
	 * "best-fit" resolution fit algorithm */
	if (empty($rra_id)) {
		if ((empty($graph_data_array["graph_start"])) || (empty($graph_data_array["graph_end"]))) {
			$rra["rows"] = 600;
			$rra["steps"] = 1;
			$rra["timespan"] = 86400;
		}else{
			/* get a list of RRAs related to this graph */
			$rras = get_associated_rras($local_graph_id);

			if (sizeof($rras) > 0) {
				foreach ($rras as $unchosen_rra) {
					/* the timespan specified in the RRA "timespan" field may not be accurate */
					$real_timespan = ($ds_step * $unchosen_rra["steps"] * $unchosen_rra["rows"]);

					/* make sure the current start/end times fit within each RRA's timespan */
					if ( (($graph_data_array["graph_end"] - $graph_data_array["graph_start"]) <= $real_timespan) && ((time() - $graph_data_array["graph_start"]) <= $real_timespan) ) {
						/* is this RRA better than the already chosen one? */
						if ((isset($rra)) && ($unchosen_rra["steps"] < $rra["steps"])) {
							$rra = $unchosen_rra;
						}else if (!isset($rra)) {
							$rra = $unchosen_rra;
						}
					}
				}
			}

			if (!isset($rra)) {
				$rra["rows"] = 600;
				$rra["steps"] = 1;
			}
		}
	}else{
		$rra = db_fetch_row("select timespan,rows,steps from rra where id=$rra_id");
	}

	$seconds_between_graph_updates = ($ds_step * $rra["steps"]);

	$graph = db_fetch_row("select
		graph_local.device_id,
		graph_local.snmp_query_id,
		graph_local.snmp_index,
		graph_templates_graph.title_cache,
		graph_templates_graph.vertical_label,
		graph_templates_graph.slope_mode,
		graph_templates_graph.auto_scale,
		graph_templates_graph.auto_scale_opts,
		graph_templates_graph.auto_scale_log,
		graph_templates_graph.scale_log_units,
		graph_templates_graph.auto_scale_rigid,
		graph_templates_graph.alt_y_grid,
		graph_templates_graph.auto_padding,
		graph_templates_graph.base_value,
		graph_templates_graph.upper_limit,
		graph_templates_graph.lower_limit,
		graph_templates_graph.height,
		graph_templates_graph.width,
		graph_templates_graph.image_format_id,
		graph_templates_graph.unit_value,
		graph_templates_graph.unit_exponent_value,
		graph_templates_graph.export,
		graph_templates_graph.right_axis,
		graph_templates_graph.right_axis_label,
		graph_templates_graph.right_axis_format,
		graph_templates_graph.only_graph,
		graph_templates_graph.full_size_mode,
		graph_templates_graph.no_gridfit,
		graph_templates_graph.x_grid,
		graph_templates_graph.unit_length,
		graph_templates_graph.colortag_back,
		graph_templates_graph.colortag_canvas,
		graph_templates_graph.colortag_shadea,
		graph_templates_graph.colortag_shadeb,
		graph_templates_graph.colortag_grid,
		graph_templates_graph.colortag_mgrid,
		graph_templates_graph.colortag_font,
		graph_templates_graph.colortag_axis,
		graph_templates_graph.colortag_frame,
		graph_templates_graph.colortag_arrow,
		graph_templates_graph.font_render_mode,
		graph_templates_graph.font_smoothing_threshold,
		graph_templates_graph.graph_render_mode,
		graph_templates_graph.pango_markup,
		graph_templates_graph.interlaced,
		graph_templates_graph.tab_width,
		graph_templates_graph.watermark,
		graph_templates_graph.force_rules_legend,
		graph_templates_graph.legend_position,
		graph_templates_graph.legend_direction,
		graph_templates_graph.grid_dash,
		graph_templates_graph.border
		from (graph_templates_graph,graph_local)
		where graph_local.id=graph_templates_graph.local_graph_id
		and graph_templates_graph.local_graph_id=$local_graph_id");

	/* lets make that sql query... */
	$graph_items = db_fetch_assoc("select
		graph_templates_item.id as graph_templates_item_id,
		graph_templates_item.cdef_id,
		graph_templates_item.vdef_id,
		graph_templates_item.text_format,
		graph_templates_item.value,
		graph_templates_item.hard_return,
		graph_templates_item.consolidation_function_id,
		graph_templates_item.graph_type_id,
		graph_templates_item.line_width,
		graph_templates_item.dashes,
		graph_templates_item.dash_offset,
		graph_templates_item.shift,
		graph_templates_item.textalign,
		graph_templates_gprint.gprint_text,
		colors.hex,
		graph_templates_item.alpha,
		data_template_rrd.id as data_template_rrd_id,
		data_template_rrd.local_data_id,
		data_template_rrd.rrd_minimum,
		data_template_rrd.rrd_maximum,
		data_template_rrd.data_source_name,
		data_template_rrd.local_data_template_rrd_id
		from graph_templates_item
		left join data_template_rrd on (graph_templates_item.task_item_id=data_template_rrd.id)
		left join colors on (graph_templates_item.color_id=colors.id)
		left join graph_templates_gprint on (graph_templates_item.gprint_id=graph_templates_gprint.id)
		where graph_templates_item.local_graph_id=$local_graph_id
		order by graph_templates_item.sequence");

	/* +++++++++++++++++++++++ GRAPH OPTIONS +++++++++++++++++++++++ */

	$rrdtool_version = read_config_option("rrdtool_version");

	/* export options: either output to stream or to file */
	if (isset($graph_data_array["export"])) {
		$graph_opts = read_config_option("path_html_export") . "/" . $graph_data_array["export_filename"] . RRD_NL;
	}else{
		if (empty($graph_data_array["output_filename"])) {
				$graph_opts = "-" . RRD_NL;
		}else{
			$graph_opts = $graph_data_array["output_filename"] . RRD_NL;
		}
	}

	# image format
	$graph_opts .= rrdgraph_image_format($graph["image_format_id"], $rrdtool_version);

	# start and end time
	list($graph_start, $graph_end) = rrdgraph_start_end($graph_data_array, $rra, $seconds_between_graph_updates);
	$graph["graph_start"] = $graph_start;
	$graph["graph_end"] = $graph_end;
	$graph_opts .= "--start=$graph_start" . RRD_NL . "--end=$graph_end" . RRD_NL;

	$graph_opts .= rrdgraph_opts($graph, $graph_data_array, $rrdtool_version);

	$graph_opts .= rrdgraph_scale($graph);

	$graph_date = date_time_format();

	/* display the timespan for zoomed graphs */
	if ((isset($graph_data_array["graph_start"])) && (isset($graph_data_array["graph_end"]))) {
		if (($graph_data_array["graph_start"] < 0) && ($graph_data_array["graph_end"] < 0)) {
			if ($rrdtool_version != RRD_VERSION_1_0) {
				$graph_opts .= "COMMENT:\"" . __("From") . " " . str_replace(":", "\:", date($graph_date, time()+$graph_data_array["graph_start"])) . " " . __("To") . " " . str_replace(":", "\:", date($graph_date, time()+$graph_data_array["graph_end"])) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}else {
				$graph_opts .= "COMMENT:\"" . __("From") . " " . date($graph_date, time()+$graph_data_array["graph_start"]) . " " . __("To") . " " . date($graph_date, time()+$graph_data_array["graph_end"]) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}
		}else if (($graph_data_array["graph_start"] >= 0) && ($graph_data_array["graph_end"] >= 0)) {
			if ($rrdtool_version != RRD_VERSION_1_0) {
				$graph_opts .= "COMMENT:\"" . __("From") . " " . str_replace(":", "\:", date($graph_date, $graph_data_array["graph_start"])) . " " . __("To") . " " . str_replace(":", "\:", date($graph_date, $graph_data_array["graph_end"])) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}else {
				$graph_opts .= "COMMENT:\"" . __("From") . " " . date($graph_date, $graph_data_array["graph_start"]) . " " . __("To") . " " . date($graph_date, $graph_data_array["graph_end"]) . "\\c\"" . RRD_NL . "COMMENT:\"  \\n\"" . RRD_NL;
			}
		}
	}


	/* Replace "|query_*|" in the graph command to replace e.g. vertical_label.  */
	$graph_opts = rrd_substitute_device_query_data($graph_opts, $graph, NULL);


	/* define some variables */
	$graph_defs = "";
	$txt_graph_items = "";
	$text_padding = "";
	$greatest_text_format = 0;
	$last_graph_type = "";
	$i = 0; $j = 0;
	$last_graph_cf = array();
	if (sizeof($graph_items) > 0) {

		/* we need to add a new column "cf_reference", so unless PHP 5 is used, this foreach syntax is required */
		foreach ($graph_items as $key => $graph_item) {
			/* mimic the old behavior: LINE[123], AREA and STACK items use the CF specified in the graph item */
			if ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREA  ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREASTACK ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3 ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINESTACK ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_TICK) {
				$graph_cf = $graph_item["consolidation_function_id"];
				/* remember the last CF for this data source for use with GPRINT
				 * if e.g. an AREA/AVERAGE and a LINE/MAX is used
				 * we will have AVERAGE first and then MAX, depending on GPRINT sequence */
				$last_graph_cf["data_source_name"]["local_data_template_rrd_id"] = $graph_cf;
				/* remember this for second foreach loop */
				$graph_items[$key]["cf_reference"] = $graph_cf;
			}elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_AVERAGE) {
				$graph_cf = $graph_item["consolidation_function_id"];
				$graph_items[$key]["cf_reference"] = $graph_cf;
			}elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_LAST) {
				$graph_cf = $graph_item["consolidation_function_id"];
				$graph_items[$key]["cf_reference"] = $graph_cf;
			}elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_MAX) {
				$graph_cf = $graph_item["consolidation_function_id"];
				$graph_items[$key]["cf_reference"] = $graph_cf;
			}elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_MIN) {
				$graph_cf = $graph_item["consolidation_function_id"];
				$graph_items[$key]["cf_reference"] = $graph_cf;
				#}elseif ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT) {
				#/* ATTENTION!
				# * the "CF" given on graph_item edit screen for GPRINT is indeed NOT a real "CF",
				# * but an aggregation function
				# * see "man rrdgraph_data" for the correct VDEF based notation
				# * so our task now is to "guess" the very graph_item, this GPRINT is related to
				# * and to use that graph_item's CF */
				#if (isset($last_graph_cf["data_source_name"]["local_data_template_rrd_id"])) {
				#	$graph_cf = $last_graph_cf["data_source_name"]["local_data_template_rrd_id"];
				#	/* remember this for second foreach loop */
				#	$graph_items[$key]["cf_reference"] = $graph_cf;
				#} else {
				#	$graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
				#	/* remember this for second foreach loop */
				#	$graph_items[$key]["cf_reference"] = $graph_cf;
				#}
			}else{
				/* all other types are based on the best matching CF */
				#GRAPH_ITEM_TYPE_COMMENT
				#GRAPH_ITEM_TYPE_HRULE
				#GRAPH_ITEM_TYPE_VRULE
				#GRAPH_ITEM_TYPE_TEXTALIGN
				$graph_cf = generate_graph_best_cf($graph_item["local_data_id"], $graph_item["consolidation_function_id"]);
				/* remember this for second foreach loop */
				$graph_items[$key]["cf_reference"] = $graph_cf;
			}

			if ((!empty($graph_item["local_data_id"])) && (!isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$graph_cf]))) {
				/* use a user-specified ds path if one is entered */
				$data_source_path = get_data_source_path($graph_item["local_data_id"], true);

				/* FOR WIN32: Escape all colon for drive letters (ex. D\:/path/to/rra) */
				$data_source_path = str_replace(":", "\:", $data_source_path);

				if (!empty($data_source_path)) {
					/* NOTE: (Update) Data source DEF names are created using the graph_item_id; then passed
					to a function that matches the digits with letters. rrdtool likes letters instead
					of numbers in DEF names; especially with CDEF's. cdef's are created
					the same way, except a 'cdef' is put on the beginning of the hash */
					$graph_defs .= "DEF:" . generate_graph_def_name(strval($i)) . "=\"$data_source_path\":" . $graph_item["data_source_name"] . ":" . $consolidation_functions[$graph_cf];
					if ($graph_item["shift"] == CHECKED && $graph_item["value"] > 0) {	# create a SHIFTed DEF
						$graph_defs .= ":start=" . $graph["graph_start"] . "-" . $graph_item["value"];
						$graph_defs .= ":end=" . $graph["graph_end"] . "-" . $graph_item["value"];
					}
					$graph_defs .= RRD_NL;

					$cf_ds_cache{$graph_item["data_template_rrd_id"]}[$graph_cf] = "$i";

					$i++;
				}
			}

			/* cache cdef value here to support data query variables in the cdef string */
			if (empty($graph_item["cdef_id"])) {
				$graph_item["cdef_cache"] = "";
				$graph_items[$j]["cdef_cache"] = "";
			}else{
				$graph_item["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
				$graph_items[$j]["cdef_cache"] = get_cdef($graph_item["cdef_id"]);
			}

			/* cache vdef value here */
			if (empty($graph_item["vdef_id"])) {
				$graph_item["vdef_cache"] = "";
				$graph_items[$j]["vdef_cache"] = "";
			}else{
				$graph_item["vdef_cache"] = get_vdef($graph_item["vdef_id"]);
				$graph_items[$j]["vdef_cache"] = get_vdef($graph_item["vdef_id"]);
			}


			/* +++++++++++++++++++++++ LEGEND: TEXT SUBSTITUTION (<>'s) +++++++++++++++++++++++ */

			/* note the current item_id for easy access */
			$graph_item_id = $graph_item["graph_templates_item_id"];

			/* the following fields will be searched for graph variables */
			$variable_fields = array(
				"text_format" => array(
					"process_no_legend" => false
					),
				"value" => array(
					"process_no_legend" => true
					),
				"cdef_cache" => array(
					"process_no_legend" => true
					),
				"vdef_cache" => array(
					"process_no_legend" => true
					)
				);

			/* loop through each field that we want to substitute values for:
			currently: text format and value */
			while (list($field_name, $field_array) = each($variable_fields)) {
				/* certain fields do not require values when the legend is not to be shown */
				if (($field_array["process_no_legend"] == false) && (isset($graph_data_array["graph_nolegend"]))) {
					continue;
				}

				$graph_variables[$field_name][$graph_item_id] = $graph_item[$field_name];

				/* date/time substitution */
				if (strstr($graph_variables[$field_name][$graph_item_id], "|date_time|")) {
					$graph_variables[$field_name][$graph_item_id] = str_replace("|date_time|", date(date_time_format(), strtotime(db_fetch_cell("select value from settings where name='date'"))), $graph_variables[$field_name][$graph_item_id]);
				}

				/* data source title substitution */
				if (strstr($graph_variables[$field_name][$graph_item_id], "|data_source_title|")) {
					$graph_variables[$field_name][$graph_item_id] = str_replace("|data_source_title|", get_data_source_title($graph_item["local_data_id"]), $graph_variables[$field_name][$graph_item_id]);
				}

				/* data query variables */
				$graph_variables[$field_name][$graph_item_id] = rrd_substitute_device_query_data($graph_variables[$field_name][$graph_item_id], $graph, $graph_item);

				/* Nth percentile */
				if (preg_match_all("/\|([0-9]{1,2}):(bits|bytes):(\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\d)?\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
					foreach ($matches as $match) {
						$graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_nth_percentile($match, $graph_item, $graph_items, $graph_start, $graph_end), $graph_variables[$field_name][$graph_item_id]);
					}
				}

				/* bandwidth summation */
				if (preg_match_all("/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/", $graph_variables[$field_name][$graph_item_id], $matches, PREG_SET_ORDER)) {
					foreach ($matches as $match) {
						$graph_variables[$field_name][$graph_item_id] = str_replace($match[0], variable_bandwidth_summation($match, $graph_item, $graph_items, $graph_start, $graph_end, $rra["steps"], $ds_step), $graph_variables[$field_name][$graph_item_id]);
					}
				}
			}

			/* if we are not displaying a legend there is no point in us even processing the auto padding,
			text format stuff. */
			if (!isset($graph_data_array["graph_nolegend"])) {
				/* set hard return variable if selected (\n) */
				if ($graph_item["hard_return"] == CHECKED) {
					$hardreturn[$graph_item_id] = "\\n";
				}else{
					$hardreturn[$graph_item_id] = "";
				}

				/* +++++++++++++++++++++++ LEGEND: AUTO PADDING (<>'s) +++++++++++++++++++++++ */

				/* PADDING: remember this is not perfect! its main use is for the basic graph setup of:
				AREA - GPRINT-CURRENT - GPRINT-AVERAGE - GPRINT-MAXIMUM \n
				of course it can be used in other situations, however may not work as intended.
				If you have any additions to this small peice of code, feel free to send them to me. */
				if ($graph["auto_padding"] == CHECKED) {
					/* only applies to AREA, STACK and LINEs */
					if ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREA ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREASTACK ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3 ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINESTACK ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_TICK) {
						$text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);

						if ($text_format_length > $greatest_text_format) {
							$greatest_text_format = $text_format_length;
						}
					}
				}
			}

			$j++;
		}
	}

	/* +++++++++++++++++++++++ GRAPH ITEMS: CDEF's +++++++++++++++++++++++ */

	$i = 0;
	reset($graph_items);

	if (sizeof($graph_items) > 0) {
	foreach ($graph_items as $graph_item) {
		/* first we need to check if there is a DEF for the current data source/cf combination. if so,
		we will use that */
		if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}{$graph_item["consolidation_function_id"]})) {
			$cf_id = $graph_item["consolidation_function_id"];
		}else{
		/* if there is not a DEF defined for the current data source/cf combination, then we will have to
		improvise. choose the first available cf in the following order: AVERAGE, MAX, MIN, LAST */
			if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[RRA_CF_TYPE_AVERAGE])) {
				$cf_id = RRA_CF_TYPE_AVERAGE; /* CF: AVERAGE */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[RRA_CF_TYPE_MAX])) {
				$cf_id = RRA_CF_TYPE_MAX; /* CF: MAX */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[RRA_CF_TYPE_MIN])) {
				$cf_id = RRA_CF_TYPE_MIN; /* CF: MIN */
			}elseif (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[RRA_CF_TYPE_LAST])) {
				$cf_id = RRA_CF_TYPE_LAST; /* CF: LAST */
			}else{
				$cf_id = RRA_CF_TYPE_AVERAGE; /* CF: AVERAGE */
			}
		}
		/* now remember the correct CF reference */
		$cf_id = $graph_item["cf_reference"];

		/* make cdef string here; a note about CDEF's in cacti. A CDEF is neither unique to a
		data source of global cdef, but is unique when those two variables combine. */
		$cdef_graph_defs = "";

		if ((!empty($graph_item["cdef_id"])) && (!isset($cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]))) {

			$cdef_string 	= $graph_variables["cdef_cache"]{$graph_item["graph_templates_item_id"]};
			$magic_item 	= array();
			$already_seen	= array();
			$sources_seen	= array();
			$count_all_ds_dups = 0;
			$count_all_ds_nodups = 0;
			$count_similar_ds_dups = 0;
			$count_similar_ds_nodups = 0;

			/* if any of those magic variables are requested ... */
			if (preg_match("/(ALL_DATA_SOURCES_(NO)?DUPS|SIMILAR_DATA_SOURCES_(NO)?DUPS)/", $cdef_string) ||
				preg_match("/(COUNT_ALL_DS_(NO)?DUPS|COUNT_SIMILAR_DS_(NO)?DUPS)/", $cdef_string)) {

				/* now walk through each case to initialize array*/
				if (preg_match("/ALL_DATA_SOURCES_DUPS/", $cdef_string)) {
					$magic_item["ALL_DATA_SOURCES_DUPS"] = "";
				}
				if (preg_match("/ALL_DATA_SOURCES_NODUPS/", $cdef_string)) {
					$magic_item["ALL_DATA_SOURCES_NODUPS"] = "";
				}
				if (preg_match("/SIMILAR_DATA_SOURCES_DUPS/", $cdef_string)) {
					$magic_item["SIMILAR_DATA_SOURCES_DUPS"] = "";
				}
				if (preg_match("/SIMILAR_DATA_SOURCES_NODUPS/", $cdef_string)) {
					$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] = "";
				}
				if (preg_match("/COUNT_ALL_DS_DUPS/", $cdef_string)) {
					$magic_item["COUNT_ALL_DS_DUPS"] = "";
				}
				if (preg_match("/COUNT_ALL_DS_NODUPS/", $cdef_string)) {
					$magic_item["COUNT_ALL_DS_NODUPS"] = "";
				}
				if (preg_match("/COUNT_SIMILAR_DS_DUPS/", $cdef_string)) {
					$magic_item["COUNT_SIMILAR_DS_DUPS"] = "";
				}
				if (preg_match("/COUNT_SIMILAR_DS_NODUPS/", $cdef_string)) {
					$magic_item["COUNT_SIMILAR_DS_NODUPS"] = "";
				}

				/* loop over all graph items */
				for ($t=0;($t<count($graph_items));$t++) {

					/* only work on graph items, omit GRPINTs, COMMENTs and stuff */
					if (($graph_items[$t]["graph_type_id"] == GRAPH_ITEM_TYPE_AREA ||
						$graph_items[$t]["graph_type_id"] == GRAPH_ITEM_TYPE_AREASTACK ||
						$graph_items[$t]["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 ||
						$graph_items[$t]["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 ||
						$graph_items[$t]["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3 ||
						$graph_items[$t]["graph_type_id"] == GRAPH_ITEM_TYPE_LINESTACK) &&
						(!empty($graph_items[$t]["data_template_rrd_id"]))) {
						/* if the user screws up CF settings, PHP will generate warnings if left unchecked */

						/* matching consolidation function? */
						if (isset($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id])) {
							$def_name = generate_graph_def_name(strval($cf_ds_cache{$graph_items[$t]["data_template_rrd_id"]}[$cf_id]));

							/* do we need ALL_DATA_SOURCES_DUPS? */
							if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
								$magic_item["ALL_DATA_SOURCES_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
							}

							/* do we need COUNT_ALL_DS_DUPS? */
							if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
								$magic_item["COUNT_ALL_DS_DUPS"] .= ($count_all_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
							}

							$count_all_ds_dups++;

							/* check if this item also qualifies for NODUPS  */
							if(!isset($already_seen[$def_name])) {
								if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
									$magic_item["ALL_DATA_SOURCES_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
								}
								if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
									$magic_item["COUNT_ALL_DS_NODUPS"] .= ($count_all_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
								}
								$count_all_ds_nodups++;
								$already_seen[$def_name]=TRUE;
							}

							/* check for SIMILAR data sources */
							if ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"]) {

								/* do we need SIMILAR_DATA_SOURCES_DUPS? */
								if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"]) && ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"])) {
									$magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
								}

								/* do we need COUNT_SIMILAR_DS_DUPS? */
								if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"]) && ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"])) {
									$magic_item["COUNT_SIMILAR_DS_DUPS"] .= ($count_similar_ds_dups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
								}

								$count_similar_ds_dups++;

								/* check if this item also qualifies for NODUPS  */
								if(!isset($sources_seen{$graph_items[$t]["data_template_rrd_id"]})) {
									if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
										$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,$def_name,$def_name,UN,0,$def_name,IF,IF"; /* convert unknowns to '0' first */
									}
									if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"]) && ($graph_item["data_source_name"] == $graph_items[$t]["data_source_name"])) {
										$magic_item["COUNT_SIMILAR_DS_NODUPS"] .= ($count_similar_ds_nodups == 0 ? "" : ",") . "TIME," . (time() - $seconds_between_graph_updates) . ",GT,1,$def_name,UN,0,1,IF,IF"; /* convert unknowns to '0' first */
									}
									$count_similar_ds_nodups++;
									$sources_seen{$graph_items[$t]["data_template_rrd_id"]} = TRUE;
								}
							} # SIMILAR data sources
						} # matching consolidation function?
					} # only work on graph items, omit GRPINTs, COMMENTs and stuff
				} #  loop over all graph items

				/* if there is only one item to total, don't even bother with the summation.
				 * Otherwise cdef=a,b,c,+,+ is fine. */
				if ($count_all_ds_dups > 1 && isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
					$magic_item["ALL_DATA_SOURCES_DUPS"] .= str_repeat(",+", ($count_all_ds_dups - 2)) . ",+";
				}
				if ($count_all_ds_nodups > 1 && isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
					$magic_item["ALL_DATA_SOURCES_NODUPS"] .= str_repeat(",+", ($count_all_ds_nodups - 2)) . ",+";
				}
				if ($count_similar_ds_dups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
					$magic_item["SIMILAR_DATA_SOURCES_DUPS"] .= str_repeat(",+", ($count_similar_ds_dups - 2)) . ",+";
				}
				if ($count_similar_ds_nodups > 1 && isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
					$magic_item["SIMILAR_DATA_SOURCES_NODUPS"] .= str_repeat(",+", ($count_similar_ds_nodups - 2)) . ",+";
				}
				if ($count_all_ds_dups > 1 && isset($magic_item["COUNT_ALL_DS_DUPS"])) {
					$magic_item["COUNT_ALL_DS_DUPS"] .= str_repeat(",+", ($count_all_ds_dups - 2)) . ",+";
				}
				if ($count_all_ds_nodups > 1 && isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
					$magic_item["COUNT_ALL_DS_NODUPS"] .= str_repeat(",+", ($count_all_ds_nodups - 2)) . ",+";
				}
				if ($count_similar_ds_dups > 1 && isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
					$magic_item["COUNT_SIMILAR_DS_DUPS"] .= str_repeat(",+", ($count_similar_ds_dups - 2)) . ",+";
				}
				if ($count_similar_ds_nodups > 1 && isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
					$magic_item["COUNT_SIMILAR_DS_NODUPS"] .= str_repeat(",+", ($count_similar_ds_nodups - 2)) . ",+";
				}
			}

			$cdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval((isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id]) ? $cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id] : "0"))), $cdef_string);

			/* ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
			if (isset($magic_item["ALL_DATA_SOURCES_DUPS"])) {
				$cdef_string = str_replace("ALL_DATA_SOURCES_DUPS", $magic_item["ALL_DATA_SOURCES_DUPS"], $cdef_string);
			}
			if (isset($magic_item["ALL_DATA_SOURCES_NODUPS"])) {
				$cdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $magic_item["ALL_DATA_SOURCES_NODUPS"], $cdef_string);
			}
			if (isset($magic_item["SIMILAR_DATA_SOURCES_DUPS"])) {
				$cdef_string = str_replace("SIMILAR_DATA_SOURCES_DUPS", $magic_item["SIMILAR_DATA_SOURCES_DUPS"], $cdef_string);
			}
			if (isset($magic_item["SIMILAR_DATA_SOURCES_NODUPS"])) {
				$cdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $magic_item["SIMILAR_DATA_SOURCES_NODUPS"], $cdef_string);
			}

			/* COUNT_ALL|SIMILAR_DATA_SOURCES(NO)?DUPS are to be replaced here */
			if (isset($magic_item["COUNT_ALL_DS_DUPS"])) {
				$cdef_string = str_replace("COUNT_ALL_DS_DUPS", $magic_item["COUNT_ALL_DS_DUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_ALL_DS_NODUPS"])) {
				$cdef_string = str_replace("COUNT_ALL_DS_NODUPS", $magic_item["COUNT_ALL_DS_NODUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_SIMILAR_DS_DUPS"])) {
				$cdef_string = str_replace("COUNT_SIMILAR_DS_DUPS", $magic_item["COUNT_SIMILAR_DS_DUPS"], $cdef_string);
			}
			if (isset($magic_item["COUNT_SIMILAR_DS_NODUPS"])) {
				$cdef_string = str_replace("COUNT_SIMILAR_DS_NODUPS", $magic_item["COUNT_SIMILAR_DS_NODUPS"], $cdef_string);
			}

			/* data source item variables */
			$cdef_string = str_replace("CURRENT_DS_MINIMUM_VALUE", (empty($graph_item["rrd_minimum"]) ? "0" : $graph_item["rrd_minimum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_DS_MAXIMUM_VALUE", (empty($graph_item["rrd_maximum"]) ? "0" : $graph_item["rrd_maximum"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MINIMUM_VALUE", (empty($graph["lower_limit"]) ? "0" : $graph["lower_limit"]), $cdef_string);
			$cdef_string = str_replace("CURRENT_GRAPH_MAXIMUM_VALUE", (empty($graph["upper_limit"]) ? "0" : $graph["upper_limit"]), $cdef_string);
			$_time_shift_start = strtotime(read_graph_config_option("day_shift_start")) - strtotime("00:00");
			$_time_shift_end = strtotime(read_graph_config_option("day_shift_end")) - strtotime("00:00");
			$cdef_string = str_replace("TIME_SHIFT_START", (empty($_time_shift_start) ? "64800" : $_time_shift_start), $cdef_string);
			$cdef_string = str_replace("TIME_SHIFT_END", (empty($_time_shift_end) ? "28800" : $_time_shift_end), $cdef_string);

			/* replace query variables in cdefs */
			$cdef_string = rrd_substitute_device_query_data($cdef_string, $graph, $graph_item);

			/* make the initial "virtual" cdef name: 'cdef' + [a,b,c,d...] */
			$cdef_graph_defs .= "CDEF:cdef" . generate_graph_def_name(strval($i)) . "=";
			$cdef_graph_defs .= $cdef_string;
			$cdef_graph_defs .= " \\\n";

			/* the CDEF cache is so we do not create duplicate CDEF's on a graph */
			$cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id] = "$i";
		}

		/* add the cdef string to the end of the def string */
		$graph_defs .= $cdef_graph_defs;

		/* +++++++++++++++++++++++ GRAPH ITEMS: VDEF's +++++++++++++++++++++++ */
		if ($rrdtool_version != RRD_VERSION_1_0) {

			/* make vdef string here, copied from cdef stuff */
			$vdef_graph_defs = "";

			if ((!empty($graph_item["vdef_id"])) && (!isset($vdef_cache{$graph_item["vdef_id"]}{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]))) {
				$vdef_string = $graph_variables["vdef_cache"]{$graph_item["graph_templates_item_id"]};
				if ($graph_item["cdef_id"] != "0") {
					/* "calculated" VDEF: use (cached) CDEF as base, only way to get calculations into VDEFs, lvm */
					$vdef_string = "cdef" . str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval(isset($cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]) ? $cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id] : "0")), $vdef_string);
			 	} else {
					/* "pure" VDEF: use DEF as base */
					$vdef_string = str_replace("CURRENT_DATA_SOURCE", generate_graph_def_name(strval(isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id]) ? $cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id] : "0")), $vdef_string);
				}
# TODO: It would be possible to refer to a CDEF, but that's all. So ALL_DATA_SOURCES_NODUPS and stuff can't be used directly!
#				$vdef_string = str_replace("ALL_DATA_SOURCES_NODUPS", $magic_item["ALL_DATA_SOURCES_NODUPS"], $vdef_string);
#				$vdef_string = str_replace("ALL_DATA_SOURCES_DUPS", $magic_item["ALL_DATA_SOURCES_DUPS"], $vdef_string);
#				$vdef_string = str_replace("SIMILAR_DATA_SOURCES_NODUPS", $magic_item["SIMILAR_DATA_SOURCES_NODUPS"], $vdef_string);
#				$vdef_string = str_replace("SIMILAR_DATA_SOURCES_DUPS", $magic_item["SIMILAR_DATA_SOURCES_DUPS"], $vdef_string);

				/* make the initial "virtual" vdef name */
				$vdef_graph_defs .= "VDEF:vdef" . generate_graph_def_name(strval($i)) . "=";
				$vdef_graph_defs .= $vdef_string;
				$vdef_graph_defs .= " \\\n";

				/* the VDEF cache is so we do not create duplicate VDEF's on a graph,
				 * but take info account, that same VDEF may use different CDEFs
				 * so index over VDEF_ID, CDEF_ID per DATA_TEMPLATE_RRD_ID, lvm */
				$vdef_cache{$graph_item["vdef_id"]}{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id] = "$i";
			}

			/* add the cdef string to the end of the def string */
			$graph_defs .= $vdef_graph_defs;
		}

		/* note the current item_id for easy access */
		$graph_item_id = $graph_item["graph_templates_item_id"];

		/* if we are not displaying a legend there is no point in us even processing the auto padding,
		text format stuff. */
		if ((!isset($graph_data_array["graph_nolegend"])) && ($graph["auto_padding"] == CHECKED)) {
			/* only applies to AREA, STACK and LINEs */
			if ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREA ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_AREASTACK ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3 ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINESTACK ||
				$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_TICK) {
				$text_format_length = strlen($graph_variables["text_format"][$graph_item_id]);

				/* we are basing how much to pad on area and stack text format,
				not gprint. but of course the padding has to be displayed in gprint,
				how fun! */

				$pad_number = ($greatest_text_format - $text_format_length);
				//cacti_log("MAX: $greatest_text_format, CURR: $text_format_lengths[$item_dsid], DSID: $item_dsid");
				$text_padding = str_pad("", $pad_number);

			/* two GPRINT's in a row screws up the padding, lets not do that */
			} else if (($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_AVERAGE ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_LAST ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_MAX ||
						$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_GPRINT_MIN) && (
						$last_graph_type == GRAPH_ITEM_TYPE_GPRINT_AVERAGE ||
						$last_graph_type == GRAPH_ITEM_TYPE_GPRINT_LAST ||
						$last_graph_type == GRAPH_ITEM_TYPE_GPRINT_MAX ||
						$last_graph_type == GRAPH_ITEM_TYPE_GPRINT_MIN)) {
				$text_padding = "";
			}

			$last_graph_type = $graph_item["graph_type_id"];
		}

		/* we put this in a variable so it can be manipulated before mainly used
		if we want to skip it, like below */
		$current_graph_item_type = $graph_item["graph_type_id"];

		/* IF this graph item has a data source... get a DEF name for it, or the cdef if that applies
		to this graph item */
		if ($graph_item["cdef_id"] == "0") {
			if (isset($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id])) {
				$data_source_name = generate_graph_def_name(strval($cf_ds_cache{$graph_item["data_template_rrd_id"]}[$cf_id]));
			}else{
				$data_source_name = "";
			}
		}else{
			$data_source_name = "cdef" . generate_graph_def_name(strval($cdef_cache{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]));
		}

		/* IF this graph item has a data source... get a DEF name for it, or the vdef if that applies
		to this graph item */
		if ($graph_item["vdef_id"] == "0") {
			/* do not overwrite $data_source_name that stems from cdef above */
		}else{
			$data_source_name = "vdef" . generate_graph_def_name(strval($vdef_cache{$graph_item["vdef_id"]}{$graph_item["cdef_id"]}{$graph_item["data_template_rrd_id"]}[$cf_id]));
		}

		/* to make things easier... if there is no text format set; set blank text */
		if (!isset($graph_variables["text_format"][$graph_item_id])) {
			$graph_variables["text_format"][$graph_item_id] = "";
		} else {
			$graph_variables["text_format"][$graph_item_id] = str_replace(':', '\:', $graph_variables["text_format"][$graph_item_id]); /* escape colons */
			$graph_variables["text_format"][$graph_item_id] = str_replace('"', '\"', $graph_variables["text_format"][$graph_item_id]); /* escape doublequotes */
		}

		if (!isset($hardreturn[$graph_item_id])) {
			$hardreturn[$graph_item_id] = "";
		}

		/* +++++++++++++++++++++++ GRAPH ITEMS +++++++++++++++++++++++ */

		/* most of the calculations have been done above. now we have for print everything out
		in an RRDTool-friendly fashion */
		$need_rrd_nl = TRUE;

		/* initialize line width support */
		if ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 ||
			$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 ||
			$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3) {
			if ($rrdtool_version == RRD_VERSION_1_0) {
				# round line_width to 1 <= line_width <= 3
				if ($graph_item["line_width"] < 1) {$graph_item["line_width"] = 1;}
				if ($graph_item["line_width"] > 3) {$graph_item["line_width"] = 3;}

				$graph_item["line_width"] = intval($graph_item["line_width"]);
			}
		}

		/* initialize color support */
		$graph_item_color_code = "";
		if (!empty($graph_item["hex"])) {
			$graph_item_color_code = "#" . $graph_item["hex"];
			if ($rrdtool_version != RRD_VERSION_1_0) {
				$graph_item_color_code .= $graph_item["alpha"];
			}
		}


		/* initialize dash support */
		$dash = "";
		if ($graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE1 ||
			$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE2 ||
			$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINE3 ||
			$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_LINESTACK ||
			$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_HRULE ||
			$graph_item["graph_type_id"] == GRAPH_ITEM_TYPE_VRULE) {
			if ($rrdtool_version != RRD_VERSION_1_0 &&
				$rrdtool_version != RRD_VERSION_1_2) {
				if (!empty($graph_item["dashes"])) {
					$dash .= ":dashes=" . $graph_item["dashes"];
				}
				if (!empty($graph_item["dash_offset"])) {
					$dash .= ":dash-offset=" . $graph_item["dash_offset"];
				}
			}
		}


		switch($graph_item["graph_type_id"]) {
			case GRAPH_ITEM_TYPE_COMMENT:
				$comment_string = $graph_item_types{$graph_item["graph_type_id"]} . ":\"" .
						substr(rrd_substitute_device_query_data(str_replace(":", "\:", $graph_variables["text_format"][$graph_item_id]), $graph, $graph_item),0,198) .
						$hardreturn[$graph_item_id] . "\" ";
				if (trim($comment_string) == 'COMMENT:"\n"') {
					$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ':" \n"'; # rrdtool will skip a COMMENT that holds a NL only; so add a blank to make NL work
				}elseif (trim($comment_string) != "COMMENT:\"\"") {
					$txt_graph_items .= $comment_string;
				}
				break;


			case GRAPH_ITEM_TYPE_TEXTALIGN:
				if (!empty($graph_item["textalign"]) &&
					$rrdtool_version != RRD_VERSION_1_0 &&
					$rrdtool_version != RRD_VERSION_1_2) {
						$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $graph_item["textalign"];
					}
				break;


			case GRAPH_ITEM_TYPE_GPRINT_AVERAGE:
				if (!isset($graph_data_array["graph_nolegend"])) {
					/* rrdtool 1.2.x VDEFs must suppress the consolidation function on GPRINTs */
					if ($rrdtool_version != RRD_VERSION_1_0) {
						if ($graph_item["vdef_id"] == "0") {
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":AVERAGE:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}else{
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}
					}else {
						$txt_graph_items .= "GPRINT:" . $data_source_name . ":AVERAGE:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
					}
				}
				break;


			case GRAPH_ITEM_TYPE_GPRINT_LAST:
				if (!isset($graph_data_array["graph_nolegend"])) {
					/* rrdtool 1.2.x VDEFs must suppress the consolidation function on GPRINTs */
					if ($rrdtool_version != RRD_VERSION_1_0) {
						if ($graph_item["vdef_id"] == "0") {
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":LAST:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}else{
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}
					}else {
						$txt_graph_items .= "GPRINT:" . $data_source_name . ":LAST:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
					}
				}
				break;


			case GRAPH_ITEM_TYPE_GPRINT_MAX:
				if (!isset($graph_data_array["graph_nolegend"])) {
					/* rrdtool 1.2.x VDEFs must suppress the consolidation function on GPRINTs */
					if ($rrdtool_version != RRD_VERSION_1_0) {
						if ($graph_item["vdef_id"] == "0") {
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":MAX:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}else{
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}
					}else {
						$txt_graph_items .= "GPRINT:" . $data_source_name . ":MAX:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
					}
				}
				break;


			case GRAPH_ITEM_TYPE_GPRINT_MIN:
				if (!isset($graph_data_array["graph_nolegend"])) {
					/* rrdtool 1.2.x VDEFs must suppress the consolidation function on GPRINTs */
					if ($rrdtool_version != RRD_VERSION_1_0) {
						if ($graph_item["vdef_id"] == "0") {
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":MIN:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}else{
							$txt_graph_items .= "GPRINT:" . $data_source_name . ":\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
						}
					}else {
						$txt_graph_items .= "GPRINT:" . $data_source_name . ":MIN:\"$text_padding" . $graph_variables["text_format"][$graph_item_id] . $graph_item["gprint_text"] . $hardreturn[$graph_item_id] . "\" ";
					}
				}
				break;


			case GRAPH_ITEM_TYPE_AREA:
				$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
				if ($graph_item["shift"] == CHECKED && $graph_item["value"] > 0) {	# create a SHIFT statement
					$txt_graph_items .= RRD_NL . "SHIFT:" . $data_source_name . ":" . $graph_item["value"];
				}
				break;


			case GRAPH_ITEM_TYPE_AREASTACK:
				if ($rrdtool_version != RRD_VERSION_1_0) {
					$txt_graph_items .= "AREA:" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\":STACK";
				}else {
					$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\" ";
				}
				if ($graph_item["shift"] == CHECKED && $graph_item["value"] > 0) {	# create a SHIFT statement
					$txt_graph_items .= RRD_NL . "SHIFT:" . $data_source_name . ":" . $graph_item["value"];
				}
				break;


			case GRAPH_ITEM_TYPE_LINE1:
			case GRAPH_ITEM_TYPE_LINE2:
			case GRAPH_ITEM_TYPE_LINE3:
				$txt_graph_items .= "LINE" . $graph_item["line_width"] . ":" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\"" . $dash;
				if ($graph_item["shift"] == CHECKED && $graph_item["value"] > 0) {	# create a SHIFT statement
					$txt_graph_items .= RRD_NL . "SHIFT:" . $data_source_name . ":" . $graph_item["value"];
				}
				break;


			case GRAPH_ITEM_TYPE_LINESTACK:
				if ($rrdtool_version != RRD_VERSION_1_0) {
					$txt_graph_items .= "LINE" . $graph_item["line_width"] . ":" . $data_source_name . $graph_item_color_code . ":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\":STACK" . $dash;
				}
				if ($graph_item["shift"] == CHECKED && $graph_item["value"] > 0) {	# create a SHIFT statement
					$txt_graph_items .= RRD_NL . "SHIFT:" . $data_source_name . ":" . $graph_item["value"];
				}
				break;


			case GRAPH_ITEM_TYPE_TICK:
				if ($rrdtool_version != RRD_VERSION_1_0) {
					$_fraction 	= (empty($graph_item["graph_type_id"]) 						? "" : (":" . $graph_item["value"]));
					$_legend 	= (empty($graph_variables["text_format"][$graph_item_id]) 	? "" : (":" . "\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\""));
					$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $data_source_name . $graph_item_color_code . $_fraction . $_legend;
				}
				break;


			case GRAPH_ITEM_TYPE_HRULE:
				$graph_variables["value"][$graph_item_id] = str_replace(":", "\:", $graph_variables["value"][$graph_item_id]); /* escape colons */
				/* perform variable substitution; if this does not return a number, rrdtool will FAIL! */
				$substitute = rrd_substitute_device_query_data($graph_variables["value"][$graph_item_id], $graph, $graph_item);
				if (is_numeric($substitute)) {
					$graph_variables["value"][$graph_item_id] = $substitute;
				}
				$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $graph_variables["value"][$graph_item_id] . $graph_item_color_code . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\"" . $dash;
				break;


			case GRAPH_ITEM_TYPE_VRULE:
				if (substr_count($graph_item["value"], ":")) {
					$value_array = explode(":", $graph_item["value"]);

					if ($value_array[0] < 0) {
						$value = date("U") - (-3600 * $value_array[0]) - 60 * $value_array[1];
					}else{
						$value = date("U", mktime($value_array[0],$value_array[1],0));
					}
				}else if (is_numeric($graph_item["value"])) {
					$value = $graph_item["value"];
				}

				$txt_graph_items .= $graph_item_types{$graph_item["graph_type_id"]} . ":" . $value . $graph_item_color_code . ":\"" . $graph_variables["text_format"][$graph_item_id] . $hardreturn[$graph_item_id] . "\"" . $dash;
				break;


			default:
				$need_rrd_nl = FALSE;

		}

		$i++;

		if (($i < sizeof($graph_items)) && ($need_rrd_nl)) {
			$txt_graph_items .= RRD_NL;
		}
	}
	}

	$graph_array = api_plugin_hook_function('rrd_graph_graph_options', array('graph_opts' => $graph_opts, 'graph_defs' => $graph_defs, 'txt_graph_items' => $txt_graph_items, 'graph_id' => $local_graph_id, 'start' => $graph_start, 'end' => $graph_end));
	if (!empty($graph_array)) {
		$graph_defs = $graph_array['graph_defs'];
		$txt_graph_items = $graph_array['txt_graph_items'];
		$graph_opts = $graph_array['graph_opts'];
	}

	/* either print out the source or pass the source onto rrdtool to get us a nice graph */
	if (isset($graph_data_array["print_source"])) {
		# since pango markup allows for <span> tags, we need to escape this stuff using htmlspecialchars
		print htmlspecialchars(read_config_option("path_rrdtool") . " graph $graph_opts$graph_defs$txt_graph_items");
	}else{
		if (isset($graph_data_array["export"])) {
			rrdtool_execute("graph $graph_opts$graph_defs$txt_graph_items", false, RRDTOOL_OUTPUT_NULL, $rrd_struc);
			return 0;
		}else{
			$graph_data_array = api_plugin_hook_function('prep_graph_array', $graph_data_array);

			if (isset($graph_data_array["output_flag"])) {
				$output_flag = $graph_data_array["output_flag"];
			}else{
				$output_flag = RRDTOOL_OUTPUT_GRAPH_DATA;
			}
			$output = rrdtool_execute("graph $graph_opts$graph_defs$txt_graph_items", false, $output_flag, $rrd_struc);

			api_plugin_hook_function('rrdtool_function_graph_set_file', array('output' => $output, 'local_graph_id' => $local_graph_id, 'rra_id' => $rra_id));

			return $output;
		}
	}
}
Beispiel #12
0
function thold_data_source_action_prepare($save)
{
    global $config;
    if ($save['drp_action'] == 'plugin_thold_create') {
        /* get the valid thold templates
         * remove those hosts that do not have any valid templates
         */
        $templates = '';
        $found_list = '';
        $not_found = '';
        if (sizeof($save['ds_array'])) {
            foreach ($save['ds_array'] as $item) {
                $data_template_id = db_fetch_cell("SELECT data_template_id FROM data_local WHERE id={$item}");
                if ($data_template_id != '') {
                    if (sizeof(db_fetch_assoc("SELECT id FROM thold_template WHERE data_template_id={$data_template_id}"))) {
                        $found_list .= '<li>' . get_data_source_title($item) . '</li>';
                        if (strlen($templates)) {
                            $templates .= ", {$data_template_id}";
                        } else {
                            $templates = "{$data_template_id}";
                        }
                    } else {
                        $not_found .= '<li>' . get_data_source_title($item) . '</li>';
                    }
                } else {
                    $not_found .= '<li>' . get_data_source_title($item) . '</li>';
                }
            }
        }
        if (strlen($templates)) {
            $sql = 'SELECT id, name FROM thold_template WHERE data_template_id IN (' . $templates . ') ORDER BY name';
        } else {
            $sql = 'SELECT id, name FROM thold_template ORDER BY name';
        }
        print "<tr><td colspan='2' class='textArea'>\n";
        if (strlen($found_list)) {
            if (strlen($not_found)) {
                print '<p>' . __('The following Data Sources have no Threshold Templates associated with them') . '</p>';
                print '<ul>' . $not_found . '</ul>';
            }
            print '<p>' . __('Are you sure you wish to create Thresholds for these Data Sources?') . '</p>
					<ul>' . $found_list . "</ul>\n\t\t\t\t</td>\n\t\t\t</tr></table><table class='cactiTable'>\n";
            $form_array = array('general_header' => array('friendly_name' => __('Available Threshold Templates'), 'method' => 'spacer'), 'thold_template_id' => array('method' => 'drop_sql', 'friendly_name' => __('Select a Threshold Template'), 'description' => '', 'none_value' => __('None'), 'value' => __('None'), 'sql' => $sql));
            draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array));
            print "</tr></table>\n";
        } else {
            if (strlen($not_found)) {
                print '<p>' . __('There are no Threshold Templates associated with the following Data Sources') . '</p>';
                print '<ul>' . $not_found . '</ul>';
            }
        }
    } else {
        return $save;
    }
}