Ejemplo n.º 1
0
function run_data_query($host_id, $snmp_query_id)
{
    global $config, $input_types;
    include_once $config["library_path"] . "/poller.php";
    include_once $config["library_path"] . "/utility.php";
    debug_log_insert("data_query", "Running data query [{$snmp_query_id}].");
    $type_id = db_fetch_cell("select data_input.type_id from (snmp_query,data_input) where snmp_query.data_input_id=data_input.id and snmp_query.id={$snmp_query_id}");
    if (isset($input_types[$type_id])) {
        debug_log_insert("data_query", "Found type = '" . $type_id . "' [" . $input_types[$type_id] . "].");
    }
    if ($type_id == DATA_INPUT_TYPE_SNMP_QUERY) {
        $result = query_snmp_host($host_id, $snmp_query_id);
    } elseif ($type_id == DATA_INPUT_TYPE_SCRIPT_QUERY) {
        $result = query_script_host($host_id, $snmp_query_id);
    } elseif ($type_id == DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER) {
        $result = query_script_host($host_id, $snmp_query_id);
    } else {
        debug_log_insert("data_query", "Unknown type = '{$type_id}'");
    }
    /* update the sort cache */
    update_data_query_sort_cache($host_id, $snmp_query_id);
    /* update the auto reindex cache */
    update_reindex_cache($host_id, $snmp_query_id);
    /* update the the "local" data query cache */
    update_data_query_cache($host_id, $snmp_query_id);
    /* update the poller cache */
    update_poller_cache_from_query($host_id, $snmp_query_id);
    api_plugin_hook_function('run_data_query', array("host_id" => $host_id, "snmp_query_id" => $snmp_query_id));
    return isset($result) ? $result : true;
}
Ejemplo n.º 2
0
function ss_host_cpu($hostname, $host_id, $snmp_auth, $cmd, $arg1 = "", $arg2 = "")
{
    $snmp = explode(":", $snmp_auth);
    $snmp_version = $snmp[0];
    $snmp_port = $snmp[1];
    $snmp_timeout = $snmp[2];
    $snmp_auth_username = "";
    $snmp_auth_password = "";
    $snmp_auth_protocol = "";
    $snmp_priv_passphrase = "";
    $snmp_priv_protocol = "";
    $snmp_community = "";
    $snmp_context = "";
    if ($snmp_version == 3) {
        $snmp_auth_username = $snmp[4];
        $snmp_auth_password = $snmp[5];
        $snmp_auth_protocol = $snmp[6];
        $snmp_priv_passphrase = $snmp[7];
        $snmp_priv_protocol = $snmp[8];
        $snmp_context = $snmp[9];
    } else {
        $snmp_community = $snmp[3];
    }
    $oids = array("index" => ".1.3.6.1.2.1.25.3.3.1", "usage" => ".1.3.6.1.2.1.25.3.3.1");
    if ($cmd == "index") {
        $arr_index = ss_host_cpu_get_indexes($hostname, $snmp_community, $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout);
        for ($i = 0; $i < sizeof($arr_index); $i++) {
            print $arr_index[$i] . "\n";
        }
    } elseif ($cmd == "query") {
        $arg = $arg1;
        $arr_index = ss_host_cpu_get_indexes($hostname, $snmp_community, $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout);
        $arr = ss_host_cpu_get_cpu_usage($hostname, $snmp_community, $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout);
        for ($i = 0; $i < sizeof($arr_index); $i++) {
            if ($arg == "usage") {
                print $arr_index[$i] . "!" . $arr[$i] . "\n";
            } elseif ($arg == "index") {
                print $arr_index[$i] . "!" . $arr_index[$i] . "\n";
            }
        }
    } elseif ($cmd == "get") {
        $arg = $arg1;
        $index = rtrim($arg2);
        $value = api_plugin_hook_function('hmib_get_cpu', array("host_id" => $host_id, "arg" => $arg, "index" => $index));
        if (is_array($value)) {
            $arr_index = ss_host_cpu_get_indexes($hostname, $snmp_community, $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout);
            $arr = ss_host_cpu_get_cpu_usage($hostname, $snmp_community, $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout);
            if (isset($arr_index[$index])) {
                return $arr[$index];
            } else {
                return "ERROR: Invalid Return Value";
            }
        } else {
            return $value;
        }
    }
}
Ejemplo n.º 3
0
function ss_host_disk($hostname, $host_id, $snmp_auth, $cmd, $arg1 = "", $arg2 = "")
{
    $snmp = explode(":", $snmp_auth);
    $snmp_version = $snmp[0];
    $snmp_port = $snmp[1];
    $snmp_timeout = $snmp[2];
    $snmp_auth_username = "";
    $snmp_auth_password = "";
    $snmp_auth_protocol = "";
    $snmp_priv_passphrase = "";
    $snmp_priv_protocol = "";
    $snmp_context = "";
    $snmp_community = "";
    if ($snmp_version == 3) {
        $snmp_auth_username = $snmp[4];
        $snmp_auth_password = $snmp[5];
        $snmp_auth_protocol = $snmp[6];
        $snmp_priv_passphrase = $snmp[7];
        $snmp_priv_protocol = $snmp[8];
        $snmp_context = $snmp[9];
    } else {
        $snmp_community = $snmp[3];
    }
    $oids = array("total" => ".1.3.6.1.2.1.25.2.3.1.5", "totalin" => ".1.3.6.1.2.1.25.2.3.1.5", "used" => ".1.3.6.1.2.1.25.2.3.1.6", "failures" => ".1.3.6.1.2.1.25.2.3.1.7", "index" => ".1.3.6.1.2.1.25.2.3.1.1", "description" => ".1.3.6.1.2.1.25.2.3.1.3", "sau" => ".1.3.6.1.2.1.25.2.3.1.4");
    if ($cmd == "index") {
        $return_arr = ss_host_disk_reindex(cacti_snmp_walk($hostname, $snmp_community, $oids["index"], $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout, read_config_option("snmp_retries"), SNMP_POLLER));
        for ($i = 0; $i < sizeof($return_arr); $i++) {
            print $return_arr[$i] . "\n";
        }
    } elseif ($cmd == "query") {
        $arg = $arg1;
        $arr_index = ss_host_disk_reindex(cacti_snmp_walk($hostname, $snmp_community, $oids["index"], $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout, read_config_option("snmp_retries"), SNMP_POLLER));
        $arr = ss_host_disk_reindex(cacti_snmp_walk($hostname, $snmp_community, $oids[$arg], $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout, read_config_option("snmp_retries"), SNMP_POLLER));
        for ($i = 0; $i < sizeof($arr_index); $i++) {
            print $arr_index[$i] . "!" . $arr[$i] . "\n";
        }
    } elseif ($cmd == "get") {
        $arg = $arg1;
        $index = $arg2;
        $value = api_plugin_hook_function('hmib_get_disk', array("host_id" => $host_id, "arg" => $arg, "index" => $index));
        if (is_array($value)) {
            if ($arg == "total" || $arg == "used") {
                $sau = eregi_replace("[^0-9]", "", db_fetch_cell("select field_value from host_snmp_cache where host_id={$host_id} and field_name='hrStorageAllocationUnits' and snmp_index='{$index}'"));
                return cacti_snmp_get($hostname, $snmp_community, $oids[$arg] . ".{$index}", $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout, read_config_option("snmp_retries"), SNMP_POLLER) * $sau;
            } else {
                return cacti_snmp_get($hostname, $snmp_community, $oids[$arg] . ".{$index}", $snmp_version, $snmp_auth_username, $snmp_auth_password, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $snmp_port, $snmp_timeout, read_config_option("snmp_retries"), SNMP_POLLER);
            }
        } else {
            return $value;
        }
    }
}
Ejemplo n.º 4
0
/**
 * run the data query
 * @param int $device_id
 * @param int $snmp_query_id
 */
function run_data_query($device_id, $snmp_query_id) {
	global $config;

	require_once(CACTI_BASE_PATH . "/include/data_input/data_input_constants.php");
	include_once(CACTI_BASE_PATH . "/lib/poller.php");
	include_once(CACTI_BASE_PATH . "/lib/utility.php");

	debug_log_insert("data_query", __("Running data query") . " [$snmp_query_id].");
	$type_id = db_fetch_cell("select data_input.type_id from (snmp_query,data_input) where snmp_query.data_input_id=data_input.id and snmp_query.id=$snmp_query_id");

	if ($type_id == DATA_INPUT_TYPE_SNMP_QUERY) {
		debug_log_insert("data_query", __("Found type") . " = '3' [snmp query].");
		$result = query_snmp_device($device_id, $snmp_query_id);
	}elseif ($type_id == DATA_INPUT_TYPE_SCRIPT_QUERY) {
		debug_log_insert("data_query", __("Found type") . " = '4 '[script query].");
		$result = query_script_device($device_id, $snmp_query_id);
	}elseif ($type_id == DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER) {
		debug_log_insert("data_query", __("Found type") . " = '6 '[script query].");
		$result = query_script_device($device_id, $snmp_query_id);
	}else{
		debug_log_insert("data_query", __("Unknown type") . " = '$type_id'");
	}

	/* update the sort cache */
	update_data_query_sort_cache($device_id, $snmp_query_id);

	/* update the auto reindex cache */
	update_reindex_cache($device_id, $snmp_query_id);

	/* update the the "local" data query cache */
	update_data_query_cache($device_id, $snmp_query_id);

	/* update the poller cache */
	update_poller_cache_from_query($device_id, $snmp_query_id);

	api_plugin_hook_function('run_data_query', array("device_id" => $device_id, "snmp_query_id" => $snmp_query_id));

	return (isset($result) ? $result : true);
}
Ejemplo n.º 5
0
						</tr>
						<tr>
							<td colspan='2' align='center'>
								<strong><?php 
                print htmlspecialchars($rra["name"], ENT_QUOTES);
                ?>
</strong>
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<?php 
                $i++;
            }
            api_plugin_hook_function('tree_view_page_end');
        }
        break;
    case 'zoom':
        /* find the maximum time span a graph can show */
        $max_timespan = 1;
        if (sizeof($rras) > 0) {
            foreach ($rras as $rra) {
                if ($rra["steps"] * $rra["rows"] * $rra["rrd_step"] > $max_timespan) {
                    $max_timespan = $rra["steps"] * $rra["rows"] * $rra["rrd_step"];
                }
            }
        }
        /* fetch information for the current RRA */
        $rra = db_fetch_row("select id,timespan,steps,name from rra where id=" . $_GET["rra_id"]);
        /* define the time span, which decides which rra to use */
Ejemplo n.º 6
0
/** create_complete_graph_from_template - creates a graph and all necessary data sources based on a
	graph template
   @param int $graph_template_id 			- the id of the graph template that will be used to create the new	graph
   @param int $device_id 					- the id of the device to associate the new graph and data sources with
   @param array $snmp_query_array 			- if the new data sources are to be based on a data query, specify the
	necessary data query information here. it must contain the following information:
	  $snmp_query_array["snmp_query_id"]
	  $snmp_query_array["snmp_index_on"]
	  $snmp_query_array["snmp_query_graph_id"]
	  $snmp_query_array["snmp_index"]
   @param array $suggested_values_array 	- any additional information to be included in the new graphs or
	data sources must be included in the array. data is to be included in the following format:
	  $values["cg"][graph_template_id]["graph_template"][field_name] = $value  // graph template
	  $values["cg"][graph_template_id]["graph_template_item"][graph_template_item_id][field_name] = $value  // graph template item
	  $values["cg"][data_template_id]["data_template"][field_name] = $value  // data template
	  $values["cg"][data_template_id]["data_template_item"][data_template_item_id][field_name] = $value  // data template item
	  $values["sg"][data_query_id][graph_template_id]["graph_template"][field_name] = $value  // graph template (w/ data query)
	  $values["sg"][data_query_id][graph_template_id]["graph_template_item"][graph_template_item_id][field_name] = $value  // graph template item (w/ data query)
	  $values["sg"][data_query_id][data_template_id]["data_template"][field_name] = $value  // data template (w/ data query)
	  $values["sg"][data_query_id][data_template_id]["data_template_item"][data_template_item_id][field_name] = $value  // data template item (w/ data query) */
function create_complete_graph_from_template($graph_template_id, $device_id, $snmp_query_array, &$suggested_values_array) {
	global $config;

	include_once(CACTI_BASE_PATH . "/lib/data_query.php");

	/* create the graph */
	$save["id"] = 0;
	$save["graph_template_id"] = $graph_template_id;
	$save["device_id"] = $device_id;

	$cache_array["local_graph_id"] = sql_save($save, "graph_local");
	change_graph_template($cache_array["local_graph_id"], $graph_template_id, true);

	if (is_array($snmp_query_array)) {
		/* suggested values for snmp query code */
		$suggested_values = db_fetch_assoc("select text,field_name from snmp_query_graph_sv where snmp_query_graph_id=" . $snmp_query_array["snmp_query_graph_id"] . " order by sequence");

		if (sizeof($suggested_values) > 0) {
		foreach ($suggested_values as $suggested_value) {
			/* once we find a match; don't try to find more */
			if (!isset($suggested_values_graph[$graph_template_id]{$suggested_value["field_name"]})) {
				$subs_string = substitute_snmp_query_data($suggested_value["text"], $device_id, $snmp_query_array["snmp_query_id"], $snmp_query_array["snmp_index"], read_config_option("max_data_query_field_length"), false);
				/* if there are no '|' characters, all of the substitutions were successful */
				if (!strstr($subs_string, "|query")) {
					db_execute("update graph_templates_graph set " . $suggested_value["field_name"] . "='" . addslashes($subs_string) . "' where local_graph_id=" . $cache_array["local_graph_id"]);

					/* once we find a working value, stop */
					$suggested_values_graph[$graph_template_id]{$suggested_value["field_name"]} = true;
				}
			}
		}
		}
	}

	/* suggested values: graph */
	if (isset($suggested_values_array[$graph_template_id]["graph_template"])) {
		while (list($field_name, $field_value) = each($suggested_values_array[$graph_template_id]["graph_template"])) {
			db_execute("update graph_templates_graph set $field_name='$field_value' where local_graph_id=" . $cache_array["local_graph_id"]);
		}
	}

	/* suggested values: graph item */
	if (isset($suggested_values_array[$graph_template_id]["graph_template_item"])) {
		while (list($graph_template_item_id, $field_array) = each($suggested_values_array[$graph_template_id]["graph_template_item"])) {
			while (list($field_name, $field_value) = each($field_array)) {
				$graph_item_id = db_fetch_cell("select id from graph_templates_item where local_graph_template_item_id=$graph_template_item_id and local_graph_id=" . $cache_array["local_graph_id"]);
				db_execute("update graph_templates_item set $field_name='$field_value' where id=$graph_item_id");
			}
		}
	}

	update_graph_title_cache($cache_array["local_graph_id"]);

	/* create each data source */
	$data_templates = db_fetch_assoc("select
		data_template.id,
		data_template.name,
		data_template_rrd.data_source_name
		from (data_template, data_template_rrd, graph_templates_item)
		where graph_templates_item.task_item_id=data_template_rrd.id
		and data_template_rrd.data_template_id=data_template.id
		and data_template_rrd.local_data_id=0
		and graph_templates_item.local_graph_id=0
		and graph_templates_item.graph_template_id=" . $graph_template_id . "
		group by data_template.id
		order by data_template.name");

	if (sizeof($data_templates) > 0) {
	foreach ($data_templates as $data_template) {
		unset($save);

		$save["id"] = 0;
		$save["data_template_id"] = $data_template["id"];
		$save["device_id"] = $device_id;

		$cache_array["local_data_id"]{$data_template["id"]} = sql_save($save, "data_local");
		change_data_template($cache_array["local_data_id"]{$data_template["id"]}, $data_template["id"]);

		$data_template_data_id = db_fetch_cell("select id from data_template_data where local_data_id=" . $cache_array["local_data_id"]{$data_template["id"]});

		if (is_array($snmp_query_array)) {
			/* suggested values for snmp query code */
			$suggested_values = db_fetch_assoc("select text,field_name from snmp_query_graph_rrd_sv where snmp_query_graph_id=" . $snmp_query_array["snmp_query_graph_id"] . " and data_template_id=" . $data_template["id"] . " order by sequence");

			if (sizeof($suggested_values) > 0) {
			foreach ($suggested_values as $suggested_value) {
				/* once we find a match; don't try to find more */
				if (!isset($suggested_values_ds{$data_template["id"]}{$suggested_value["field_name"]})) {
					$subs_string = substitute_snmp_query_data($suggested_value["text"], $device_id, $snmp_query_array["snmp_query_id"], $snmp_query_array["snmp_index"], read_config_option("max_data_query_field_length"), false);

					/* if there are no '|' characters, all of the substitutions were successful */
					if (!strstr($subs_string, "|query")) {
						if (sizeof(db_fetch_row("show columns from data_template_data like '" . $suggested_value["field_name"] . "'"))) {
							db_execute("update data_template_data set " . $suggested_value["field_name"] . "='" . addslashes($subs_string) . "' where local_data_id=" . $cache_array["local_data_id"]{$data_template["id"]});
						}

						/* once we find a working value, stop */
						$suggested_values_ds{$data_template["id"]}{$suggested_value["field_name"]} = true;

						if ((sizeof(db_fetch_row("show columns from data_template_rrd like '" . $suggested_value["field_name"] . "'"))) &&
							(!substr_count($subs_string, "|"))) {
							db_execute("update data_template_rrd set " . $suggested_value["field_name"] . "='" . $subs_string . "' where local_data_id=" . $cache_array["local_data_id"]{$data_template["id"]});
						}
					}
				}
			}
			}
		}

		if (is_array($snmp_query_array)) {
			$data_input_field = array_rekey(db_fetch_assoc("SELECT
				data_input_fields.id,
				data_input_fields.type_code
				FROM (snmp_query,data_input,data_input_fields)
				WHERE snmp_query.data_input_id=data_input.id
				AND data_input.id=data_input_fields.data_input_id
				AND (data_input_fields.type_code='index_type'
					OR data_input_fields.type_code='index_value'
					OR data_input_fields.type_code='output_type')
				AND snmp_query.id=" . $snmp_query_array["snmp_query_id"]), "type_code", "id");

			$snmp_cache_value = db_fetch_cell("SELECT field_value
				FROM device_snmp_cache
				WHERE device_id='$device_id'
				AND snmp_query_id='" . $snmp_query_array["snmp_query_id"] . "'
				AND field_name='" . $snmp_query_array["snmp_index_on"] . "'
				AND snmp_index='" . $snmp_query_array["snmp_index"] . "'");

			/* save the value to index on (ie. ifindex, ifip, etc) */
			db_execute("REPLACE INTO data_input_data
				(data_input_field_id, data_template_data_id, t_value, value)
				VALUES (" . $data_input_field["index_type"] . ", $data_template_data_id, '', '" . $snmp_query_array["snmp_index_on"] . "')");

			/* save the actual value (ie. 3, 192.168.1.101, etc) */
			db_execute("REPLACE INTO data_input_data
				(data_input_field_id,data_template_data_id,t_value,value)
				VALUES (" . $data_input_field["index_value"] . ",$data_template_data_id,'','" . addslashes($snmp_cache_value) . "')");

			/* set the expected output type (ie. bytes, errors, packets) */
			db_execute("REPLACE INTO data_input_data
				(data_input_field_id,data_template_data_id,t_value,value)
				VALUES (" . $data_input_field["output_type"] . ",$data_template_data_id,'','" . $snmp_query_array["snmp_query_graph_id"] . "')");

			/* now that we have put data into the 'data_input_data' table, update the snmp cache for ds's */
			update_data_source_data_query_cache($cache_array["local_data_id"]{$data_template["id"]});
		}

		/* suggested values: data source */
		if (isset($suggested_values_array[$graph_template_id]["data_template"]{$data_template["id"]})) {
			reset($suggested_values_array[$graph_template_id]["data_template"]{$data_template["id"]});
			while (list($field_name, $field_value) = each($suggested_values_array[$graph_template_id]["data_template"]{$data_template["id"]})) {
				db_execute("UPDATE data_template_data
					SET $field_name='$field_value'
					WHERE local_data_id=" . $cache_array["local_data_id"]{$data_template["id"]});
			}
		}

		/* suggested values: data source item */
		if (isset($suggested_values_array[$graph_template_id]["data_template_item"])) {
			reset($suggested_values_array[$graph_template_id]["data_template_item"]);
			while (list($data_template_item_id, $field_array) = each($suggested_values_array[$graph_template_id]["data_template_item"])) {
				while (list($field_name, $field_value) = each($field_array)) {
					$data_source_item_id = db_fetch_cell("select id from data_template_rrd where local_data_template_rrd_id=$data_template_item_id and local_data_id=" . $cache_array["local_data_id"]{$data_template["id"]});
					db_execute("UPDATE data_template_rrd
						SET $field_name='$field_value'
						WHERE id=$data_source_item_id");
				}
			}
		}

		/* suggested values: custom data */
		if (isset($suggested_values_array[$graph_template_id]["custom_data"]{$data_template["id"]})) {
			reset($suggested_values_array[$graph_template_id]["custom_data"]{$data_template["id"]});
			while (list($data_input_field_id, $field_value) = each($suggested_values_array[$graph_template_id]["custom_data"]{$data_template["id"]})) {
				db_execute("replace into data_input_data (data_input_field_id,data_template_data_id,t_value,value) values ($data_input_field_id,$data_template_data_id,'','$field_value')");
			}
		}

		update_data_source_title_cache($cache_array["local_data_id"]{$data_template["id"]});
	}
	}

	/* connect the dots: graph -> data source(s) */
	$template_item_list = db_fetch_assoc("select
		graph_templates_item.id,
		data_template_rrd.id as data_template_rrd_id,
		data_template_rrd.data_template_id
		from (graph_templates_item,data_template_rrd)
		where graph_templates_item.task_item_id=data_template_rrd.id
		and graph_templates_item.graph_template_id=$graph_template_id
		and local_graph_id=0
		and task_item_id>0");

	/* loop through each item affected and update column data */
	if (sizeof($template_item_list) > 0) {
	foreach ($template_item_list as $template_item) {
		$local_data_id = $cache_array["local_data_id"]{$template_item["data_template_id"]};

		$graph_template_item_id = db_fetch_cell("select id from graph_templates_item where local_graph_template_item_id=" . $template_item["id"] . " and local_graph_id=" . $cache_array["local_graph_id"]);
		$data_template_rrd_id = db_fetch_cell("select id from data_template_rrd where local_data_template_rrd_id=" . $template_item["data_template_rrd_id"] . " and local_data_id=$local_data_id");

		if (!empty($data_template_rrd_id)) {
			db_execute("update graph_templates_item set task_item_id='$data_template_rrd_id' where id=$graph_template_item_id");
		}
	}
	}

	/* this will not work until the ds->graph dots are connected */
	if (is_array($snmp_query_array)) {
		update_graph_data_query_cache($cache_array["local_graph_id"]);
	}

	# now that we have the id of the new host, we may plugin postprocessing code
	$save["id"] = $cache_array["local_graph_id"];
	$save["graph_template_id"] = $graph_template_id;	// attention: unset!
	if (is_array($snmp_query_array)) {
		$save["snmp_query_id"] = $snmp_query_array["snmp_query_id"];
		$save["snmp_index"] = $snmp_query_array["snmp_index"];
	} else {
		$save["snmp_query_id"] = 0;
		$save["snmp_index"] = 0;
	}
	api_plugin_hook_function('create_complete_graph_from_template', $save);

	return $cache_array;
}
Ejemplo n.º 7
0
                        /* default graph page */
                        header("Location: graph_view.php");
                        break;
                    default:
                        api_plugin_hook_function('login_options_navigate', $user['login_opts']);
                }
            } else {
                header("Location: graph_view.php");
            }
            exit;
        } else {
            $bad_password = true;
        }
        break;
}
if (api_plugin_hook_function('custom_password', OPER_MODE_NATIVE) == OPER_MODE_RESKIN) {
    exit;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>Login to cacti</title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	<STYLE TYPE="text/css">
	<!--
		BODY, TABLE, TR, TD {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px;}
		A {text-decoration: none;}
		A:active { text-decoration: none;}
		A:hover {text-decoration: underline; color: #333333;}
		A:visited {color: Blue;}
Ejemplo n.º 8
0
function schedule_edit()
{
    global $plugins, $config, $tabs, $maint_types, $maint_intervals;
    /* ================= input validation ================= */
    get_filter_request_var('id');
    /* ==================================================== */
    maint_tabs();
    if (isset_request_var('id')) {
        $id = get_request_var('id');
        $maint_item_data = db_fetch_row('SELECT * FROM plugin_maint_schedules WHERE id = ' . $id);
    } else {
        $id = 0;
        $maint_item_data = array('id' => 0, 'name' => __('New Maintenance Schedule'), 'enabled' => 'on', 'mtype' => 1, 'stime' => time(), 'etime' => time() + 3600, 'minterval' => 0);
    }
    $header_label = get_header_label();
    if (get_request_var('tab') == 'general') {
        form_start('maint.php', 'maint');
        html_start_box(htmlspecialchars($header_label), '100%', '', '3', 'center', '');
        $form_array = array('general_header' => array('friendly_name' => __('Schedule'), 'method' => 'spacer'), 'name' => array('friendly_name' => __('Schedule Name'), 'method' => 'textbox', 'max_length' => 100, 'default' => $maint_item_data['name'], 'description' => __('Provide the Maintenance Schedule a meaningful name'), 'value' => isset($maint_item_data['name']) ? $maint_item_data['name'] : ''), 'enabled' => array('friendly_name' => __('Enabled'), 'method' => 'checkbox', 'default' => 'on', 'description' => __('Whether or not this threshold will be checked and alerted upon.'), 'value' => isset($maint_item_data['enabled']) ? $maint_item_data['enabled'] : ''), 'mtype' => array('friendly_name' => __('Schedule Type'), 'method' => 'drop_array', 'on_change' => 'changemaintType()', 'array' => $maint_types, 'description' => __('The type of Threshold that will be monitored.'), 'value' => isset($maint_item_data['mtype']) ? $maint_item_data['mtype'] : ''), 'minterval' => array('friendly_name' => __('Interval'), 'method' => 'drop_array', 'array' => $maint_intervals, 'default' => 86400, 'description' => __('This is the interval in which the start / end time will repeat.'), 'value' => isset($maint_item_data['minterval']) ? $maint_item_data['minterval'] : '1'), 'stime' => array('friendly_name' => __('Start Time'), 'method' => 'textbox', 'max_length' => 100, 'description' => __('The start date / time for this schedule. Most date / time formats accepted.'), 'default' => date('F j, Y, G:i', time()), 'value' => isset($maint_item_data['stime']) ? date('F j, Y,  G:i', $maint_item_data['stime']) : ''), 'etime' => array('friendly_name' => __('End Time'), 'method' => 'textbox', 'max_length' => 100, 'default' => date('F j, Y, G:i', time() + 3600), 'description' => __('The end date / time for this schedule. Most date / time formats accepted.'), 'value' => isset($maint_item_data['etime']) ? date('F j, Y,  G:i', $maint_item_data['etime']) : ''), 'save_component' => array('method' => 'hidden', 'value' => '1'), 'save' => array('method' => 'hidden', 'value' => 'edit'), 'id' => array('method' => 'hidden', 'value' => $id));
        draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array));
        html_end_box();
        form_save_button('maint.php', 'return');
        ?>
		<script type='text/javascript'>

		var date1Open = false;
		var date2Open = false;

		function changemaintType () {
			type = $('#mtype').val();
			switch(type) {
			case '1':
				$('#row_minterval').hide();
				break;
			case '2':
				$('#row_minterval').show();
				break;
			}
		}
	
		$(function() {
			$('#stime').after('<i id="startDate" class="calendar fa fa-calendar" title="<?php 
        print __('Start Date/Time Selector');
        ?>
"></i>');
			$('#etime').after('<i id="endDate" class="calendar fa fa-calendar" title="<?php 
        print __('End Date/Time Selector');
        ?>
"></i>');
			$('#startDate').click(function() {
				if (date1Open) {
					date1Open = false;
					$('#stime').datetimepicker('hide');
				}else{
					date1Open = true;
					$('#stime').datetimepicker('show');
				}
			});

			$('#endDate').click(function() {
				if (date2Open) {
					date2Open = false;
					$('#etime').datetimepicker('hide');
				}else{
					date2Open = true;
					$('#etime').datetimepicker('show');
				}
			});

			changemaintType ();

			$('#stime').datetimepicker({
				minuteGrid: 10,
				stepMinute: 1,
				showAnim: 'slideDown',
				numberOfMonths: 1,
				timeFormat: 'HH:mm',
				dateFormat: 'MM d, yy, ',
				showButtonPanel: false
			});

			$('#etime').datetimepicker({
				minuteGrid: 10,
				stepMinute: 1,
				showAnim: 'slideDown',
				numberOfMonths: 1,
				timeFormat: 'HH:mm',
				dateFormat: 'MM d, yy, ',
				showButtonPanel: false
			});
		});
		</script>
		<?php 
    } elseif (get_request_var('tab') == 'hosts') {
        thold_hosts($header_label);
    } elseif (get_request_var('tab') == 'webseer') {
        webseer_urls($header_label);
    } else {
        api_plugin_hook_function('maint_show_tab', $header_label);
    }
}
Ejemplo n.º 9
0
Archivo: host.php Proyecto: MrWnn/cacti
function form_actions()
{
    global $device_actions, $fields_host_edit;
    /* ================= input validation ================= */
    input_validate_input_regex(get_request_var_post('drp_action'), '^([a-zA-Z0-9_]+)$');
    /* ==================================================== */
    /* if we are to save this form, instead of display it */
    if (isset($_POST['selected_items'])) {
        $selected_items = unserialize(stripslashes($_POST['selected_items']));
        if ($_POST['drp_action'] == '2') {
            /* Enable Selected Devices */
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                /* ==================================================== */
                db_execute_prepared("UPDATE host SET disabled = '' WHERE id = ?", array($selected_items[$i]));
                /* update poller cache */
                $data_sources = db_fetch_assoc_prepared('SELECT id FROM data_local WHERE host_id = ?', array($selected_items[$i]));
                $poller_items = $local_data_ids = array();
                if (sizeof($data_sources) > 0) {
                    foreach ($data_sources as $data_source) {
                        $local_data_ids[] = $data_source['id'];
                        $poller_items = array_merge($poller_items, update_poller_cache($data_source['id']));
                    }
                }
                if (sizeof($local_data_ids)) {
                    poller_update_poller_cache_from_buffer($local_data_ids, $poller_items);
                }
            }
        } elseif ($_POST['drp_action'] == '3') {
            /* Disable Selected Devices */
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                /* ==================================================== */
                db_execute_prepared("UPDATE host SET disabled='on' WHERE id = ?", array($selected_items[$i]));
                /* update poller cache */
                db_execute_prepared('DELETE FROM poller_item WHERE host_id = ?', array($selected_items[$i]));
                db_execute_prepared('DELETE FROM poller_reindex WHERE host_id = ?', array($selected_items[$i]));
            }
        } elseif ($_POST['drp_action'] == '4') {
            /* change snmp options */
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                /* ==================================================== */
                reset($fields_host_edit);
                while (list($field_name, $field_array) = each($fields_host_edit)) {
                    if (isset($_POST["t_{$field_name}"])) {
                        db_execute_prepared("UPDATE host SET {$field_name} = ? WHERE id = ?", array($_POST[$field_name], $selected_items[$i]));
                    }
                }
                push_out_host($selected_items[$i]);
            }
        } elseif ($_POST['drp_action'] == '5') {
            /* Clear Statisitics for Selected Devices */
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                /* ==================================================== */
                db_execute_prepared("UPDATE host SET min_time = '9.99999', max_time = '0', cur_time = '0', avg_time = '0',\n\t\t\t\t\t\ttotal_polls = '0', failed_polls = '0',\tavailability = '100.00'\n\t\t\t\t\t\twhere id = ?", array($selected_items[$i]));
            }
        } elseif ($_POST['drp_action'] == '6') {
            /* change availability options */
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                /* ==================================================== */
                reset($fields_host_edit);
                while (list($field_name, $field_array) = each($fields_host_edit)) {
                    if (isset($_POST["t_{$field_name}"])) {
                        db_execute_prepared("UPDATE host SET {$field_name} = ? WHERE id = ?", array($_POST[$field_name], $selected_items[$i]));
                    }
                }
                push_out_host($selected_items[$i]);
            }
        } elseif ($_POST['drp_action'] == '1') {
            /* delete */
            if (!isset($_POST['delete_type'])) {
                $_POST['delete_type'] = 2;
            }
            $data_sources_to_act_on = array();
            $graphs_to_act_on = array();
            $devices_to_act_on = array();
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                /* ==================================================== */
                $data_sources = db_fetch_assoc('SELECT
					data_local.id AS local_data_id
					FROM data_local
					WHERE ' . array_to_sql_or($selected_items, 'data_local.host_id'));
                if (sizeof($data_sources) > 0) {
                    foreach ($data_sources as $data_source) {
                        $data_sources_to_act_on[] = $data_source['local_data_id'];
                    }
                }
                if ($_POST['delete_type'] == 2) {
                    $graphs = db_fetch_assoc('SELECT
						graph_local.id AS local_graph_id
						FROM graph_local
						WHERE ' . array_to_sql_or($selected_items, 'graph_local.host_id'));
                    if (sizeof($graphs) > 0) {
                        foreach ($graphs as $graph) {
                            $graphs_to_act_on[] = $graph['local_graph_id'];
                        }
                    }
                }
                $devices_to_act_on[] = $selected_items[$i];
            }
            switch ($_POST['delete_type']) {
                case '1':
                    /* leave graphs and data_sources in place, but disable the data sources */
                    api_data_source_disable_multi($data_sources_to_act_on);
                    api_plugin_hook_function('data_source_remove', $data_sources_to_act_on);
                    break;
                case '2':
                    /* delete graphs/data sources tied to this device */
                    api_data_source_remove_multi($data_sources_to_act_on);
                    api_graph_remove_multi($graphs_to_act_on);
                    api_plugin_hook_function('graphs_remove', $graphs_to_act_on);
                    break;
            }
            api_device_remove_multi($devices_to_act_on);
            api_plugin_hook_function('device_remove', $devices_to_act_on);
        } elseif (preg_match('/^tr_([0-9]+)$/', $_POST['drp_action'], $matches)) {
            /* place on tree */
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                input_validate_input_number(get_request_var_post('tree_id'));
                input_validate_input_number(get_request_var_post('tree_item_id'));
                /* ==================================================== */
                api_tree_item_save(0, $_POST['tree_id'], TREE_ITEM_TYPE_HOST, $_POST['tree_item_id'], '', 0, read_graph_config_option('default_rra_id'), $selected_items[$i], 1, 1, false);
            }
        } else {
            api_plugin_hook_function('device_action_execute', $_POST['drp_action']);
        }
        /* update snmpcache */
        snmpagent_device_action_bottom(array($_POST['drp_action'], $selected_items));
        api_plugin_hook_function('device_action_bottom', array($_POST['drp_action'], $selected_items));
        header('Location: host.php');
        exit;
    }
    /* setup some variables */
    $host_list = '';
    $i = 0;
    /* loop through each of the host templates selected on the previous page and get more info about them */
    while (list($var, $val) = each($_POST)) {
        if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) {
            /* ================= input validation ================= */
            input_validate_input_number($matches[1]);
            /* ==================================================== */
            $host_list .= '<li>' . htmlspecialchars(db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($matches[1]))) . '<br>';
            $host_array[$i] = $matches[1];
            $i++;
        }
    }
    top_header();
    /* add a list of tree names to the actions dropdown */
    add_tree_names_to_actions_array();
    html_start_box('<strong>' . $device_actions[get_request_var_post('drp_action')] . '</strong>', '60%', '', '3', 'center', '');
    print "<form action='host.php' autocomplete='off' method='post'>\n";
    if (isset($host_array) && sizeof($host_array)) {
        if ($_POST['drp_action'] == '2') {
            /* Enable Devices */
            print "\t<tr>\n\t\t\t\t\t<td colspan='2' class='textArea'>\n\t\t\t\t\t\t<p>To enable the following Device(s), click \"Continue\".</p>\n\t\t\t\t\t\t<p><ul>" . $host_list . "</ul></p>\n\t\t\t\t\t</td>\n\t\t\t\t\t</tr>";
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue' title='Enable Device(s)'>";
        } elseif ($_POST['drp_action'] == '3') {
            /* Disable Devices */
            print "\t<tr>\n\t\t\t\t\t<td colspan='2' class='textArea'>\n\t\t\t\t\t\t<p>To disable the following Device(s), click \"Continue\".</p>\n\t\t\t\t\t\t<p><ul>" . $host_list . '</ul></p>
					</td>
					</tr>';
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue' title='Disable Device(s)'>";
        } elseif ($_POST['drp_action'] == '4') {
            /* change snmp options */
            print "\t<tr>\n\t\t\t\t\t<td colspan='2' class='textArea'>\n\t\t\t\t\t\t<p>To change SNMP parameters for the following Device(s), check the box next to the fields\n\t\t\t\t\t\tyou want to update, fill in the new value, and click \"Continue\".</p>\n\t\t\t\t\t\t<p><ul>" . $host_list . '</ul></p>
					</td>
					</tr>';
            $form_array = array();
            while (list($field_name, $field_array) = each($fields_host_edit)) {
                if (preg_match('/^snmp_/', $field_name) || $field_name == 'max_oids') {
                    $form_array += array($field_name => $fields_host_edit[$field_name]);
                    $form_array[$field_name]['value'] = '';
                    $form_array[$field_name]['description'] = '';
                    $form_array[$field_name]['form_id'] = 0;
                    $form_array[$field_name]['sub_checkbox'] = array('name' => 't_' . $field_name, 'friendly_name' => 'Update this Field', 'value' => '');
                }
            }
            draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array));
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue' title='Change Device(s) SNMP Options'>";
        } elseif ($_POST['drp_action'] == '6') {
            /* change availability options */
            print "\t<tr>\n\t\t\t\t\t<td colspan='2' class='textArea'>\n\t\t\t\t\t\t<p>To change Availability parameters for the following Device(s), check the box next to the fields\n\t\t\t\t\t\tyou want to update, fill in the new value, and click \"Continue\".</p>\n\t\t\t\t\t\t<p><ul>" . $host_list . '</ul></p>
					</td>
					</tr>';
            $form_array = array();
            while (list($field_name, $field_array) = each($fields_host_edit)) {
                if (preg_match('/(availability_method|ping_method|ping_port)/', $field_name)) {
                    $form_array += array($field_name => $fields_host_edit[$field_name]);
                    $form_array[$field_name]['value'] = '';
                    $form_array[$field_name]['description'] = '';
                    $form_array[$field_name]['form_id'] = 0;
                    $form_array[$field_name]['sub_checkbox'] = array('name' => 't_' . $field_name, 'friendly_name' => 'Update this Field', 'value' => '');
                }
            }
            draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array));
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue' title='Change Device(s) Availability Options'>";
        } elseif ($_POST['drp_action'] == '5') {
            /* Clear Statisitics for Selected Devices */
            print "\t<tr>\n\t\t\t\t\t<td colspan='2' class='textArea'>\n\t\t\t\t\t\t<p>To clear the counters for the following Device(s), press the \"Continue\" button below.</p>\n\t\t\t\t\t\t<p><ul>" . $host_list . '</ul></p>
					</td>
					</tr>';
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue' title='Clear Statistics on Device(s)'>";
        } elseif ($_POST['drp_action'] == '1') {
            /* delete */
            print "\t<tr>\n\t\t\t\t\t<td class='textArea'>\n\t\t\t\t\t\t<p>When you click \"Continue\" the following Device(s) will be deleted.</p>\n\t\t\t\t\t\t<p><ul>" . $host_list . '</ul></p>';
            form_radio_button('delete_type', '2', '1', 'Leave all Graph(s) and Data Source(s) untouched.  Data Source(s) will be disabled however.', '1');
            print '<br>';
            form_radio_button('delete_type', '2', '2', 'Delete all associated <strong>Graph(s)</strong> and <strong>Data Source(s)</strong>.', '1');
            print '<br>';
            print "</td></tr>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\n\t\t\t\t";
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue' title='Delete Device(s)'>";
        } elseif (preg_match('/^tr_([0-9]+)$/', $_POST['drp_action'], $matches)) {
            /* place on tree */
            print "\t<tr>\n\t\t\t\t\t<td class='textArea'>\n\t\t\t\t\t\t<p>When you click \"Continue\", the following Device(s) will be placed under the branch selected\n\t\t\t\t\t\tbelow.</p>\n\t\t\t\t\t\t<p><ul>" . $host_list . '</ul></p>
						<p><strong>Destination Branch:</strong><br>';
            grow_dropdown_tree($matches[1], '0', 'tree_item_id', '0');
            print "</p>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\n\t\t\t\t<input type='hidden' name='tree_id' value='" . $matches[1] . "'>\n\n\t\t\t\t";
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue' title='Place Device(s) on Tree'>";
        } else {
            $save['drp_action'] = $_POST['drp_action'];
            $save['host_list'] = $host_list;
            $save['host_array'] = isset($host_array) ? $host_array : array();
            api_plugin_hook_function('device_action_prepare', $save);
            $save_html = "<input type='button' value='Cancel' onClick='window.history.back()'>&nbsp;<input type='submit' value='Continue'>";
        }
    } else {
        print "<tr><td class='even'><span class='textError'>You must select at least one device.</span></td></tr>\n";
        $save_html = "<input type='button' value='Return' onClick='window.history.back()'>";
    }
    print "\t<tr>\n\t\t\t<td colspan='2' align='right' class='saveRow'>\n\t\t\t\t<input type='hidden' name='action' value='actions'>\n\t\t\t\t<input type='hidden' name='selected_items' value='" . (isset($host_array) ? serialize($host_array) : '') . "'>\n\t\t\t\t<input type='hidden' name='drp_action' value='" . $_POST['drp_action'] . "'>\n\t\t\t\t{$save_html}\n\t\t\t</td>\n\t\t</tr>\n\t\t";
    html_end_box();
    bottom_footer();
}
Ejemplo n.º 10
0
function substitute_host_data($string, $l_escape_string, $r_escape_string, $host_id)
{
    if (!empty($host_id)) {
        if (!isset($_SESSION['sess_host_cache_array'][$host_id])) {
            $host = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id));
            $_SESSION['sess_host_cache_array'][$host_id] = $host;
        }
        $string = str_replace($l_escape_string . 'host_management_ip' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['hostname'], $string);
        /* for compatability */
        $string = str_replace($l_escape_string . 'host_hostname' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['hostname'], $string);
        $string = str_replace($l_escape_string . 'host_description' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['description'], $string);
        $string = str_replace($l_escape_string . 'host_notes' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['notes'], $string);
        $string = str_replace($l_escape_string . 'host_polling_time' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['polling_time'], $string);
        $string = str_replace($l_escape_string . 'host_avg_time' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['avg_time'], $string);
        $string = str_replace($l_escape_string . 'host_cur_time' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['cur_time'], $string);
        $string = str_replace($l_escape_string . 'host_availability' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['availability'], $string);
        /* snmp connectivity information */
        $string = str_replace($l_escape_string . 'host_snmp_community' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_community'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_version' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_version'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_username' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_username'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_password' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_password'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_auth_protocol' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_auth_protocol'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_priv_passphrase' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_priv_passphrase'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_priv_protocol' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_priv_protocol'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_context' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_context'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_port' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_port'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_timeout' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_timeout'], $string);
        /* snmp system information */
        $string = str_replace($l_escape_string . 'host_snmp_sysDescr' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysDescr'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysObjectID' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysObjectID'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysContact' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysContact'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysLocation' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysLocation'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysName' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysName'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysUpTimeInstance' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysUpTimeInstance'], $string);
        $string = str_replace($l_escape_string . 'host_ping_retries' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['ping_retries'], $string);
        $string = str_replace($l_escape_string . 'host_max_oids' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['max_oids'], $string);
        $string = str_replace($l_escape_string . 'host_id' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['id'], $string);
        $temp = api_plugin_hook_function('substitute_host_data', array('string' => $string, 'l_escape_string' => $l_escape_string, 'r_escape_string' => $r_escape_string, 'host_id' => $host_id));
        $string = $temp['string'];
    }
    return $string;
}
Ejemplo n.º 11
0
function syslog_filter($sql_where, $tab)
{
    global $colors, $config, $graph_timespans, $graph_timeshifts, $reset_multi, $page_refresh_interval;
    include dirname(__FILE__) . "/config.php";
    if (isset($_SESSION["sess_current_date1"])) {
        $filter_text = "</strong> [ Start: '" . $_SESSION["sess_current_date1"] . "' to End: '" . $_SESSION["sess_current_date2"] . "' ]";
    } else {
        $filter_text = "</strong>";
    }
    ?>
	<script type="text/javascript">
	<!--
	// Initialize the calendar
	calendar=null;

	// This function displays the calendar associated to the input field 'id'
	function showCalendar(id) {
		var el = document.getElementById(id);
		if (calendar != null) {
			// we already have some calendar created
			calendar.hide();  // so we hide it first.
		} else {
			// first-time call, create the calendar.
			var cal = new Calendar(true, null, selected, closeHandler);
			cal.weekNumbers = false;  // Do not display the week number
			cal.showsTime = true;     // Display the time
			cal.time24 = true;        // Hours have a 24 hours format
			cal.showsOtherMonths = false;    // Just the current month is displayed
			calendar = cal;                  // remember it in the global var
			cal.setRange(1900, 2070);        // min/max year allowed.
			cal.create();
		}

		calendar.setDateFormat('%Y-%m-%d %H:%M');    // set the specified date format
		calendar.parseDate(el.value);                // try to parse the text in field
		calendar.sel = el;                           // inform it what input field we use

		// Display the calendar below the input field
		calendar.showAtElement(el, "Br");        // show the calendar

		return false;
	}

	// This function update the date in the input field when selected
	function selected(cal, date) {
		cal.sel.value = date;      // just update the date in the input field.
	}

	// This function gets called when the end-user clicks on the 'Close' button.
	// It just hides the calendar without destroying it.
	function closeHandler(cal) {
		cal.hide();                        // hide the calendar
		calendar = null;
	}

	function applyTimespanFilterChange(objForm) {
		strURL = '?predefined_timespan=' + objForm.predefined_timespan.value;
		strURL = strURL + '&predefined_timeshift=' + objForm.predefined_timeshift.value;
		document.location = strURL;
	}
	-->
	</script>
	<form style='margin:0px;padding:0px;' id="syslog_form" name="syslog_form" method="post" action="syslog.php">
	<table width="100%" cellspacing="0" cellpadding="0" border="0">
		<tr>
			<td colspan="2" style="background-color:#EFEFEF;">
				<table width='100%' cellpadding="0" cellspacing="0" border="0">
					<tr>
						<td width='100%'>
							<?php 
    html_start_box("<strong>Syslog Message Filter{$filter_text}", "100%", $colors["header"], "1", "center", "");
    ?>
							<tr bgcolor="<?php 
    print $colors["panel"];
    ?>
" class="noprint">
								<td class="noprint">
									<table cellpadding="0" cellspacing="0" border="0">
										<tr>
											<td nowrap style='white-space: nowrap;' width='60'>
												&nbsp;<strong>Presets:</strong>&nbsp;
											</td>
											<td nowrap style='white-space: nowrap;' width='130'>
												<select name='predefined_timespan' onChange="applyTimespanFilterChange(document.syslog_form)">
													<?php 
    if ($_SESSION["custom"]) {
        $graph_timespans[GT_CUSTOM] = "Custom";
        $_REQUEST["predefined_timespan"] = GT_CUSTOM;
        $start_val = 0;
        $end_val = sizeof($graph_timespans);
    } else {
        if (isset($graph_timespans[GT_CUSTOM])) {
            asort($graph_timespans);
            array_shift($graph_timespans);
        }
        $start_val = 1;
        $end_val = sizeof($graph_timespans) + 1;
    }
    if (sizeof($graph_timespans) > 0) {
        for ($value = $start_val; $value < $end_val; $value++) {
            print "<option value='{$value}'";
            if ($_REQUEST["predefined_timespan"] == $value) {
                print " selected";
            }
            print ">" . title_trim($graph_timespans[$value], 40) . "</option>\n";
        }
    }
    ?>
												</select>
											</td>
											<td nowrap style='white-space: nowrap;' width='30'>
												&nbsp;<strong>From:</strong>&nbsp;
											</td>
											<td width='150' nowrap style='white-space: nowrap;'>
												<input type='text' name='date1' id='date1' title='Graph Begin Timestamp' size='14' value='<?php 
    print isset($_SESSION["sess_current_date1"]) ? $_SESSION["sess_current_date1"] : "";
    ?>
'>
												&nbsp;<input style='padding-bottom: 4px;' type='image' src='<?php 
    print $config["url_path"];
    ?>
images/calendar.gif' alt='Start date selector' title='Start date selector' border='0' align='absmiddle' onclick="return showCalendar('date1');">&nbsp;
											</td>
											<td nowrap style='white-space: nowrap;' width='20'>
												&nbsp;<strong>To:</strong>&nbsp;
											</td>
											<td width='150' nowrap style='white-space: nowrap;'>
												<input type='text' name='date2' id='date2' title='Graph End Timestamp' size='14' value='<?php 
    print isset($_SESSION["sess_current_date2"]) ? $_SESSION["sess_current_date2"] : "";
    ?>
'>
												&nbsp;<input style='padding-bottom: 4px;' type='image' src='<?php 
    print $config["url_path"];
    ?>
images/calendar.gif' alt='End date selector' title='End date selector' border='0' align='absmiddle' onclick="return showCalendar('date2');">
											</td>
											<td width='125' nowrap style='white-space: nowrap;'>
												&nbsp;&nbsp;<input style='padding-bottom: 4px;' type='image' name='move_left' src='<?php 
    print $config["url_path"];
    ?>
images/move_left.gif' alt='Left' border='0' align='absmiddle' title='Shift Left'>
												<select name='predefined_timeshift' title='Define Shifting Interval' onChange="applyTimespanFilterChange(document.syslog_form)">
													<?php 
    $start_val = 1;
    $end_val = sizeof($graph_timeshifts) + 1;
    if (sizeof($graph_timeshifts) > 0) {
        for ($shift_value = $start_val; $shift_value < $end_val; $shift_value++) {
            print "<option value='{$shift_value}'";
            if ($_REQUEST["predefined_timeshift"] == $shift_value) {
                print " selected";
            }
            print ">" . title_trim($graph_timeshifts[$shift_value], 40) . "</option>\n";
        }
    }
    ?>
												</select>
												<input style='padding-bottom: 4px;' type='image' name='move_right' src='<?php 
    print $config["url_path"];
    ?>
images/move_right.gif' alt='Right' border='0' align='absmiddle' title='Shift Right'>
											</td>
											<td>
												&nbsp;<input type="submit" value='Go' name='go' title="Go">
											</td>
											<td>
												&nbsp;<input type='submit' value='Clear' name='button_clear_x' title='Return to the default time span'>
											</td>
											<td>
												&nbsp;<input type='submit' value='Export' name='export' title='Export Records to CSV'>
											</td>
											<td>
												<input type='hidden' name='action' value='actions'>
												<input type='hidden' name='syslog_pdt_change' value='false'>
											</td>
										</tr>
									</table>
								</td><?php 
    if (api_plugin_user_realm_auth('syslog_alerts.php')) {
        ?>
								<td align='right' style='white-space:nowrap;'>
									<input type='button' value='Alerts' title='View Syslog Alert Rules' onClick='javascript:document.location="<?php 
        print $config['url_path'] . "plugins/syslog/syslog_alerts.php";
        ?>
"'>
									<input type='button' value='Removals' title='View Syslog Removal Rules' onClick='javascript:document.location="<?php 
        print $config['url_path'] . "plugins/syslog/syslog_removal.php";
        ?>
"'>
									<input type='button' value='Reports' title='View Syslog Reports' onClick='javascript:document.location="<?php 
        print $config['url_path'] . "plugins/syslog/syslog_reports.php";
        ?>
"'>&nbsp;
								</td><?php 
    }
    ?>
							</tr>
						</table>
						<table width="100%" cellpadding="0" cellspacing="0" border="0">
							<tr bgcolor="<?php 
    print $colors["panel"];
    ?>
" class="noprint">
								<td>
									<table cellpadding="0" cellspacing="0">
										<tr>
											<td nowrap style='white-space: nowrap;' width='60'>
												&nbsp;<strong>Search:</strong>
											</td>
											<td style='padding-right:2px;'>
												<input type="text" name="filter" size="30" value="<?php 
    print $_REQUEST["filter"];
    ?>
">
											</td>
											<?php 
    api_plugin_hook('syslog_extend_filter');
    ?>
											<td style='padding-right:2px;'>
												<select name="efacility" onChange="javascript:document.getElementById('syslog_form').submit();" title="Facilities">
													<option value="0"<?php 
    if ($_REQUEST["efacility"] == "0") {
        ?>
 selected<?php 
    }
    ?>
>All Facilities</option>
													<?php 
    if (!isset($hostfilter)) {
        $hostfilter = "";
    }
    $efacilities = syslog_db_fetch_assoc("SELECT DISTINCT f.facility_id, f.facility\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM `" . $syslogdb_default . "`.`syslog_host_facilities` AS fh\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN `" . $syslogdb_default . "`.`syslog_facilities` AS f\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tON f.facility_id=fh.facility_id " . (strlen($hostfilter) ? "WHERE " : "") . $hostfilter . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY facility");
    if (sizeof($efacilities)) {
        foreach ($efacilities as $efacility) {
            print "<option value=" . $efacility["facility_id"];
            if ($_REQUEST["efacility"] == $efacility["facility_id"]) {
                print " selected";
            }
            print ">" . ucfirst($efacility["facility"]) . "</option>\n";
        }
    }
    ?>
												</select>
											</td>
											<td style='padding-right:2px;'>
												<select name="elevel" onChange="javascript:document.getElementById('syslog_form').submit();" title="Priority Levels">
													<option value="0"<?php 
    if ($_REQUEST["elevel"] == "0") {
        ?>
 selected<?php 
    }
    ?>
>All Priorities</option>
													<option value="1"<?php 
    if ($_REQUEST["elevel"] == "1") {
        ?>
 selected<?php 
    }
    ?>
>Emergency</option>
													<option value="2"<?php 
    if ($_REQUEST["elevel"] == "2") {
        ?>
 selected<?php 
    }
    ?>
>Critical++</option>
													<option value="2o"<?php 
    if ($_REQUEST["elevel"] == "2o") {
        ?>
 selected<?php 
    }
    ?>
>Critical</option>
													<option value="3"<?php 
    if ($_REQUEST["elevel"] == "3") {
        ?>
 selected<?php 
    }
    ?>
>Alert++</option>
													<option value="3o"<?php 
    if ($_REQUEST["elevel"] == "3o") {
        ?>
 selected<?php 
    }
    ?>
>Alert</option>
													<option value="4"<?php 
    if ($_REQUEST["elevel"] == "4") {
        ?>
 selected<?php 
    }
    ?>
>Error++</option>
													<option value="4o"<?php 
    if ($_REQUEST["elevel"] == "4o") {
        ?>
 selected<?php 
    }
    ?>
>Error</option>
													<option value="5"<?php 
    if ($_REQUEST["elevel"] == "5") {
        ?>
 selected<?php 
    }
    ?>
>Warning++</option>
													<option value="5o"<?php 
    if ($_REQUEST["elevel"] == "5o") {
        ?>
 selected<?php 
    }
    ?>
>Warning</option>
													<option value="6"<?php 
    if ($_REQUEST["elevel"] == "6") {
        ?>
 selected<?php 
    }
    ?>
>Notice++</option>
													<option value="6o"<?php 
    if ($_REQUEST["elevel"] == "6o") {
        ?>
 selected<?php 
    }
    ?>
>Notice</option>
													<option value="7"<?php 
    if ($_REQUEST["elevel"] == "7") {
        ?>
 selected<?php 
    }
    ?>
>Info++</option>
													<option value="7o"<?php 
    if ($_REQUEST["elevel"] == "7o") {
        ?>
 selected<?php 
    }
    ?>
>Info</option>
													<option value="8"<?php 
    if ($_REQUEST["elevel"] == "8") {
        ?>
 selected<?php 
    }
    ?>
>Debug</option>
												</select>
											</td>
											<?php 
    if ($_REQUEST["tab"] == "syslog") {
        ?>
											<td style='padding-right:2px;'>
												<select name="removal" onChange="javascript:document.getElementById('syslog_form').submit();" title="Removal Handling">
													<option value="1"<?php 
        if ($_REQUEST["removal"] == "1") {
            ?>
 selected<?php 
        }
        ?>
>All Records</option>
													<option value="-1"<?php 
        if ($_REQUEST["removal"] == "-1") {
            ?>
 selected<?php 
        }
        ?>
>Main Records</option>
													<option value="2"<?php 
        if ($_REQUEST["removal"] == "2") {
            ?>
 selected<?php 
        }
        ?>
>Removed Records</option>
												</select>
											</td>
											<?php 
    }
    ?>
											<td style='padding-right:2px;'>
												<select name="rows" onChange="javascript:document.getElementById('syslog_form').submit();" title="Display Rows">
													<option value="10"<?php 
    if ($_REQUEST["rows"] == "10") {
        ?>
 selected<?php 
    }
    ?>
>10</option>
													<option value="15"<?php 
    if ($_REQUEST["rows"] == "15") {
        ?>
 selected<?php 
    }
    ?>
>15</option>
													<option value="20"<?php 
    if ($_REQUEST["rows"] == "20") {
        ?>
 selected<?php 
    }
    ?>
>20</option>
													<option value="25"<?php 
    if ($_REQUEST["rows"] == "25") {
        ?>
 selected<?php 
    }
    ?>
>25</option>
													<option value="30"<?php 
    if ($_REQUEST["rows"] == "30") {
        ?>
 selected<?php 
    }
    ?>
>30</option>
													<option value="35"<?php 
    if ($_REQUEST["rows"] == "35") {
        ?>
 selected<?php 
    }
    ?>
>35</option>
													<option value="40"<?php 
    if ($_REQUEST["rows"] == "40") {
        ?>
 selected<?php 
    }
    ?>
>40</option>
													<option value="45"<?php 
    if ($_REQUEST["rows"] == "45") {
        ?>
 selected<?php 
    }
    ?>
>45</option>
													<option value="50"<?php 
    if ($_REQUEST["rows"] == "50") {
        ?>
 selected<?php 
    }
    ?>
>50</option>
													<option value="100"<?php 
    if ($_REQUEST["rows"] == "100") {
        ?>
 selected<?php 
    }
    ?>
>100</option>
													<option value="200"<?php 
    if ($_REQUEST["rows"] == "200") {
        ?>
 selected<?php 
    }
    ?>
>200</option>
													<option value="500"<?php 
    if ($_REQUEST["rows"] == "500") {
        ?>
 selected<?php 
    }
    ?>
>500</option>
												</select>
											</td>
											<td style='padding-right:2px;'>
												<select name="trimval" onChange="javascript:document.getElementById('syslog_form').submit();" title="Message Trim">
													<option value="1024"<?php 
    if ($_REQUEST["trimval"] == "1024") {
        ?>
 selected<?php 
    }
    ?>
>All Text</option>
													<option value="30"<?php 
    if ($_REQUEST["trimval"] == "30") {
        ?>
 selected<?php 
    }
    ?>
>30 Chars</option>
													<option value="50"<?php 
    if ($_REQUEST["trimval"] == "50") {
        ?>
 selected<?php 
    }
    ?>
>50 Chars</option>
													<option value="75"<?php 
    if ($_REQUEST["trimval"] == "75") {
        ?>
 selected<?php 
    }
    ?>
>75 Chars</option>
													<option value="100"<?php 
    if ($_REQUEST["trimval"] == "100") {
        ?>
 selected<?php 
    }
    ?>
>100 Chars</option>
													<option value="150"<?php 
    if ($_REQUEST["trimval"] == "150") {
        ?>
 selected<?php 
    }
    ?>
>150 Chars</option>
													<option value="300"<?php 
    if ($_REQUEST["trimval"] == "300") {
        ?>
 selected<?php 
    }
    ?>
>300 Chars</option>
												</select>
											</td>
											<td width="1">
												<select name="refresh" onChange="javascript:document.getElementById('syslog_form').submit();">
													<?php 
    foreach ($page_refresh_interval as $seconds => $display_text) {
        print "<option value='" . $seconds . "'";
        if ($_REQUEST["refresh"] == $seconds) {
            print " selected";
        }
        print ">" . $display_text . "</option>\n";
    }
    ?>
												</select>
											</td>
										</tr>
									</table>
								</td>
							</tr>
							<?php 
    html_end_box(false);
    ?>
					</tr>
				</table>
			</td>
		</tr>
		<tr>
			<td valign="top" style="border-right: #aaaaaa 1px solid;" bgcolor='#efefef'>
				<table align="center" cellpadding="1" cellspacing="0" border="0">
					<tr>
						<td>
							<?php 
    html_start_box("", "", $colors["header"], "3", "center", "");
    ?>
							<tr>
								<td class="textHeader" nowrap>
									Select Host(s):&nbsp;
								</td>
							</tr>
							<tr>
								<td>
									<select title="Host Filters" id="host_select" name="host[]" multiple size="20" style="width: 150px; overflow: scroll; height: auto;" onChange="javascript:document.getElementById('syslog_form').submit();">
										<?php 
    if ($tab == "syslog") {
        ?>
<option id="host_all" value="0"<?php 
        if (is_array($_REQUEST["host"]) && $_REQUEST["host"][0] == "0" || $reset_multi) {
            ?>
 selected<?php 
        }
        ?>
>Show All Hosts</option><?php 
    } else {
        ?>
										<option id="host_all" value="0"<?php 
        if (is_array($_REQUEST["host"]) && $_REQUEST["host"][0] == "0" || $reset_multi) {
            ?>
 selected<?php 
        }
        ?>
>Show All Logs</option>
										<option id="host_none" value="-1"<?php 
        if (is_array($_REQUEST["host"]) && $_REQUEST["host"][0] == "-1") {
            ?>
 selected<?php 
        }
        ?>
>Threshold Logs</option><?php 
    }
    ?>
										<?php 
    $hosts_where = "";
    $hosts_where = api_plugin_hook_function('syslog_hosts_where', $hosts_where);
    $hosts = syslog_db_fetch_assoc("SELECT * FROM `" . $syslogdb_default . "`.`syslog_hosts` {$hosts_where} ORDER BY host");
    if (sizeof($hosts)) {
        foreach ($hosts as $host) {
            print "<option value=" . $host["host_id"];
            if (sizeof($_REQUEST["host"])) {
                foreach ($_REQUEST["host"] as $rh) {
                    if ($rh == $host["host_id"] && !$reset_multi) {
                        print " selected";
                        break;
                    }
                }
            } else {
                if ($host["host_id"] == $_REQUEST["host"] && !$reset_multi) {
                    print " selected";
                }
            }
            print ">";
            print $host["host"] . "</option>\n";
        }
    }
    ?>
									</select>
								</td>
							</tr>
							<?php 
    html_end_box(false);
    ?>
						</td>
					</tr>
				</table>
			</td>
			<td width="100%" valign="top" style="padding: 0px;">
				<table width="100%" cellspacing="0" cellpadding="1">
					<tr>
						<td width="100%" valign="top"><?php 
    display_output_messages();
    ?>
							<?php 
    if ($tab == "syslog") {
        if ($_REQUEST["removal"] == 1) {
            $total_rows = syslog_db_fetch_cell("SELECT SUM(totals)\n\t\t\t\t\t\t\t\t\t\t\tFROM (\n\t\t\t\t\t\t\t\t\t\t\tSELECT count(*) AS totals\n\t\t\t\t\t\t\t\t\t\t\tFROM `" . $syslogdb_default . "`.`syslog` " . $sql_where . "\n\t\t\t\t\t\t\t\t\t\t\tUNION\n\t\t\t\t\t\t\t\t\t\t\tSELECT count(*) AS totals\n\t\t\t\t\t\t\t\t\t\t\tFROM `" . $syslogdb_default . "`.`syslog_removed` " . $sql_where . ") AS rowcount");
        } elseif ($_REQUEST["removal"] == -1) {
            $total_rows = syslog_db_fetch_cell("SELECT count(*) FROM `" . $syslogdb_default . "`.`syslog` " . $sql_where);
        } else {
            $total_rows = syslog_db_fetch_cell("SELECT count(*) FROM `" . $syslogdb_default . "`.`syslog_removed` " . $sql_where);
        }
    } else {
        $total_rows = syslog_db_fetch_cell("SELECT count(*)\n\t\t\t\t\t\t\t\t\tFROM `" . $syslogdb_default . "`.`syslog_logs` AS sl\n\t\t\t\t\t\t\t\t\tLEFT JOIN `" . $syslogdb_default . "`.`syslog_facilities` AS sf\n\t\t\t\t\t\t\t\t\tON sl.facility=sf.facility\n\t\t\t\t\t\t\t\t\tLEFT JOIN `" . $syslogdb_default . "`.`syslog_priorities` AS sp\n\t\t\t\t\t\t\t\t\tON sl.priority=sp.priority\n\t\t\t\t\t\t\t\t\tLEFT JOIN `" . $syslogdb_default . "`.`syslog_hosts` AS sh\n\t\t\t\t\t\t\t\t\tON sl.host=sh.host\n\t\t\t\t\t\t\t\t\tLEFT JOIN `" . $syslogdb_default . "`.`syslog_alert` AS sa\n\t\t\t\t\t\t\t\t\tON sl.alert_id=sa.id " . $sql_where);
    }
    html_start_box("", "100%", $colors["header"], "3", "center", "");
    $hostarray = "";
    if (is_array($_REQUEST["host"])) {
        foreach ($_REQUEST["host"] as $h) {
            $hostarray .= "host[]={$h}&";
        }
    } else {
        $hostarray .= "host[]=" . $_REQUEST["host"] . "&";
    }
    return $total_rows;
}
Ejemplo n.º 12
0
		utilities_clear_user_log();
		utilities_view_user_log();

		include_once(CACTI_BASE_PATH . "/include/bottom_footer.php");
		break;
	case 'view_tech':
		include_once(CACTI_BASE_PATH . "/include/top_header.php");

		utilities_view_tech();

		include_once(CACTI_BASE_PATH . "/include/bottom_footer.php");
		break;
	default:

		if (!api_plugin_hook_function('utilities_action', get_request_var_request('action'))) {
			include_once(CACTI_BASE_PATH . "/include/top_header.php");

			utilities();

			include_once(CACTI_BASE_PATH . "/include/bottom_footer.php");
		}
		break;
}

/* -----------------------
    Utilities Functions
   ----------------------- */

function utilities_php_modules() {
	/*
Ejemplo n.º 13
0
function process_poller_output(&$rrdtool_pipe, $remainder = FALSE)
{
    global $config, $debug;
    include_once $config["library_path"] . "/rrd.php";
    /* let's count the number of rrd files we processed */
    $rrds_processed = 0;
    if ($remainder) {
        $limit = "";
    } else {
        $limit = "LIMIT 10000";
    }
    /* create/update the rrd files */
    $results = db_fetch_assoc("select\n\t\tpoller_output.output,\n\t\tpoller_output.time,\n\t\tUNIX_TIMESTAMP(poller_output.time) as unix_time,\n\t\tpoller_output.local_data_id,\n\t\tpoller_item.rrd_path,\n\t\tpoller_item.rrd_name,\n\t\tpoller_item.rrd_num\n\t\tfrom (poller_output,poller_item)\n\t\twhere (poller_output.local_data_id=poller_item.local_data_id and poller_output.rrd_name=poller_item.rrd_name)\n\t\torder by poller_output.local_data_id\n\t\t{$limit}");
    if (sizeof($results) > 0) {
        /* create an array keyed off of each .rrd file */
        foreach ($results as $item) {
            /* trim the default characters, but add single and double quotes */
            $value = trim($item["output"], " \r\n\t\v\"'");
            $unix_time = $item["unix_time"];
            $rrd_update_array[$item["rrd_path"]]["local_data_id"] = $item["local_data_id"];
            /* single one value output */
            if (is_numeric($value) || $value == "U") {
                $rrd_update_array[$item["rrd_path"]]["times"][$unix_time][$item["rrd_name"]] = $value;
                /* special case of one value output: hexadecimal to decimal conversion */
            } elseif (is_hexadecimal($value)) {
                /* attempt to accomodate 32bit and 64bit systems */
                $value = str_replace(' ', '', $value);
                if (strlen($value) <= 8 || 2147483647 + 1 == intval(2147483647 + 1)) {
                    $rrd_update_array[$item["rrd_path"]]["times"][$unix_time][$item["rrd_name"]] = hexdec($value);
                } elseif (function_exists("bcpow")) {
                    $dec = 0;
                    $vallen = strlen($value);
                    for ($i = 1; $i <= $vallen; $i++) {
                        $dec = bcadd($dec, bcmul(strval(hexdec($value[$i - 1])), bcpow('16', strval($vallen - $i))));
                    }
                    $rrd_update_array[$item["rrd_path"]]["times"][$unix_time][$item["rrd_name"]] = $dec;
                } else {
                    $rrd_update_array[$item["rrd_path"]]["times"][$unix_time][$item["rrd_name"]] = "U";
                }
                /* multiple value output */
            } else {
                $values = explode(" ", $value);
                $rrd_field_names = array_rekey(db_fetch_assoc("select\n\t\t\t\t\tdata_template_rrd.data_source_name,\n\t\t\t\t\tdata_input_fields.data_name\n\t\t\t\t\tfrom (data_template_rrd,data_input_fields)\n\t\t\t\t\twhere data_template_rrd.data_input_field_id=data_input_fields.id\n\t\t\t\t\tand data_template_rrd.local_data_id=" . $item["local_data_id"]), "data_name", "data_source_name");
                if (sizeof($values)) {
                    foreach ($values as $value) {
                        $matches = explode(":", $value);
                        if (sizeof($matches) == 2) {
                            if (isset($rrd_field_names[$matches[0]])) {
                                if (read_config_option("log_verbosity") >= POLLER_VERBOSITY_DEBUG || $debug) {
                                    cacti_log("Parsed MULTI output field '" . $matches[0] . ":" . $matches[1] . "' [map " . $matches[0] . "->" . $rrd_field_names[$matches[0]] . "]", true, "POLLER");
                                }
                                $rrd_update_array[$item["rrd_path"]]["times"][$unix_time][$rrd_field_names[$matches[0]]] = $matches[1];
                            }
                        }
                    }
                }
            }
            /* fallback values */
            if (!isset($rrd_update_array[$item["rrd_path"]]["times"][$unix_time]) && $item["rrd_name"] != "") {
                $rrd_update_array[$item["rrd_path"]]["times"][$unix_time][$item["rrd_name"]] = "U";
            } else {
                if (!isset($rrd_update_array[$item["rrd_path"]]["times"][$unix_time]) && $item["rrd_name"] == "") {
                    unset($rrd_update_array[$item["rrd_path"]]);
                }
            }
        }
        /* make sure each .rrd file has complete data */
        reset($results);
        $k = 0;
        $data_ids = array();
        foreach ($results as $item) {
            $unix_time = $item["unix_time"];
            if (isset($rrd_update_array[$item["rrd_path"]]["times"][$unix_time])) {
                if ($item["rrd_num"] <= sizeof($rrd_update_array[$item["rrd_path"]]["times"][$unix_time])) {
                    $data_ids[] = $item["local_data_id"];
                    $k++;
                    if ($k % 10000 == 0) {
                        db_execute("DELETE FROM poller_output WHERE local_data_id IN (" . implode(",", $data_ids) . ")");
                        $k = 0;
                        $data_ids = array();
                    }
                } else {
                    unset($rrd_update_array[$item["rrd_path"]]["times"][$unix_time]);
                }
            }
        }
        if ($k > 0) {
            db_execute("DELETE FROM poller_output WHERE local_data_id IN (" . implode(",", $data_ids) . ")");
        }
        api_plugin_hook_function('poller_output', $rrd_update_array);
        if (api_plugin_hook_function('poller_on_demand', $results)) {
            $rrds_processed = rrdtool_function_update($rrd_update_array, $rrdtool_pipe);
        }
    }
    return $rrds_processed;
}
Ejemplo n.º 14
0
function grow_right_pane_tree($tree_id, $leaf_id, $host_group_data)
{
    global $current_user, $config, $graphs_per_page, $graph_timeshifts;
    include $config['include_path'] . '/global_arrays.php';
    include_once $config['library_path'] . '/data_query.php';
    include_once $config['library_path'] . '/html_utility.php';
    if (empty($tree_id)) {
        return;
    }
    if (empty($leaf_id)) {
        $leaf_id = 0;
    }
    $sql_where = '';
    $sql_join = '';
    $title = '';
    $title_delimeter = '';
    $leaf = db_fetch_row("SELECT title, host_id, host_grouping_type\n\t\tFROM graph_tree_items\n\t\tWHERE id={$leaf_id}");
    $leaf_type = api_tree_get_item_type($leaf_id);
    /* get information for the headers */
    if (!empty($tree_id)) {
        $tree_name = db_fetch_cell("SELECT name FROM graph_tree WHERE id={$tree_id}");
    }
    if (!empty($leaf_id)) {
        $leaf_name = $leaf['title'];
    }
    if (!empty($leaf_id)) {
        $host_name = db_fetch_cell("SELECT host.description FROM (graph_tree_items,host) WHERE graph_tree_items.host_id=host.id AND graph_tree_items.id={$leaf_id}");
    }
    $host_group_data_array = explode(':', $host_group_data);
    if ($host_group_data_array[0] == 'graph_template') {
        $host_group_data_name = '<strong>Graph Template:</strong> ' . db_fetch_cell('select name from graph_templates where id=' . $host_group_data_array[1]);
        $graph_template_id = $host_group_data_array[1];
    } elseif ($host_group_data_array[0] == 'data_query') {
        $host_group_data_name = '<strong>Graph Template:</strong> ' . (empty($host_group_data_array[1]) ? 'Non Query Based' : db_fetch_cell('select name from snmp_query where id=' . $host_group_data_array[1]));
        $data_query_id = $host_group_data_array[1];
    } elseif ($host_group_data_array[0] == 'data_query_index') {
        $host_group_data_name = '<strong>Graph Template:</strong> ' . (empty($host_group_data_array[1]) ? 'Non Query Based' : db_fetch_cell('select name from snmp_query where id=' . $host_group_data_array[1])) . '-> ' . (empty($host_group_data_array[2]) ? 'Template Based' : get_formatted_data_query_index($leaf['host_id'], $host_group_data_array[1], $host_group_data_array[2]));
        $data_query_id = $host_group_data_array[1];
        $data_query_index = $host_group_data_array[2];
    }
    if (!empty($tree_name)) {
        $title .= $title_delimeter . '<strong>Tree:</strong>' . htmlspecialchars($tree_name);
        $title_delimeter = '-> ';
    }
    if (!empty($leaf_name)) {
        $title .= $title_delimeter . '<strong>Leaf:</strong>' . htmlspecialchars($leaf_name);
        $title_delimeter = '-> ';
    }
    if (!empty($host_name)) {
        $title .= $title_delimeter . '<strong>Device:</strong>' . htmlspecialchars($host_name);
        $title_delimeter = '-> ';
    }
    if (!empty($host_group_data_name)) {
        $title .= $title_delimeter . " {$host_group_data_name}";
        $title_delimeter = '-> ';
    }
    validate_tree_vars($tree_id, $leaf_id, $host_group_data);
    html_start_box('<strong>Graph Filters</strong>' . (strlen(get_request_var_request('filter')) ? " [ Filter '" . htmlspecialchars(get_request_var_request('filter')) . "' Applied ]" : ''), '100%', "", '3', 'center', '');
    /* include time span selector */
    if (read_graph_config_option('timespan_sel') == 'on') {
        ?>
		<tr class='even noprint'>
			<td class='noprint'>
			<form name='form_timespan_selector' method='post' action='graph_view.php'>
				<table cellpadding='2' cellspacing='0'>
					<tr id='timespan'>
						<td width='50'>
							Presets
						</td>
						<td>
							<select id='predefined_timespan' name='predefined_timespan' onChange='spanTime()'>
								<?php 
        if (isset($_SESSION['custom'])) {
            $graph_timespans[GT_CUSTOM] = 'Custom';
            $start_val = 0;
            $end_val = sizeof($graph_timespans);
        } else {
            if (isset($graph_timespans[GT_CUSTOM])) {
                asort($graph_timespans);
                array_shift($graph_timespans);
            }
            $start_val = 1;
            $end_val = sizeof($graph_timespans) + 1;
        }
        if (sizeof($graph_timespans) > 0) {
            for ($value = $start_val; $value < $end_val; $value++) {
                print "<option value='{$value}'";
                if ($_SESSION['sess_current_timespan'] == $value) {
                    print ' selected';
                }
                print '>' . title_trim($graph_timespans[$value], 40) . "</option>\n";
            }
        }
        ?>
							</select>
						</td>
						<td>
							From
						</td>
						<td>
							<input type='text' name='date1' id='date1' title='Graph Begin Timestamp' size='15' value='<?php 
        print isset($_SESSION['sess_current_date1']) ? $_SESSION['sess_current_date1'] : '';
        ?>
'>
						</td>
						<td>
							<input type='image' src='images/calendar.gif' align='middle' alt='Start date selector' title='Start date selector' onclick="return showCalendar('date1');">
						</td>
						<td>
							To
						</td>
						<td>
							<input type='text' name='date2' id='date2' title='Graph End Timestamp' size='15' value='<?php 
        print isset($_SESSION['sess_current_date2']) ? $_SESSION['sess_current_date2'] : '';
        ?>
'>
						</td>
						<td>
							<input type='image' src='images/calendar.gif' align='middle' alt='End date selector' title='End date selector' onclick="return showCalendar('date2');">
						</td>
						<td>
							<img style='padding-bottom:0px;cursor:pointer;' border='0' src='images/move_left.gif' align='middle' alt='' title='Shift Left' onClick='timeshiftFilterLeft()'/>
						</td>
						<td>
							<select id='predefined_timeshift' name='predefined_timeshift' title='Define Shifting Interval'>
								<?php 
        $start_val = 1;
        $end_val = sizeof($graph_timeshifts) + 1;
        if (sizeof($graph_timeshifts) > 0) {
            for ($shift_value = $start_val; $shift_value < $end_val; $shift_value++) {
                print "<option value='{$shift_value}'";
                if ($_SESSION['sess_current_timeshift'] == $shift_value) {
                    print ' selected';
                }
                print '>' . title_trim($graph_timeshifts[$shift_value], 40) . "</option>\n";
            }
        }
        ?>
							</select>
						</td>
						<td>
							<img style='padding-bottom:0px;cursor:pointer;' name='move_right' src='images/move_right.gif' align='middle' alt='' title='Shift Right' onClick='timeshiftFilterRight()'/>
						</td>
						<td>
							<input type='button' name='button_refresh_x' value='Refresh' title='Refresh selected time span' onClick='refreshTimespanFilter()'>
						</td>
						<td>
							<input type='button' name='button_clear_x' value='Clear' title='Return to the default time span' onClick='clearTimespanFilter()'>
						</td>
					</tr>
					<tr id='realtime' style='display:none;'>
						<td width='50'> 
							Window
						</td>
						<td>
							<select name='graph_start' id='graph_start' onChange='self.imageOptionsChanged("timespan")'>
								<?php 
        foreach ($realtime_window as $interval => $text) {
            printf('<option value="%d"%s>%s</option>', $interval, $interval == $_SESSION['sess_realtime_window'] ? ' selected="selected"' : '', $text);
        }
        ?>
							</select>
						</td>
						<td>
							Refresh
						</td>
						<td>
							<select name='ds_step' id='ds_step' onChange="self.imageOptionsChanged('interval')">
								<?php 
        foreach ($realtime_refresh as $interval => $text) {
            printf('<option value="%d"%s>%s</option>', $interval, $interval == $_SESSION['sess_realtime_dsstep'] ? ' selected="selected"' : '', $text);
        }
        ?>
							</select>
						</td>
						<td>
							<input type='button' id='realtimeoff' value='Stop'>
						</td>
						<td align='center' colspan='6'>
							<span id='countdown'></span>
						</td>
					</tr>
				</table>
			</form>
			</td>
		</tr>
		<?php 
    }
    ?>
	<tr class='even noprint' id='search'>
		<td class='noprint'>
		<form name='form_graph_view' method='post' onSubmit='changeFilter();return false'>
			<table cellpadding='2' cellspacing='0'>
				<tr>
					<td width='50'>
						Search
					</td>
					<td>
						<input id='filter' size='30' name='filter' value='<?php 
    print htmlspecialchars(get_request_var_request('filter'));
    ?>
'>
					</td>
					<td>
						Graphs
					</td>
					<td>
						<select name='graphs' id='graphs' onChange='changeFilter()'>
							<?php 
    if (sizeof($graphs_per_page) > 0) {
        foreach ($graphs_per_page as $key => $value) {
            print "<option value='" . $key . "'";
            if (get_request_var_request('graphs') == $key) {
                print ' selected';
            }
            print '>' . $value . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
					<td>
						Columns
					</td>
					<td>
						<select name='columns' id='columns' onChange='changeFilter()' <?php 
    print get_request_var_request('thumbnails') == 'false' ? 'disabled' : '';
    ?>
>
							<?php 
    if (get_request_var_request('thumbnails') == 'false') {
        ?>
							<option value='<?php 
        print get_request_var_request('columns');
        ?>
' selected>N/A</option>
							<?php 
    } else {
        ?>
							<option value='1' <?php 
        print get_request_var_request('columns') == '1' ? ' selected' : '';
        ?>
>1 Column</option>
							<option value='2' <?php 
        print get_request_var_request('columns') == '2' ? ' selected' : '';
        ?>
>2 Columns</option>
							<option value='3' <?php 
        print get_request_var_request('columns') == '3' ? ' selected' : '';
        ?>
>3 Columns</option>
							<option value='4' <?php 
        print get_request_var_request('columns') == '4' ? ' selected' : '';
        ?>
>4 Columns</option>
							<option value='5' <?php 
        print get_request_var_request('columns') == '5' ? ' selected' : '';
        ?>
>5 Columns</option>
							<?php 
    }
    ?>
						</select>
					</td>
					<td>
						<label for='thumbnails'>Thumbnails:</label>
					</td>
					<td>
						<input id='thumbnails' type='checkbox' name='thumbnails' onClick='changeFilter()' <?php 
    print $_REQUEST['thumbnails'] == 'true' ? 'checked' : '';
    ?>
>
					</td>
					<td>
						<input type='button' value='Go' title='Set/Refresh Filter' onClick='changeFilter()'>
					</td>
					<td>
						<input type='button' value='Clear' title='Clear Filters' onClick='clearFilter()'>
					</td>
				</tr>
			</table>
		</form>
		</td>
	</tr>
	<script type='text/javascript'>

	$(function() {
		var navBar = "<div id='navBar' class='navBar'><?php 
    print draw_navigation_text();
    ?>
</div>";
		if (navBar != '') {
			$('#navBar').replaceWith(navBar);
		}
		setupBreadcrumbs();
	});

	function changeFilter() {
		$.get('graph_view.php?action=tree_content&tree_id=<?php 
    print $_SESSION['sess_graph_tree_tree_id'];
    ?>
&leaf_id=<?php 
    print $_SESSION['sess_graph_tree_leaf_id'];
    ?>
&host_group_data=<?php 
    print $_SESSION['sess_graph_tree_host_group_data'];
    ?>
&graphs='+$('#graphs').val()+'&filter='+$('#filter').val()+'&thumbnails='+$('#thumbnails').is(':checked')+'&columns='+$('#columns').val()+'&nodeid='+'<?php 
    print $_SESSION['sess_graph_tree_nodeid'];
    ?>
', function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

	function clearFilter() {
		$.get('graph_view.php?action=tree_content&tree_id=<?php 
    print $_SESSION['sess_graph_tree_tree_id'];
    ?>
&leaf_id=<?php 
    print $_SESSION['sess_graph_tree_leaf_id'];
    ?>
&host_group_data=<?php 
    print $_SESSION['sess_graph_tree_host_group_data'];
    ?>
&clear_x=1&nodeid='+'<?php 
    print $_SESSION['sess_graph_tree_nodeid'];
    ?>
', function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

	function spanTime() {
		$.get('graph_view.php?action=tree_content&tree_id=<?php 
    print $_SESSION['sess_graph_tree_tree_id'];
    ?>
&leaf_id=<?php 
    print $_SESSION['sess_graph_tree_leaf_id'];
    ?>
&host_group_data=<?php 
    print $_SESSION['sess_graph_tree_host_group_data'];
    ?>
&nodeid='+'<?php 
    print $_SESSION['sess_graph_tree_nodeid'];
    ?>
&predefined_timespan='+$('#predefined_timespan').val()+'&predefined_timeshift='+$('#predefined_timeshift').val(), function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

	function clearTimespanFilter() {
		var json = { button_clear_x: 1, date1: $('#date1').val(), date2: $('#date2').val(), predefined_timespan: $('#predefined_timespan').val(), predefined_timeshift: $('#predefined_timeshift').val() };
		var url  = 'graph_view.php?action=tree_content&tree_id=<?php 
    print $_SESSION['sess_graph_tree_tree_id'];
    ?>
&leaf_id=<?php 
    print $_SESSION['sess_graph_tree_leaf_id'];
    ?>
&host_group_data=<?php 
    print $_SESSION['sess_graph_tree_host_group_data'];
    ?>
&nodeid=<?php 
    print $_SESSION['sess_graph_tree_nodeid'];
    ?>
';
		$.post(url, json).done(function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

	function refreshTimespanFilter() {
		var json = { button_refresh_x: 1, date1: $('#date1').val(), date2: $('#date2').val(), predefined_timespan: $('#predefined_timespan').val(), predefined_timeshift: $('#predefined_timeshift').val() };
		var url  = 'graph_view.php?action=tree_content&tree_id=<?php 
    print $_SESSION['sess_graph_tree_tree_id'];
    ?>
&leaf_id=<?php 
    print $_SESSION['sess_graph_tree_leaf_id'];
    ?>
&host_group_data=<?php 
    print $_SESSION['sess_graph_tree_host_group_data'];
    ?>
&nodeid=<?php 
    print $_SESSION['sess_graph_tree_nodeid'];
    ?>
';
		$.post(url, json).done(function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

	function timeshiftFilterLeft() {
		var json = { move_left_x: 1, move_left_y: 1, date1: $('#date1').val(), date2: $('#date2').val(), predefined_timespan: $('#predefined_timespan').val(), predefined_timeshift: $('#predefined_timeshift').val() };
		var url  = 'graph_view.php?action=tree_content&tree_id=<?php 
    print $_SESSION['sess_graph_tree_tree_id'];
    ?>
&leaf_id=<?php 
    print $_SESSION['sess_graph_tree_leaf_id'];
    ?>
&host_group_data=<?php 
    print $_SESSION['sess_graph_tree_host_group_data'];
    ?>
&nodeid=<?php 
    print $_SESSION['sess_graph_tree_nodeid'];
    ?>
';
		$.post(url, json).done(function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

	function timeshiftFilterRight() {
		var json = { move_right_x: 1, move_right_y: 1, date1: $('#date1').val(), date2: $('#date2').val(), predefined_timespan: $('#predefined_timespan').val(), predefined_timeshift: $('#predefined_timeshift').val() };
		var url  = 'graph_view.php?action=tree_content&tree_id=<?php 
    print $_SESSION['sess_graph_tree_tree_id'];
    ?>
&leaf_id=<?php 
    print $_SESSION['sess_graph_tree_leaf_id'];
    ?>
&host_group_data=<?php 
    print $_SESSION['sess_graph_tree_host_group_data'];
    ?>
&nodeid=<?php 
    print $_SESSION['sess_graph_tree_nodeid'];
    ?>
';
		$.post(url, json).done(function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

	function url_graph(strNavURL) {
		return '';
	}

	</script>
	<?php 
    html_end_box();
    api_plugin_hook_function('graph_tree_page_buttons', array('treeid' => $tree_id, 'leafid' => $leaf_id, 'mode' => 'tree', 'timespan' => $_SESSION['sess_current_timespan'], 'starttime' => get_current_graph_start(), 'endtime' => get_current_graph_end()));
    html_start_box('', '100%', "", '3', 'center', '');
    $graph_list = array();
    /* if the number of rows is -1, set it to the default */
    if ($_REQUEST['graphs'] == -1) {
        $_REQUEST['graphs'] = read_graph_config_option('treeview_graphs_per_page');
    }
    if ($leaf_type == 'header' || empty($leaf_id)) {
        $sql_where = '';
        if (strlen(get_request_var_request('filter'))) {
            $sql_where = " (gtg.title_cache LIKE '%" . get_request_var_request('filter') . "%' OR gtg.title LIKE '%" . get_request_var_request('filter') . "%')";
        }
        $graph_list = get_allowed_tree_header_graphs($tree_id, $leaf_id, $sql_where);
    } elseif ($leaf_type == 'host') {
        /* graph template grouping */
        if ($leaf['host_grouping_type'] == HOST_GROUPING_GRAPH_TEMPLATE) {
            $sql_where = 'gl.host_id=' . $leaf['host_id'] . (empty($graph_template_id) ? '' : ' AND gt.id=' . $graph_template_id);
            $graph_templates = get_allowed_graph_templates($sql_where);
            /* for graphs without a template */
            array_push($graph_templates, array('id' => '0', 'name' => '(No Graph Template)'));
            if (sizeof($graph_templates) > 0) {
                foreach ($graph_templates as $graph_template) {
                    $sql_where = '';
                    if (strlen(get_request_var_request('filter'))) {
                        $sql_where = " (gtg.title_cache LIKE '%" . get_request_var_request('filter') . "%')";
                    }
                    $sql_where .= (strlen($sql_where) ? 'AND' : '') . ' gl.graph_template_id=' . $graph_template['id'] . ' AND gl.host_id=' . $leaf['host_id'];
                    $graphs = get_allowed_graphs($sql_where);
                    /* let's sort the graphs naturally */
                    usort($graphs, 'naturally_sort_graphs');
                    if (sizeof($graphs)) {
                        foreach ($graphs as $graph) {
                            $graph['graph_template_name'] = $graph_template['name'];
                            array_push($graph_list, $graph);
                        }
                    }
                }
            }
            /* data query index grouping */
        } elseif ($leaf['host_grouping_type'] == HOST_GROUPING_DATA_QUERY_INDEX) {
            $data_queries = db_fetch_assoc("SELECT sq.id, sq.name\n\t\t\t\tFROM graph_local AS gl\n\t\t\t\tINNER JOIN snmp_query AS sq\n\t\t\t\tON gl.snmp_query_id=sq.id\n\t\t\t\tWHERE gl.host_id=" . $leaf['host_id'] . "\n\t\t\t\t" . (!isset($data_query_id) ? '' : "AND sq.id={$data_query_id}") . "\n\t\t\t\tGROUP BY sq.id\n\t\t\t\tORDER BY sq.name");
            /* for graphs without a data query */
            if (empty($data_query_id)) {
                array_push($data_queries, array('id' => '0', 'name' => 'Non Query Based'));
            }
            if (sizeof($data_queries) > 0) {
                foreach ($data_queries as $data_query) {
                    $sql_where = '';
                    /* fetch a list of field names that are sorted by the preferred sort field */
                    $sort_field_data = get_formatted_data_query_indexes($leaf['host_id'], $data_query['id']);
                    if (strlen(get_request_var_request('filter'))) {
                        $sql_where = " (gtg.title_cache LIKE '%" . get_request_var_request('filter') . "%')";
                    }
                    /* grab a list of all graphs for this host/data query combination */
                    $sql_where .= (strlen($sql_where) ? ' AND ' : '') . ' gl.snmp_query_id=' . $data_query['id'] . ' AND gl.host_id=' . $leaf['host_id'] . "\n                                        " . (empty($data_query_index) ? '' : " AND gl.snmp_index='{$data_query_index}'");
                    $graphs = get_allowed_graphs($sql_where);
                    /* re-key the results on data query index */
                    $snmp_index_to_graph = array();
                    if (sizeof($graphs) > 0) {
                        /* let's sort the graphs naturally */
                        usort($graphs, 'naturally_sort_graphs');
                        foreach ($graphs as $graph) {
                            $snmp_index_to_graph[$graph['snmp_index']][$graph['local_graph_id']] = $graph['title_cache'];
                            $graphs_height[$graph['local_graph_id']] = $graph['height'];
                            $graphs_width[$graph['local_graph_id']] = $graph['width'];
                        }
                    }
                    /* using the sorted data as they key; grab each snmp index from the master list */
                    while (list($snmp_index, $sort_field_value) = each($sort_field_data)) {
                        /* render each graph for the current data query index */
                        if (isset($snmp_index_to_graph[$snmp_index])) {
                            while (list($local_graph_id, $graph_title) = each($snmp_index_to_graph[$snmp_index])) {
                                /* reformat the array so it's compatable with the html_graph* area functions */
                                array_push($graph_list, array('data_query_name' => $data_query['name'], 'sort_field_value' => $sort_field_value, 'local_graph_id' => $local_graph_id, 'title_cache' => $graph_title, 'height' => $graphs_height[$graph['local_graph_id']], 'width' => $graphs_width[$graph['local_graph_id']]));
                            }
                        }
                    }
                }
            }
        }
    }
    $total_rows = sizeof($graph_list);
    /* generate page list */
    $nav = html_nav_bar("graph_view.php?action=tree_content&tree_id={$tree_id}&leaf_id={$leaf_id}&nodeid=" . get_request_var_request('nodeid') . '&host_group_data=' . get_request_var_request('host_group_data'), MAX_DISPLAY_PAGES, get_request_var_request('page'), get_request_var_request('graphs'), $total_rows, 5, 'Graphs', 'page', 'main');
    print $nav;
    /* start graph display */
    print "<tr class='tableHeader'><td width='390' colspan='11' class='graphSubHeaderColumn textHeaderDark'>{$title}</td></tr>";
    $i = get_request_var_request('graphs') * (get_request_var_request('page') - 1);
    $last_graph = $i + get_request_var_request('graphs');
    $new_graph_list = array();
    while ($i < $total_rows && $i < $last_graph) {
        $new_graph_list[] = $graph_list[$i];
        $i++;
    }
    if ($_REQUEST['thumbnails'] == 'true') {
        html_graph_thumbnail_area($new_graph_list, '', 'view_type=tree&graph_start=' . get_current_graph_start() . '&graph_end=' . get_current_graph_end(), '', get_request_var_request('columns'));
    } else {
        html_graph_area($new_graph_list, '', 'view_type=tree&graph_start=' . get_current_graph_start() . '&graph_end=' . get_current_graph_end(), '', 1);
    }
    if (!empty($leaf_id)) {
        api_plugin_hook_function('tree_after', $host_name . ',' . get_request_var_request('leaf_id'));
    }
    api_plugin_hook_function('tree_view_page_end');
    if ($total_rows > 0) {
        print $nav;
    }
    html_end_box();
}
Ejemplo n.º 15
0
			$extra_args     = "-q \"" . CACTI_BASE_PATH . "/cmd.php\"";
			$method         = "cmd.php";
			$total_procs    = $concurrent_processes;
		}else{
			$command_string = read_config_option("path_php_binary");
			$extra_args     = "-q \"" . strtolower(CACTI_BASE_PATH . "/cmd.php\"");
			$method         = "cmd.php";
			$total_procs    = $concurrent_processes;
		}

		/* add the poller id for the various collectors */
		if ($poller_id > 0) {
			$extra_args .= " --poller=$poller_id";
		}

		$extra_args = api_plugin_hook_function ('poller_command_args', $extra_args);

		/* Populate each execution file with appropriate information */
		foreach ($polling_devices as $item) {
			if ($device_count == 1) {
				$first_device = $item["id"];
			}

			if ($process_leveling != CHECKED) {
				if ($device_count == $devices_per_process) {
					$last_device    = $item["id"];
					$change_proc  = true;
				}
			}else{
				if (isset($items_perdevice[$item["id"]])) {
					$items_launched += $items_perdevice[$item["id"]];
Ejemplo n.º 16
0
function user_edit() {
	global $colors, $fields_user_user_edit_device;

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

	if (!empty($_GET["id"])) {
		$user = db_fetch_row("SELECT * FROM user_auth WHERE id = " . get_request_var("id"));
		$header_label = __("[edit: ") . $user["username"] . "]";
	}else{
		$header_label = __("[new]");
	}

	api_plugin_hook_function('user_admin_edit', (isset($user) ? get_request_var("id") : 0));

	$user_tabs = array(
		"user_edit" => array("name" => __("General Settings"), "title" => __("General Settings are common settings for all users.")),
		"user_realms_edit" => array("name" => __("Realm Permissions"), "title" => __("Realm permissions control which sections of Cacti this user will have access to.")),
		"graph_perms_edit" => array("name" => __("Graph Permissions"), "title" => __("Graph policies will be evaluated in the order shown until a match is found.")),
		"graph_settings_edit" => array("name" => __("Graph Settings"), "title" => __("Graph settings control how graphs are displayed for this user.")));

	/* draw the categories tabs on the top of the page */
	/* set the default settings category */
	if (!isset($_GET["action"])) {
		/* there is no selected tab; select the first one */
		$current_tab = array_keys($user_tabs);
		$current_tab = $current_tab[0];
	}else{
		$current_tab = $_GET["action"];
	}

	print "<table width='100%' cellspacing='0' cellpadding='0' align='center'><tr>";
	print "<td><div class='tabs'>";

	if (sizeof($user_tabs)) {
	foreach (array_keys($user_tabs) as $tab_short_name) {
		print "<div title='" . $user_tabs[$tab_short_name]["title"] . "' class='tabDefault'><a " . (($tab_short_name == $current_tab) ? "class='tabSelected'" : "class='tabDefault'") . " href='" . htmlspecialchars("user_admin.php?action=shift&action=" . $tab_short_name . "&id=" . get_request_var("id")) . "'>" . $user_tabs[$tab_short_name]["name"] . "</a></div>";

		if (empty($_GET["id"])) break;
	}
	}

	print "</div></td></tr></table>\n";

	print "<form method='post' action='" .  basename($_SERVER["PHP_SELF"]) . "' name='user_edit'>\n";
	if (get_request_var("action") == "user_edit") {
		html_start_box("<strong>" . __("General Settings") . "</strong>", "100", $colors["header"], 0, "center");
		$header_items = array(__("Field"), __("Value"));
		print "<tr><td>";
		html_header($header_items, 2, true, 'settings_general');

		draw_edit_form(array(
			"config" => array("form_name" => "chk"),
			"fields" => inject_form_variables($fields_user_user_edit_device, (isset($user) ? $user : array()))
		));
		print "</table></td></tr>";		/* end of html_header */
		html_end_box();
	}else{
#		print "<span style='display:none;'>";
#
#		html_start_box("", "100%", $colors["header"], "3", "center");
#		draw_edit_form(array(
#			"config" => array("form_name" => "chk"),
#			"fields" => inject_form_variables($fields_user_user_edit_device, (isset($user) ? $user : array()))
#		));
#		html_end_box();
#
#		print "</span>";

		if (get_request_var("action") == "graph_settings_edit") {
			graph_settings_edit();
		}elseif (get_request_var("action") == "user_realms_edit") {
			user_realms_edit();
		}elseif (get_request_var("action") == "graph_perms_edit") {
			graph_perms_edit();
		}else{
			if (!api_plugin_hook_function('user_admin_run_action', get_request_var_request("action"))) {
				user_realms_edit();
			}
		}
	}
	form_save_button_alt("return!user_admin.php");
}
Ejemplo n.º 17
0
/** api_device_save - save a device to the database
 *
 * @param int $id
 * @param int $site_id
 * @param int $poller_id
 * @param int $device_template_id
 * @param string $description
 * @param string $hostname
 * @param string $snmp_community
 * @param int $snmp_version
 * @param string $snmp_username
 * @param string $snmp_password
 * @param int $snmp_port
 * @param int $snmp_timeout
 * @param string $disabled
 * @param int $availability_method
 * @param int $ping_method
 * @param int $ping_port
 * @param int $ping_timeout
 * @param int $ping_retries
 * @param string $notes
 * @param string $snmp_auth_protocol
 * @param string $snmp_priv_passphrase
 * @param string $snmp_priv_protocol
 * @param string $snmp_context
 * @param int $max_oids
 * @param int $device_threads
 * @param string $template_enabled
 * @return unknown_type
 */
function api_device_save($id, $site_id, $poller_id, $device_template_id, $description, $hostname, $snmp_community, $snmp_version,
	$snmp_username, $snmp_password, $snmp_port, $snmp_timeout, $disabled,
	$availability_method, $ping_method, $ping_port, $ping_timeout, $ping_retries,
	$notes, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $max_oids, $device_threads, $template_enabled) {

	/* fetch some cache variables */
	if (empty($id)) {
		$_device_template_id = 0;
	}else{
		$_device_template_id = db_fetch_cell("select device_template_id from device where id=$id");
	}

	$save["id"] = $id;
	$save["site_id"]          = form_input_validate($site_id, "site_id", "^[0-9]+$", false, 3);
	$save["poller_id"]        = form_input_validate($poller_id, "poller_id", "^[0-9]+$", false, 3);
	$save["device_template_id"] = form_input_validate($device_template_id, "device_template_id", "^[0-9]+$", false, 3);
	$save["description"]      = form_input_validate($description, "description", "", false, 3);
	$save["hostname"]         = form_input_validate(trim($hostname), "hostname", "", false, 3);
	$save["notes"]            = form_input_validate($notes, "notes", "", true, 3);
	$save["disabled"]         = form_input_validate($disabled, "disabled", "", true, 3);
	$save["template_enabled"] = form_input_validate($template_enabled, "template_enabled", "", true, 3);

	$save["snmp_version"]     = form_input_validate($snmp_version, "snmp_version", "", true, 3);
	$save["snmp_community"]   = form_input_validate($snmp_community, "snmp_community", "", true, 3);

	if ($save["snmp_version"] == 3) {
		$save["snmp_username"]        = form_input_validate($snmp_username, "snmp_username", "", true, 3);
		$save["snmp_password"]        = form_input_validate($snmp_password, "snmp_password", "", true, 3);
		$save["snmp_auth_protocol"]   = form_input_validate($snmp_auth_protocol, "snmp_auth_protocol", "", true, 3);
		$save["snmp_priv_passphrase"] = form_input_validate($snmp_priv_passphrase, "snmp_priv_passphrase", "", true, 3);
		$save["snmp_priv_protocol"]   = form_input_validate($snmp_priv_protocol, "snmp_priv_protocol", "", true, 3);
		$save["snmp_context"]         = form_input_validate($snmp_context, "snmp_context", "", true, 3);
	} else {
		$save["snmp_username"]        = "";
		$save["snmp_password"]        = "";
		$save["snmp_auth_protocol"]   = "";
		$save["snmp_priv_passphrase"] = "";
		$save["snmp_priv_protocol"]   = "";
		$save["snmp_context"]         = "";
	}

	$save["snmp_port"]           = form_input_validate($snmp_port, "snmp_port", "^[0-9]+$", false, 3);
	$save["snmp_timeout"]        = form_input_validate($snmp_timeout, "snmp_timeout", "^[0-9]+$", false, 3);

	$save["availability_method"] = form_input_validate($availability_method, "availability_method", "^[0-9]+$", false, 3);
	$save["ping_method"]         = form_input_validate($ping_method, "ping_method", "^[0-9]+$", false, 3);
	$save["ping_port"]           = form_input_validate($ping_port, "ping_port", "^[0-9]+$", true, 3);
	$save["ping_timeout"]        = form_input_validate($ping_timeout, "ping_timeout", "^[0-9]+$", true, 3);
	$save["ping_retries"]        = form_input_validate($ping_retries, "ping_retries", "^[0-9]+$", true, 3);
	$save["max_oids"]            = form_input_validate($max_oids, "max_oids", "^[0-9]+$", true, 3);
	$save["device_threads"]      = form_input_validate($device_threads, "device_threads", "^[0-9]+$", true, 3);

	$save = api_plugin_hook_function('api_device_save', $save);

	$device_id = 0;

	if (!is_error_message()) {
		$device_id = sql_save($save, "device");

		if ($device_id) {
			raise_message(1);

			/* push out relavant fields to data sources using this device */
			push_out_device($device_id, 0);

			/* the device substitution cache is now stale; purge it */
			kill_session_var("sess_device_cache_array");

			/* update title cache for graph and data source */
			update_data_source_title_cache_from_device($device_id);
			update_graph_title_cache_from_device($device_id);
		}else{
			raise_message(2);
		}

		/* recache in case any snmp information was changed */
		if (!empty($id)) { /* a valid device was already existing */
			/* detect SNMP change, if current snmp parameters cannot be found in device table */
			$snmp_changed = ($id != db_fetch_cell("SELECT " .
					"id " .
					"FROM device " .
					"WHERE id=$id " .
					"AND snmp_version='$snmp_version' " .
					"AND snmp_community='$snmp_community' " .
					"AND snmp_username='******' " .
					"AND snmp_password='******' " .
					"AND snmp_auth_protocol='$snmp_auth_protocol' " .
					"AND snmp_priv_passphrase='$snmp_priv_passphrase' " .
					"AND snmp_priv_protocol='$snmp_priv_protocol' " .
					"AND snmp_context='$snmp_context' " .
					"AND snmp_port='$snmp_port' " .
					"AND snmp_timeout='$snmp_timeout' "));

			if ($snmp_changed) {
				/* fecth all existing snmp queries */
				$snmp_queries = db_fetch_assoc("SELECT " .
						"snmp_query_id, " .
						"reindex_method " .
						"FROM device_snmp_query " .
						"WHERE device_id=$id");

				if (sizeof($snmp_queries) > 0) {
					foreach ($snmp_queries as $snmp_query) {
						/* recache all existing snmp queries */
						run_data_query($id, $snmp_query["snmp_query_id"]);
					}
				}
			}
		}

		/* if the user changes the device template, add each snmp query associated with it */
		if (($device_template_id != $_device_template_id) && (!empty($device_template_id))) {
			$snmp_queries = db_fetch_assoc("select snmp_query_id, reindex_method from device_template_snmp_query where device_template_id=$device_template_id");

			if (sizeof($snmp_queries) > 0) {
			foreach ($snmp_queries as $snmp_query) {
				db_execute("replace into device_snmp_query (device_id,snmp_query_id,reindex_method) values ($device_id," . $snmp_query["snmp_query_id"] . "," . $snmp_query["reindex_method"] . ")");

				/* recache snmp data */
				run_data_query($device_id, $snmp_query["snmp_query_id"]);
			}
			}

			$graph_templates = db_fetch_assoc("select graph_template_id from device_template_graph where device_template_id=$device_template_id");

			if (sizeof($graph_templates) > 0) {
			foreach ($graph_templates as $graph_template) {
				db_execute("replace into device_graph (device_id,graph_template_id) values ($device_id," . $graph_template["graph_template_id"] . ")");
				api_plugin_hook_function('add_graph_template_to_device', array("device_id" => $device_id, "graph_template_id" => $graph_template["graph_template_id"]));
			}
			}
		}
	}

	return $device_id;
}
Ejemplo n.º 18
0
 | GNU General Public License for more details.                            |
 +-------------------------------------------------------------------------+
 | Cacti: The Complete RRDTool-based Graphing Solution                     |
 +-------------------------------------------------------------------------+
 | This code is designed, written, and maintained by the Cacti Group. See  |
 | about.php and/or the AUTHORS file for specific developer information.   |
 +-------------------------------------------------------------------------+
 | http://www.cacti.net/                                                   |
 +-------------------------------------------------------------------------+
*/

include_once(CACTI_BASE_PATH . "/lib/time.php");

global $colors, $config, $lang2locale;

$page_title = api_plugin_hook_function('page_title', 'Cacti');

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title><?php echo $page_title; ?></title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	<meta http-equiv="Content-Script-Type" content="text/javascript">
	<meta http-equiv="Content-Style-Type" content="text/css">
	<link type="text/css" href="<?php echo CACTI_URL_PATH; ?>include/main.css" rel="stylesheet">
	<link type="text/css" href="<?php echo CACTI_URL_PATH; ?>include/jquery.autocomplete.css" rel="stylesheet">
	<link type="text/css" href="<?php echo CACTI_URL_PATH; ?>include/dd.css" rel="stylesheet">
	<link type="text/css" media="screen" href="<?php echo CACTI_URL_PATH; ?>include/css/colorpicker.css" rel="stylesheet">
	<link type="text/css" media="screen" href="<?php echo CACTI_URL_PATH; ?>include/css/cacti_dd_menu.css" rel="stylesheet">
	<link href="<?php echo CACTI_URL_PATH; ?>images/favicon.ico" rel="shortcut icon">
Ejemplo n.º 19
0
function ds()
{
    global $ds_actions, $item_rows;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request("ds_rows"));
    input_validate_input_number(get_request_var_request("host_id"));
    input_validate_input_number(get_request_var_request("template_id"));
    input_validate_input_number(get_request_var_request("method_id"));
    input_validate_input_number(get_request_var_request("page"));
    /* ==================================================== */
    /* clean up search string */
    if (isset($_REQUEST["filter"])) {
        $_REQUEST["filter"] = sanitize_search_string(get_request_var("filter"));
    }
    /* clean up sort_column string */
    if (isset($_REQUEST["sort_column"])) {
        $_REQUEST["sort_column"] = sanitize_search_string(get_request_var("sort_column"));
    }
    /* clean up sort_direction string */
    if (isset($_REQUEST["sort_direction"])) {
        $_REQUEST["sort_direction"] = sanitize_search_string(get_request_var("sort_direction"));
    }
    /* if the user pushed the 'clear' button */
    if (isset($_REQUEST["clear_x"])) {
        kill_session_var("sess_ds_current_page");
        kill_session_var("sess_ds_filter");
        kill_session_var("sess_ds_sort_column");
        kill_session_var("sess_ds_sort_direction");
        kill_session_var("sess_ds_rows");
        kill_session_var("sess_ds_host_id");
        kill_session_var("sess_ds_template_id");
        kill_session_var("sess_ds_method_id");
        unset($_REQUEST["page"]);
        unset($_REQUEST["filter"]);
        unset($_REQUEST["sort_column"]);
        unset($_REQUEST["sort_direction"]);
        unset($_REQUEST["ds_rows"]);
        unset($_REQUEST["host_id"]);
        unset($_REQUEST["template_id"]);
        unset($_REQUEST["method_id"]);
    }
    /* remember these search fields in session vars so we don't have to keep passing them around */
    load_current_session_value("page", "sess_ds_current_page", "1");
    load_current_session_value("filter", "sess_ds_filter", "");
    load_current_session_value("sort_column", "sess_ds_sort_column", "name_cache");
    load_current_session_value("sort_direction", "sess_ds_sort_direction", "ASC");
    load_current_session_value("ds_rows", "sess_ds_rows", read_config_option("num_rows_data_source"));
    load_current_session_value("host_id", "sess_ds_host_id", "-1");
    load_current_session_value("template_id", "sess_ds_template_id", "-1");
    load_current_session_value("method_id", "sess_ds_method_id", "-1");
    $host = db_fetch_row("select hostname from host where id=" . get_request_var_request("host_id"));
    /* if the number of rows is -1, set it to the default */
    if (get_request_var_request("ds_rows") == -1) {
        $_REQUEST["ds_rows"] = read_config_option("num_rows_data_source");
    }
    ?>
	<script type="text/javascript">
	<!--

	function applyDSFilterChange(objForm) {
		strURL = '?host_id=' + objForm.host_id.value;
		strURL = strURL + '&filter=' + objForm.filter.value;
		strURL = strURL + '&ds_rows=' + objForm.ds_rows.value;
		strURL = strURL + '&template_id=' + objForm.template_id.value;
		strURL = strURL + '&method_id=' + objForm.method_id.value;
		document.location = strURL;
	}

	-->
	</script>
	<?php 
    html_start_box("<strong>Data Sources</strong> [host: " . (empty($host["hostname"]) ? "No Host" : htmlspecialchars($host["hostname"])) . "]", "100%", "", "3", "center", "data_sources.php?action=ds_edit&host_id=" . get_request_var_request("host_id"));
    ?>
	<tr class='even noprint'>
		<td>
		<form name="form_data_sources" action="data_sources.php">
			<table cellpadding="1" cellspacing="0">
				<tr>
					<td width="50">
						Host:&nbsp;
					</td>
					<td>
						<select name="host_id" onChange="applyDSFilterChange(document.form_data_sources)">
							<option value="-1"<?php 
    if (get_request_var_request("host_id") == "-1") {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
							<option value="0"<?php 
    if (get_request_var_request("host_id") == "0") {
        ?>
 selected<?php 
    }
    ?>
>None</option>
							<?php 
    $hosts = db_fetch_assoc("select id,CONCAT_WS('',description,' (',hostname,')') as name from host order by description,hostname");
    if (sizeof($hosts) > 0) {
        foreach ($hosts as $host) {
            print "<option value='" . $host["id"] . "'";
            if (get_request_var_request("host_id") == $host["id"]) {
                print " selected";
            }
            print ">" . title_trim(htmlspecialchars($host["name"]), 40) . "</option>\n";
        }
    }
    ?>

						</select>
					</td>
					<td width="50">
						&nbsp;Template:&nbsp;
					</td>
					<td width="1">
						<select name="template_id" onChange="applyDSFilterChange(document.form_data_sources)">
							<option value="-1"<?php 
    if (get_request_var_request("template_id") == "-1") {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
							<option value="0"<?php 
    if (get_request_var_request("template_id") == "0") {
        ?>
 selected<?php 
    }
    ?>
>None</option>
							<?php 
    $templates = db_fetch_assoc("SELECT DISTINCT data_template.id, data_template.name\n\t\t\t\t\t\t\t\tFROM data_template\n\t\t\t\t\t\t\t\tINNER JOIN data_template_data\n\t\t\t\t\t\t\t\tON data_template.id=data_template_data.data_template_id\n\t\t\t\t\t\t\t\tWHERE data_template_data.local_data_id>0\n\t\t\t\t\t\t\t\tORDER BY data_template.name");
    if (sizeof($templates) > 0) {
        foreach ($templates as $template) {
            print "<option value='" . $template["id"] . "'";
            if (get_request_var_request("template_id") == $template["id"]) {
                print " selected";
            }
            print ">" . title_trim(htmlspecialchars($template["name"]), 40) . "</option>\n";
        }
    }
    ?>

						</select>
					</td>
					<td nowrap style='white-space: nowrap;'>
						&nbsp;<input type="submit" value="Go" title="Set/Refresh Filters">
						<input type="submit" name="clear_x" value="Clear" title="Clear Filters">
					</td>
				</tr>
				<tr>
					<td width="50">
						Method:&nbsp;
					</td>
					<td width="1">
						<select name="method_id" onChange="applyDSFilterChange(document.form_data_sources)">
							<option value="-1"<?php 
    if (get_request_var_request("method_id") == "-1") {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
							<option value="0"<?php 
    if (get_request_var_request("method_id") == "0") {
        ?>
 selected<?php 
    }
    ?>
>None</option>
							<?php 
    $methods = db_fetch_assoc("SELECT DISTINCT data_input.id, data_input.name\n\t\t\t\t\t\t\t\tFROM data_input\n\t\t\t\t\t\t\t\tINNER JOIN data_template_data\n\t\t\t\t\t\t\t\tON data_input.id=data_template_data.data_input_id\n\t\t\t\t\t\t\t\tWHERE data_template_data.local_data_id>0\n\t\t\t\t\t\t\t\tORDER BY data_input.name");
    if (sizeof($methods) > 0) {
        foreach ($methods as $method) {
            print "<option value='" . $method["id"] . "'";
            if (get_request_var_request("method_id") == $method["id"]) {
                print " selected";
            }
            print ">" . title_trim(htmlspecialchars($method["name"]), 40) . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
					<td nowrap style='white-space: nowrap;' width="50">
						&nbsp;Rows per Page:&nbsp;
					</td>
					<td width="1">
						<select name="ds_rows" onChange="applyDSFilterChange(document.form_data_sources)">
							<option value="-1"<?php 
    if (get_request_var_request("ds_rows") == "-1") {
        ?>
 selected<?php 
    }
    ?>
>Default</option>
							<?php 
    if (sizeof($item_rows) > 0) {
        foreach ($item_rows as $key => $value) {
            print "<option value='" . $key . "'";
            if (get_request_var_request("ds_rows") == $key) {
                print " selected";
            }
            print ">" . htmlspecialchars($value) . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
				</tr>
			</table>
			<table cellpadding="1" cellspacing="0">
				<tr>
					<td width="50">
						Search:&nbsp;
					</td>
					<td width="1">
						<input type="text" name="filter" size="40" value="<?php 
    print htmlspecialchars(get_request_var_request("filter"));
    ?>
">
					</td>
				</tr>
			</table>
			<input type='hidden' name='page' value='1'>
		</form>
		</td>
	</tr>
	<?php 
    html_end_box();
    /* form the 'where' clause for our main sql query */
    if (strlen(get_request_var_request("filter"))) {
        $sql_where1 = "AND (data_template_data.name_cache like '%%" . get_request_var_request("filter") . "%%'" . " OR data_template_data.local_data_id like '%%" . get_request_var_request("filter") . "%%'" . " OR data_template.name like '%%" . get_request_var_request("filter") . "%%'" . " OR data_input.name like '%%" . get_request_var_request("filter") . "%%')";
        $sql_where2 = "AND (data_template_data.name_cache like '%%" . get_request_var_request("filter") . "%%'" . " OR data_template.name like '%%" . get_request_var_request("filter") . "%%')";
    } else {
        $sql_where1 = "";
        $sql_where2 = "";
    }
    if (get_request_var_request("host_id") == "-1") {
        /* Show all items */
    } elseif (get_request_var_request("host_id") == "0") {
        $sql_where1 .= " AND data_local.host_id=0";
        $sql_where2 .= " AND data_local.host_id=0";
    } elseif (!empty($_REQUEST["host_id"])) {
        $sql_where1 .= " AND data_local.host_id=" . get_request_var_request("host_id");
        $sql_where2 .= " AND data_local.host_id=" . get_request_var_request("host_id");
    }
    if (get_request_var_request("template_id") == "-1") {
        /* Show all items */
    } elseif (get_request_var_request("template_id") == "0") {
        $sql_where1 .= " AND data_template_data.data_template_id=0";
        $sql_where2 .= " AND data_template_data.data_template_id=0";
    } elseif (!empty($_REQUEST["host_id"])) {
        $sql_where1 .= " AND data_template_data.data_template_id=" . get_request_var_request("template_id");
        $sql_where2 .= " AND data_template_data.data_template_id=" . get_request_var_request("template_id");
    }
    if (get_request_var_request("method_id") == "-1") {
        /* Show all items */
    } elseif (get_request_var_request("method_id") == "0") {
        $sql_where1 .= " AND data_template_data.data_input_id=0";
        $sql_where2 .= " AND data_template_data.data_input_id=0";
    } elseif (!empty($_REQUEST["method_id"])) {
        $sql_where1 .= " AND data_template_data.data_input_id=" . get_request_var_request("method_id");
        $sql_where2 .= " AND data_template_data.data_input_id=" . get_request_var_request("method_id");
    }
    $total_rows = sizeof(db_fetch_assoc("SELECT\n\t\tdata_local.id\n\t\tFROM (data_local,data_template_data)\n\t\tLEFT JOIN data_input\n\t\tON (data_input.id=data_template_data.data_input_id)\n\t\tLEFT JOIN data_template\n\t\tON (data_local.data_template_id=data_template.id)\n\t\tWHERE data_local.id=data_template_data.local_data_id\n\t\t{$sql_where1}"));
    $poller_intervals = array_rekey(db_fetch_assoc("SELECT data_template_data.local_data_id AS id,\n\t\tMin(data_template_data.rrd_step*rra.steps) AS poller_interval\n\t\tFROM data_template\n\t\tINNER JOIN (data_local\n\t\tINNER JOIN ((data_template_data_rra\n\t\tINNER JOIN data_template_data ON data_template_data_rra.data_template_data_id=data_template_data.id)\n\t\tINNER JOIN rra ON data_template_data_rra.rra_id = rra.id) ON data_local.id = data_template_data.local_data_id) ON data_template.id = data_template_data.data_template_id\n\t\t{$sql_where2}\n\t\tGROUP BY data_template_data.local_data_id"), "id", "poller_interval");
    $data_sources = db_fetch_assoc("SELECT\n\t\tdata_template_data.local_data_id,\n\t\tdata_template_data.name_cache,\n\t\tdata_template_data.active,\n\t\tdata_input.name as data_input_name,\n\t\tdata_template.name as data_template_name,\n\t\tdata_local.host_id\n\t\tFROM (data_local,data_template_data)\n\t\tLEFT JOIN data_input\n\t\tON (data_input.id=data_template_data.data_input_id)\n\t\tLEFT JOIN data_template\n\t\tON (data_local.data_template_id=data_template.id)\n\t\tWHERE data_local.id=data_template_data.local_data_id\n\t\t{$sql_where1}\n\t\tORDER BY " . get_request_var_request("sort_column") . " " . get_request_var_request("sort_direction") . " LIMIT " . get_request_var_request("ds_rows") * (get_request_var_request("page") - 1) . "," . get_request_var_request("ds_rows"));
    print "<form name='chk' method='post' action='data_sources.php'>\n";
    html_start_box("", "100%", "", "3", "center", "");
    $nav = html_nav_bar("data_sources.php?filter=" . get_request_var_request("filter") . "&host_id=" . get_request_var_request("host_id"), MAX_DISPLAY_PAGES, get_request_var_request("page"), get_request_var_request("ds_rows"), $total_rows, 7);
    print $nav;
    $display_text = array("name_cache" => array("Name", "ASC"), "local_data_id" => array("ID", "ASC"), "data_input_name" => array("Data Input Method", "ASC"), "nosort" => array("Poller Interval", "ASC"), "active" => array("Active", "ASC"), "data_template_name" => array("Template Name", "ASC"));
    html_header_sort_checkbox($display_text, get_request_var_request("sort_column"), get_request_var_request("sort_direction"), false);
    $i = 0;
    if (sizeof($data_sources) > 0) {
        foreach ($data_sources as $data_source) {
            $data_source["data_template_name"] = htmlspecialchars($data_source["data_template_name"]);
            $data_name_cache = title_trim(htmlspecialchars($data_source["name_cache"]), read_config_option("max_title_data_source"));
            if (trim(get_request_var_request("filter") != "")) {
                $data_name_cache = preg_replace("/(" . preg_quote(get_request_var_request("filter"), "/") . ")/i", "<span style='background-color: #F8D93D;'>\\1</span>", $data_name_cache);
            }
            /* keep copy of data source for comparison */
            $data_source_orig = $data_source;
            $data_source = api_plugin_hook_function('data_sources_table', $data_source);
            /* we're escaping strings here, so no need to escape them on form_selectable_cell */
            if (empty($data_source["data_template_name"])) {
                $data_template_name = "<em>None</em>";
            } elseif ($data_source_orig["data_template_name"] != $data_source["data_template_name"]) {
                /* was changed by plugin, plugin has to take care for html-escaping */
                $data_template_name = empty($data_source["data_template_name"]) ? "<em>None</em>" : $data_source["data_template_name"];
            } elseif (trim(get_request_var_request("filter") != "")) {
                /* we take care of html-escaping */
                $data_template_name = preg_replace("/(" . preg_quote(get_request_var_request("filter"), "/") . ")/i", "<span style='background-color: #F8D93D;'>\\1</span>", htmlspecialchars($data_source['data_template_name']));
            } else {
                $data_template_name = htmlspecialchars($data_source["data_template_name"]);
            }
            if (empty($data_source["data_input_name"])) {
                $data_input_name = "<em>None</em>";
            } elseif ($data_source_orig["data_input_name"] != $data_source["data_input_name"]) {
                /* was changed by plugin, plugin has to take care for html-escaping */
                $data_input_name = empty($data_source["data_input_name"]) ? "<em>None</em>" : $data_source["data_input_name"];
            } elseif (trim(get_request_var_request("filter") != "")) {
                /* we take care of html-escaping */
                $data_input_name = preg_replace("/(" . preg_quote(get_request_var_request("filter"), "/") . ")/i", "<span style='background-color: #F8D93D;'>\\1</span>", htmlspecialchars($data_source['data_input_name']));
            } else {
                $data_input_name = htmlspecialchars($data_source["data_input_name"]);
            }
            $poller_interval = isset($poller_intervals[$data_source["local_data_id"]]) ? $poller_intervals[$data_source["local_data_id"]] : 0;
            form_alternate_row('line' . $data_source["local_data_id"], true);
            form_selectable_cell("<a class='linkEditMain' href='" . htmlspecialchars("data_sources.php?action=ds_edit&id=" . $data_source["local_data_id"]) . "' title='" . htmlspecialchars($data_source["name_cache"], ENT_QUOTES) . "'>" . (get_request_var_request("filter") != "" ? preg_replace("/(" . preg_quote(get_request_var_request("filter"), "/") . ")/i", "<span style='background-color: #F8D93D;'>\\1</span>", title_trim(htmlspecialchars($data_source["name_cache"]), read_config_option("max_title_data_source"))) : title_trim(htmlspecialchars($data_source["name_cache"]), read_config_option("max_title_data_source"))) . "</a>", $data_source["local_data_id"]);
            form_selectable_cell($data_source['local_data_id'], $data_source['local_data_id']);
            form_selectable_cell($data_input_name, $data_source["local_data_id"]);
            form_selectable_cell(get_poller_interval($poller_interval), $data_source["local_data_id"]);
            form_selectable_cell($data_source['active'] == "on" ? "Yes" : "No", $data_source["local_data_id"]);
            form_selectable_cell($data_template_name, $data_source["local_data_id"]);
            form_checkbox_cell($data_source["name_cache"], $data_source["local_data_id"]);
            form_end_row();
        }
        /* put the nav bar on the bottom as well */
        print $nav;
    } else {
        print "<tr><td><em>No Data Sources</em></td></tr>";
    }
    html_end_box(false);
    /* draw the dropdown containing a list of available actions for this form */
    draw_actions_dropdown($ds_actions);
    print "</form>\n";
}
Ejemplo n.º 20
0
function data_source() {
	global $colors, $item_rows;
	require(CACTI_BASE_PATH . "/include/data_source/data_source_arrays.php");

	/* validate request variables */
	data_source_validate();

	/* if the user pushed the 'clear' button */
	if (isset($_REQUEST["clear_x"])) {
		kill_session_var("sess_ds_current_page");
		kill_session_var("sess_ds_filter");
		kill_session_var("sess_ds_sort_column");
		kill_session_var("sess_ds_sort_direction");
		kill_session_var("sess_ds_rows");

		if (!substr_count($_SERVER["REQUEST_URI"], "/devices.php")) {
			kill_session_var("sess_ds_device_id");
		}

		kill_session_var("sess_ds_template_id");
		kill_session_var("sess_ds_method_id");

		unset($_REQUEST["page"]);
		unset($_REQUEST["filter"]);
		unset($_REQUEST["sort_column"]);
		unset($_REQUEST["sort_direction"]);
		unset($_REQUEST["rows"]);

		if (!substr_count($_SERVER["REQUEST_URI"], "/devices.php")) {
			unset($_REQUEST["device_id"]);
		}

		unset($_REQUEST["template_id"]);
		unset($_REQUEST["method_id"]);

		$_REQUEST["page"] = 1;
	}else{
		/* let's see if someone changed an important setting */
		$changed  = FALSE;
		$changed += check_changed("filter",      "sess_ds_filter");
		$changed += check_changed("rows",        "sess_ds_rows");
		$changed += check_changed("device_id",     "sess_ds_device_id");
		$changed += check_changed("template_id", "sess_ds_template_id");
		$changed += check_changed("method_id",   "sess_ds_method_id");

		if ($changed) {
			$_REQUEST["page"] = "1";
		}
	}

	/* remember these search fields in session vars so we don't have to keep passing them around */
	load_current_session_value("page", "sess_ds_current_page", "1");
	load_current_session_value("filter", "sess_ds_filter", "");
	load_current_session_value("sort_column", "sess_ds_sort_column", "name_cache");
	load_current_session_value("sort_direction", "sess_ds_sort_direction", "ASC");
	load_current_session_value("rows", "sess_ds_rows", "-1");
	load_current_session_value("device_id", "sess_ds_device_id", "-1");
	load_current_session_value("template_id", "sess_ds_template_id", "-1");
	load_current_session_value("method_id", "sess_ds_method_id", "-1");

	$device = db_fetch_row("select hostname from device where id=" . $_REQUEST["device_id"]);

	?>
	<script type="text/javascript">
	<!--
	$().ready(function() {
		$("#device").autocomplete("./lib/ajax/get_devices_brief.php", { max: 8, highlight: false, scroll: true, scrollHeight: 300 });
		$("#device").result(function(event, data, formatted) {
			if (data) {
				$(this).parent().find("#device_id").val(data[1]);
				applyDSFilterChange(document.form_data_sources);
			}else{
				$(this).parent().find("#device_id").val(0);
			}
		});
	});

	function clearDSFilterChange(objForm) {
		strURL = '?filter=';
		<?php
		# called from outside
		if (isset($_REQUEST["tab"])) {
			# print the tab
			print "strURL = strURL + &tab=" . $_REQUEST["tab"] . "';";
			# now look for more parameters
			if (isset($_REQUEST["device_id"])) {
				print "strURL = strURL + '&device_id=" . $_REQUEST["device_id"] . "&id=" . $_REQUEST["device_id"] . "';";
			}
			if (isset($_REQUEST["template_id"])) {
				print "strURL = strURL + '&template_id=" . $_REQUEST["template_id"] . "&id=" . $_REQUEST["template_id"] . "';";
			}
		}else {
			# clear all parms
			print "strURL = strURL + '&device_id=-1';";
			print "strURL = strURL + '&template_id=-1';";
		}
		?>
		strURL = strURL + '&rows=-1';
		strURL = strURL + '&method_id=-1';
		document.location = strURL;
	}

	function applyDSFilterChange(objForm) {
		strURL = '?filter=' + objForm.filter.value;
		// take care of parms provided via autocomplete
		// those are passed as objForm.<parm>.value
		// instead of $_REQUEST["<parm>"] when called from outside
		if (objForm.device_id.value) {
			strURL = '?device_id=' + objForm.device_id.value;
		}else{
			<?php print (isset($_REQUEST["device_id"]) ? "strURL = strURL + '&device_id=" . $_REQUEST["device_id"] . "&id=" . $_REQUEST["device_id"] . "';" : "strURL = strURL + '&device_id=-1';");?>
		}
		if (objForm.template_id.value) {
			strURL = '?template_id=' + objForm.template_id.value;
		}else{
			<?php print (isset($_REQUEST["template_id"]) ? "strURL = strURL + '&template_id=" . $_REQUEST["template_id"] . "&id=" . $_REQUEST["template_id"] . "';" : "strURL = strURL + '&template_id=-1';");?>
		}
		strURL = strURL + '&rows=' + objForm.rows.value;
		strURL = strURL + '&method_id=' + objForm.method_id.value;
		document.location = strURL;
	}
	-->
	</script>
	<?php

	html_start_box("<strong>" . __("Data Sources") . "</strong> " . __("[device:") . " " . (empty($device["hostname"]) ? __("No Host") : $device["hostname"]) . "]", "100", $colors["header"], "3", "center", "data_sources.php?action=data_source_edit&device_id=" . $_REQUEST["device_id"], true);
	?>
	<tr class='rowAlternate2'>
		<td>
			<form action="data_sources.php" name="form_data_sources">
			<table cellpadding="0" cellspacing="3">
				<tr>
					<td class="nw50">
						&nbsp;<?php print __("Host:");?>&nbsp;
					</td>
					<td class="w1">
						<?php
						if (isset($_REQUEST["device_id"])) {
							$hostname = db_fetch_cell("SELECT description as name FROM device WHERE id=".$_REQUEST["device_id"]." ORDER BY description,hostname");
						} else {
							$hostname = "";
						}
						?>
						<input class="ac_field" type="text" id="device" size="30" value="<?php print $hostname; ?>">
						<input type="hidden" id="device_id">
					</td>
					<td class="nw50">
						&nbsp;<?php print __("Template:");?>&nbsp;
					</td>
					<td class="w1">
						<select name="template_id" onChange="applyDSFilterChange(document.form_data_sources)">
							<option value="-1"<?php if (get_request_var_request("template_id") == "-1") {?> selected<?php }?>><?php print __("Any");?></option>
							<option value="0"<?php if (get_request_var_request("template_id") == "0") {?> selected<?php }?>><?php print __("None");?></option>
							<?php

							$templates = db_fetch_assoc("SELECT DISTINCT data_template.id, data_template.name
								FROM data_template
								INNER JOIN data_template_data
								ON data_template.id=data_template_data.data_template_id
								WHERE data_template_data.local_data_id>0
								ORDER BY data_template.name");

							if (sizeof($templates) > 0) {
							foreach ($templates as $template) {
								print "<option value='" . $template["id"] . "'"; if (get_request_var_request("template_id") == $template["id"]) { print " selected"; } print ">" . title_trim($template["name"], 40) . "</option>\n";
							}
							}
							?>
						</select>
					</td>
					<td class="nw120">
						&nbsp;<input type="submit" value="<?php print __("Go");?>" name="go" align="middle">
						<input type="button" value="<?php print __("Clear");?>" name="clear" align="middle" onClick="clearDSFilterChange(document.form_data_sources)">
					</td>
				</tr>
				<tr>
					<td class="nw50">
						&nbsp;<?php print __("Method:");?>&nbsp;
					</td>
					<td class="w1">
						<select name="method_id" onChange="applyDSFilterChange(document.form_data_sources)">
							<option value="-1"<?php if (get_request_var_request("method_id") == "-1") {?> selected<?php }?>><?php print __("Any");?></option>
							<option value="0"<?php if (get_request_var_request("method_id") == "0") {?> selected<?php }?>><?php print __("None");?></option>
							<?php

							$methods = db_fetch_assoc("SELECT DISTINCT data_input.id, data_input.name
								FROM data_input
								INNER JOIN data_template_data
								ON data_input.id=data_template_data.data_input_id
								WHERE data_template_data.local_data_id>0
								ORDER BY data_input.name");

							if (sizeof($methods) > 0) {
							foreach ($methods as $method) {
								print "<option value='" . $method["id"] . "'"; if (get_request_var_request("method_id") == $method["id"]) { print " selected"; } print ">" . title_trim($method["name"], 40) . "</option>\n";
							}
							}
							?>
						</select>
					</td>
					<td class="nw50">
						&nbsp;<?php print __("Rows:");?>&nbsp;
					</td>
					<td class="w1">
						<select name="rows" onChange="applyDSFilterChange(document.form_data_sources)">
							<option value="-1"<?php if (get_request_var_request("rows") == "-1") {?> selected<?php }?>><?php print __("Default");?></option>
							<?php
							if (sizeof($item_rows) > 0) {
							foreach ($item_rows as $key => $value) {
								print "<option value='" . $key . "'"; if (get_request_var_request("rows") == $key) { print " selected"; } print ">" . $value . "</option>\n";
							}
							}
							?>
						</select>
					</td>
				</tr>
			</table>
			<table cellpadding="1" cellspacing="3">
				<tr>
					<td class="nw50">
						&nbsp;<?php print __("Search:");?>&nbsp;
					</td>
					<td class="w1">
						<input type="text" name="filter" size="40" value="<?php print $_REQUEST["filter"];?>">
					</td>
				</tr>
			</table>
			<input type='hidden' name='page' value='1'>
			</form>
		</td>
	</tr>
	<?php
	html_end_box(false);

	/* form the 'where' clause for our main sql query */
	if (strlen(get_request_var_request("filter"))) {
		$sql_where1 = "AND (data_template_data.name_cache like '%%" . $_REQUEST["filter"] . "%%'" .
			" OR data_template_data.local_data_id like '%%" . get_request_var_request("filter") . "%%'" .
			" OR data_template.name like '%%" . get_request_var_request("filter") . "%%'" .
			" OR data_input.name like '%%" . get_request_var_request("filter") . "%%')";

		$sql_where2 = "AND (data_template_data.name_cache like '%%" . $_REQUEST["filter"] . "%%'" .
			" OR data_template.name like '%%" . get_request_var_request("filter") . "%%')";
	}else{
		$sql_where1 = "";
		$sql_where2 = "";
	}

	if (get_request_var_request("device_id") == "-1") {
		/* Show all items */
	}elseif (get_request_var_request("device_id") == "0") {
		$sql_where1 .= " AND data_local.device_id=0";
		$sql_where2 .= " AND data_local.device_id=0";
	}else {
		$sql_where1 .= " AND data_local.device_id=" . $_REQUEST["device_id"];
		$sql_where2 .= " AND data_local.device_id=" . $_REQUEST["device_id"];
	}

	if (get_request_var_request("template_id") == "-1") {
		/* Show all items */
	}elseif (get_request_var_request("template_id") == "0") {
		$sql_where1 .= " AND data_template_data.data_template_id=0";
		$sql_where2 .= " AND data_template_data.data_template_id=0";
	}else {
		$sql_where1 .= " AND data_template_data.data_template_id=" . $_REQUEST["template_id"];
		$sql_where2 .= " AND data_template_data.data_template_id=" . $_REQUEST["template_id"];
	}

	if (get_request_var_request("method_id") == "-1") {
		/* Show all items */
	}elseif (get_request_var_request("method_id") == "0") {
		$sql_where1 .= " AND data_template_data.data_input_id=0";
		$sql_where2 .= " AND data_template_data.data_input_id=0";
	}else {
		$sql_where1 .= " AND data_template_data.data_input_id=" . $_REQUEST["method_id"];
		$sql_where2 .= " AND data_template_data.data_input_id=" . $_REQUEST["method_id"];
	}

	if (get_request_var_request("rows") == "-1") {
		$rows = read_config_option("num_rows_data_source");
	}else{
		$rows = get_request_var_request("rows");
	}

	$total_rows = sizeof(db_fetch_assoc("SELECT
		data_local.id
		FROM (data_local,data_template_data)
		LEFT JOIN data_input
		ON (data_input.id=data_template_data.data_input_id)
		LEFT JOIN data_template
		ON (data_local.data_template_id=data_template.id)
		WHERE data_local.id=data_template_data.local_data_id
		$sql_where1"));

	$poller_intervals = array_rekey(db_fetch_assoc("SELECT data_template_data.local_data_id AS id,
		Min(data_template_data.rrd_step*rra.steps) AS poller_interval
		FROM data_template
		INNER JOIN (data_local
		INNER JOIN ((data_template_data_rra
		INNER JOIN data_template_data ON data_template_data_rra.data_template_data_id=data_template_data.id)
		INNER JOIN rra ON data_template_data_rra.rra_id = rra.id) ON data_local.id = data_template_data.local_data_id) ON data_template.id = data_template_data.data_template_id
		$sql_where2
		GROUP BY data_template_data.local_data_id"), "id", "poller_interval");

	$dssql = "SELECT
		data_template_data.local_data_id,
		data_template_data.name_cache,
		data_template_data.active,
		data_input.name as data_input_name,
		data_template.name as data_template_name,
		data_local.device_id
		FROM (data_local,data_template_data)
		LEFT JOIN data_input
		ON (data_input.id=data_template_data.data_input_id)
		LEFT JOIN data_template
		ON (data_local.data_template_id=data_template.id)
		WHERE data_local.id=data_template_data.local_data_id
		$sql_where1
		ORDER BY ". get_request_var_request('sort_column') . " " . get_request_var_request('sort_direction') .
		" LIMIT " . ($rows*(get_request_var_request("page")-1)) . "," . $rows;

	$data_sources = db_fetch_assoc($dssql);

	html_start_box("", "100", $colors["header"], "0", "center", "");

	/* generate page list navigation */
	$nav = html_create_nav($_REQUEST["page"], MAX_DISPLAY_PAGES, $rows, $total_rows, 7, "data_sources.php");

	print $nav;
	html_end_box(false);

	$display_text = array(
		"name_cache" => array(__("Name"), "ASC"),
		"local_data_id" => array(__("ID"),"ASC"),
		"data_input_name" => array(__("Data Input Method"), "ASC"),
		"nosort" => array(__("Poller Interval"), "ASC"),
		"active" => array(__("Active"), "ASC"),
		"data_template_name" => array(__("Template Name"), "ASC"));

	html_header_sort_checkbox($display_text, get_request_var_request("sort_column"), get_request_var_request("sort_direction"));

	if (sizeof($data_sources) > 0) {
		foreach ($data_sources as $data_source) {
			$data_source = api_plugin_hook_function('data_sources_table', $data_source);
			$data_template_name = ((empty($data_source["data_template_name"])) ? "<em>" . __("None") . "</em>" : $data_source["data_template_name"]);
			$data_input_name    = ((empty($data_source["data_input_name"])) ? "<em>" . __("External") . "</em>" : $data_source["data_input_name"]);
			$poller_interval    = ((isset($poller_intervals[$data_source["local_data_id"]])) ? $poller_intervals[$data_source["local_data_id"]] : 0);

			form_alternate_row_color('line' . $data_source["local_data_id"], true);
			form_selectable_cell("<a class='linkEditMain' href='" . htmlspecialchars("data_sources.php?action=data_source_edit&id=" . $data_source["local_data_id"]) . "' title='" . htmlspecialchars($data_source["name_cache"]) . "'>" . (($_REQUEST["filter"] != "") ? preg_replace("/(" . preg_quote($_REQUEST["filter"]) . ")/i", "<span class=\"filter\">\\1</span>", title_trim(htmlentities($data_source["name_cache"], ENT_NOQUOTES, "UTF-8"), read_config_option("max_title_data_source"))) : title_trim(htmlentities($data_source["name_cache"], ENT_NOQUOTES, "UTF-8"), read_config_option("max_title_data_source"))) . "</a>", $data_source["local_data_id"]);
			form_selectable_cell($data_source['local_data_id'], $data_source['local_data_id']);
			form_selectable_cell((($_REQUEST["filter"] != "") ? preg_replace("/(" . preg_quote($_REQUEST["filter"]) . ")/i", "<span class=\"filter\">\\1</span>", $data_input_name) : $data_input_name), $data_source["local_data_id"]);
			form_selectable_cell(get_poller_interval($poller_interval), $data_source["local_data_id"]);
			form_selectable_cell(($data_source['active'] == CHECKED ? "Yes" : "No"), $data_source["local_data_id"]);
			form_selectable_cell((($_REQUEST["filter"] != "") ? preg_replace("/(" . preg_quote($_REQUEST["filter"]) . ")/i", "<span class=\"filter\">\\1</span>", $data_source['data_template_name']) : $data_source['data_template_name']), $data_source["local_data_id"]);
			form_checkbox_cell($data_source["name_cache"], $data_source["local_data_id"]);
			form_end_row();
		}

		form_end_table();

		/* put the nav bar on the bottom as well */
		print $nav;
	}else{
		print "<tr><td><em>" . __("No Data Sources") . "</em></td></tr>";
	}

	print "</table>\n";	# end table of html_header_sort_checkbox

	/* draw the dropdown containing a list of available actions for this form */
	draw_actions_dropdown($ds_actions);
	print "</form>\n";	# end form of html_header_sort_checkbox
}
Ejemplo n.º 21
0
function graph()
{
    global $colors, $graph_actions, $item_rows;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request("host_id"));
    input_validate_input_number(get_request_var_request("graph_rows"));
    input_validate_input_number(get_request_var_request("template_id"));
    input_validate_input_number(get_request_var_request("page"));
    /* ==================================================== */
    /* clean up search string */
    if (isset($_REQUEST["filter"])) {
        $_REQUEST["filter"] = sanitize_search_string(get_request_var("filter"));
    }
    /* clean up sort_column string */
    if (isset($_REQUEST["sort_column"])) {
        $_REQUEST["sort_column"] = sanitize_search_string(get_request_var("sort_column"));
    }
    /* clean up sort_direction string */
    if (isset($_REQUEST["sort_direction"])) {
        $_REQUEST["sort_direction"] = sanitize_search_string(get_request_var("sort_direction"));
    }
    /* if the user pushed the 'clear' button */
    if (isset($_REQUEST["clear_x"])) {
        kill_session_var("sess_graph_current_page");
        kill_session_var("sess_graph_filter");
        kill_session_var("sess_graph_sort_column");
        kill_session_var("sess_graph_sort_direction");
        kill_session_var("sess_graph_host_id");
        kill_session_var("sess_graph_rows");
        kill_session_var("sess_graph_template_id");
        unset($_REQUEST["page"]);
        unset($_REQUEST["filter"]);
        unset($_REQUEST["sort_column"]);
        unset($_REQUEST["sort_direction"]);
        unset($_REQUEST["host_id"]);
        unset($_REQUEST["graph_rows"]);
        unset($_REQUEST["template_id"]);
    }
    /* remember these search fields in session vars so we don't have to keep passing them around */
    load_current_session_value("page", "sess_graph_current_page", "1");
    load_current_session_value("filter", "sess_graph_filter", "");
    load_current_session_value("sort_column", "sess_graph_sort_column", "title_cache");
    load_current_session_value("sort_direction", "sess_graph_sort_direction", "ASC");
    load_current_session_value("host_id", "sess_graph_host_id", "-1");
    load_current_session_value("graph_rows", "sess_graph_rows", read_config_option("num_rows_graph"));
    load_current_session_value("template_id", "sess_graph_template_id", "-1");
    /* if the number of rows is -1, set it to the default */
    if (get_request_var_request("graph_rows") == -1) {
        $_REQUEST["graph_rows"] = read_config_option("num_rows_graph");
    }
    ?>
	<script type="text/javascript">
	<!--

	function applyGraphsFilterChange(objForm) {
		strURL = '?host_id=' + objForm.host_id.value;
		strURL = strURL + '&graph_rows=' + objForm.graph_rows.value;
		strURL = strURL + '&filter=' + objForm.filter.value;
		strURL = strURL + '&template_id=' + objForm.template_id.value;
		document.location = strURL;
	}

	-->
	</script>
	<?php 
    /* modify for multi user start */
    if (check_resource_count(RESOURCE_GRAPH) == TRUE) {
        html_start_box("<strong>Graph Management</strong>", "100%", $colors["header"], "3", "center", "graphs.php?action=graph_edit&host_id=" . htmlspecialchars(get_request_var_request("host_id")));
    } else {
        html_start_box("<strong>Graph Management</strong>", "100%", $colors["header"], "3", "center", "");
    }
    ?>
	<tr bgcolor="#<?php 
    print $colors["panel"];
    ?>
">
		<td>
			<form name="form_graph_id" action="graphs.php">
			<table cellpadding="1" cellspacing="0">
				<tr>
					<td width="50">
						Host:&nbsp;
					</td>
					<td width="1">
						<select name="host_id" onChange="applyGraphsFilterChange(document.form_graph_id)">
							<option value="-1"<?php 
    if (get_request_var_request("host_id") == "-1") {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
                            <?php 
    /* modify for multi user start */
    if ($_SESSION["permission"] == ACCESS_ADMINISTRATOR) {
        ?>
							<option value="0"<?php 
        if (get_request_var_request("host_id") == "0") {
            ?>
 selected<?php 
        }
        ?>
>None</option>
							<?php 
    }
    if ($_SESSION["permission"] <= ACCESS_ADMINISTRATOR) {
        $hosts = db_fetch_assoc("\r\n                                    SELECT host.id,CONCAT_WS('',host.description,' (',host.hostname,')') as name FROM host \r\n                                        INNER JOIN user_auth_perms ON host.id = user_auth_perms.item_id AND user_auth_perms.user_id = '" . $_SESSION["sess_user_id"] . "' AND user_auth_perms.type = '3' \r\n                                    ORDER BY host.description,host.hostname");
    } else {
        if (read_config_option("auth_method") != 0) {
            /* get policy information for the sql where clause */
            $current_user = db_fetch_row("select * from user_auth where id=" . $_SESSION["sess_user_id"]);
            $sql_where = get_graph_permissions_sql($current_user["policy_graphs"], $current_user["policy_hosts"], $current_user["policy_graph_templates"]);
            $hosts = db_fetch_assoc("SELECT DISTINCT host.id, CONCAT_WS('',host.description,' (',host.hostname,')') as name\r\n\t\t\t\t\t\t\t\t\tFROM (graph_templates_graph,host)\r\n\t\t\t\t\t\t\t\t\tLEFT JOIN graph_local ON (graph_local.host_id=host.id)\r\n\t\t\t\t\t\t\t\t\tLEFT JOIN graph_templates ON (graph_templates.id=graph_local.graph_template_id)\r\n\t\t\t\t\t\t\t\t\tLEFT JOIN user_auth_perms ON ((graph_templates_graph.local_graph_id=user_auth_perms.item_id and user_auth_perms.type=1 and user_auth_perms.user_id=" . $_SESSION["sess_user_id"] . ") OR (host.id=user_auth_perms.item_id and user_auth_perms.type=3 and user_auth_perms.user_id=" . $_SESSION["sess_user_id"] . ") OR (graph_templates.id=user_auth_perms.item_id and user_auth_perms.type=4 and user_auth_perms.user_id=" . $_SESSION["sess_user_id"] . "))\r\n\t\t\t\t\t\t\t\t\tWHERE graph_templates_graph.local_graph_id=graph_local.id\r\n\t\t\t\t\t\t\t\t\t" . (empty($sql_where) ? "" : "and {$sql_where}") . "\r\n\t\t\t\t\t\t\t\t\tORDER BY name");
        } else {
            $hosts = db_fetch_assoc("SELECT DISTINCT host.id, CONCAT_WS('',host.description,' (',host.hostname,')') as name\r\n\t\t\t\t\t\t\t\t\tFROM host\r\n\t\t\t\t\t\t\t\t\tORDER BY name");
        }
    }
    /* modify for multi user end */
    if (sizeof($hosts) > 0) {
        foreach ($hosts as $host) {
            print "<option value='" . $host["id"] . "'";
            if (get_request_var_request("host_id") == $host["id"]) {
                print " selected";
            }
            print ">" . title_trim(htmlspecialchars($host["name"]), 40) . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
					<td width="70">
						&nbsp;Template:&nbsp;
					</td>
					<td width="1">
						<select name="template_id" onChange="applyGraphsFilterChange(document.form_graph_id)">
							<option value="-1"<?php 
    if (get_request_var_request("template_id") == "-1") {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
                            <?php 
    /* modify for multi user start */
    if ($_SESSION["permission"] == ACCESS_ADMINISTRATOR) {
        ?>
							<option value="0"<?php 
        if (get_request_var_request("template_id") == "0") {
            ?>
 selected<?php 
        }
        ?>
>None</option>
							<?php 
    }
    if ($_SESSION["permission"] < ACCESS_ADMINISTRATOR) {
        $templates = db_fetch_assoc("\r\n                                    SELECT DISTINCT graph_templates.id, graph_templates.name FROM graph_templates\r\n                                        LEFT JOIN graph_local ON graph_templates.id = graph_local.graph_template_id\r\n                                        INNER JOIN host ON graph_local.host_id = host.id\r\n                                        INNER JOIN user_auth_perms ON host.id = user_auth_perms.item_id AND user_auth_perms.user_id = '" . $_SESSION["sess_user_id"] . "' AND user_auth_perms.type = '3'\r\n                                    ORDER BY graph_templates.name");
    } else {
        if (read_config_option("auth_method") != 0) {
            $templates = db_fetch_assoc("SELECT DISTINCT graph_templates.id, graph_templates.name\r\n\t\t\t\t\t\t\t\t\tFROM (graph_templates_graph,graph_local)\r\n\t\t\t\t\t\t\t\t\tLEFT JOIN host ON (host.id=graph_local.host_id)\r\n\t\t\t\t\t\t\t\t\tLEFT JOIN graph_templates ON (graph_templates.id=graph_local.graph_template_id)\r\n\t\t\t\t\t\t\t\t\tLEFT JOIN user_auth_perms ON ((graph_templates_graph.local_graph_id=user_auth_perms.item_id and user_auth_perms.type=1 and user_auth_perms.user_id=" . $_SESSION["sess_user_id"] . ") OR (host.id=user_auth_perms.item_id and user_auth_perms.type=3 and user_auth_perms.user_id=" . $_SESSION["sess_user_id"] . ") OR (graph_templates.id=user_auth_perms.item_id and user_auth_perms.type=4 and user_auth_perms.user_id=" . $_SESSION["sess_user_id"] . "))\r\n\t\t\t\t\t\t\t\t\tWHERE graph_templates_graph.local_graph_id=graph_local.id\r\n\t\t\t\t\t\t\t\t\tAND graph_templates.id IS NOT NULL\r\n\t\t\t\t\t\t\t\t\t" . (empty($sql_where) ? "" : "AND {$sql_where}") . "\r\n\t\t\t\t\t\t\t\t\tORDER BY name");
        } else {
            $templates = db_fetch_assoc("SELECT DISTINCT graph_templates.id, graph_templates.name\r\n\t\t\t\t\t\t\t\t\tFROM graph_templates\r\n\t\t\t\t\t\t\t\t\tORDER BY name");
        }
    }
    /* modify for multi user end */
    if (sizeof($templates) > 0) {
        foreach ($templates as $template) {
            print "<option value='" . $template["id"] . "'";
            if (get_request_var_request("template_id") == $template["id"]) {
                print " selected";
            }
            print ">" . title_trim(htmlspecialchars($template["name"]), 40) . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
					<td width="120" nowrap style='white-space: nowrap;'>
						&nbsp;<input type="submit" value="Go" title="Set/Refresh Filters">
						<input type="submit" name="clear_x" value="Clear" title="Clear Filters">
					</td>
				</tr>
			</table>
			<table cellpadding="1" cellspacing="0">
				<tr>
					<td width="50">
						Search:&nbsp;
					</td>
					<td>
						<input type="text" name="filter" size="40" value="<?php 
    print htmlspecialchars(get_request_var_request("filter"));
    ?>
">
					</td>
					<td nowrap style='white-space: nowrap;' width="50">
						Rows per Page:&nbsp;
					</td>
					<td width="1">
						<select name="graph_rows" onChange="applyGraphsFilterChange(document.form_graph_id)">
							<option value="-1"<?php 
    if (get_request_var_request("graph_rows") == "-1") {
        ?>
 selected<?php 
    }
    ?>
>Default</option>
							<?php 
    if (sizeof($item_rows) > 0) {
        foreach ($item_rows as $key => $value) {
            print "<option value='" . $key . "'";
            if (get_request_var_request("graph_rows") == $key) {
                print " selected";
            }
            print ">" . htmlspecialchars($value) . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
				</tr>
			</table>
			<input type='hidden' name='page' value='1'>
			</form>
		</td>
	</tr>
	<?php 
    html_end_box();
    /* form the 'where' clause for our main sql query */
    if (strlen(get_request_var_request("filter"))) {
        $sql_where = " AND (graph_templates_graph.title_cache like '%%" . get_request_var_request("filter") . "%%'" . " OR graph_templates.name like '%%" . get_request_var_request("filter") . "%%')";
    } else {
        $sql_where = "";
    }
    if (get_request_var_request("host_id") == "-1") {
        /* Show all items */
    } elseif (get_request_var_request("host_id") == "0") {
        $sql_where .= " AND graph_local.host_id=0";
    } elseif (!empty($_REQUEST["host_id"])) {
        $sql_where .= " AND graph_local.host_id=" . get_request_var_request("host_id");
    }
    if (get_request_var_request("template_id") == "-1") {
        /* Show all items */
    } elseif (get_request_var_request("template_id") == "0") {
        $sql_where .= " AND graph_templates_graph.graph_template_id=0";
    } elseif (!empty($_REQUEST["template_id"])) {
        $sql_where .= " AND graph_templates_graph.graph_template_id=" . get_request_var_request("template_id");
    }
    /* allow plugins to modify sql_where */
    $sql_where .= api_plugin_hook_function('graphs_sql_where', $sql_where);
    /* print checkbox form for validation */
    print "<form name='chk' method='post' action='graphs.php'>\n";
    html_start_box("", "100%", $colors["header"], "3", "center", "");
    /* modify for multi user start */
    $sql_join = "";
    if ($_SESSION["permission"] < ACCESS_ADMINISTRATOR) {
        $sql_join = "\r\n        \tINNER JOIN host ON graph_local.host_id = host.id\r\n            INNER JOIN user_auth_perms ON host.id = user_auth_perms.item_id AND user_auth_perms.user_id = '" . $_SESSION["sess_user_id"] . "' AND user_auth_perms.type = '3'";
    }
    $total_rows = db_fetch_cell("SELECT\r\n\t\tDISTINCT(COUNT(graph_templates_graph.id))\r\n\t\tFROM (graph_local,graph_templates_graph)\r\n\t\tLEFT JOIN graph_templates ON (graph_local.graph_template_id=graph_templates.id)\r\n        {$sql_join}\r\n\t\tWHERE graph_local.id=graph_templates_graph.local_graph_id\r\n\t\t{$sql_where}");
    $graph_list = db_fetch_assoc("SELECT DISTINCT\r\n\t\tgraph_templates_graph.id,\r\n\t\tgraph_templates_graph.local_graph_id,\r\n\t\tgraph_templates_graph.height,\r\n\t\tgraph_templates_graph.width,\r\n\t\tgraph_templates_graph.title_cache,\r\n\t\tgraph_templates.name,\r\n\t\tgraph_local.host_id\r\n\t\tFROM (graph_local,graph_templates_graph)\r\n\t\tLEFT JOIN graph_templates ON (graph_local.graph_template_id=graph_templates.id)\r\n        {$sql_join}\r\n\t\tWHERE graph_local.id=graph_templates_graph.local_graph_id\r\n\t\t{$sql_where}\r\n\t\tORDER BY " . $_REQUEST["sort_column"] . " " . get_request_var_request("sort_direction") . " LIMIT " . get_request_var_request("graph_rows") * (get_request_var_request("page") - 1) . "," . get_request_var_request("graph_rows"));
    /* modify for multi user end */
    /* generate page list */
    $url_page_select = get_page_list(get_request_var_request("page"), MAX_DISPLAY_PAGES, get_request_var_request("graph_rows"), $total_rows, "graphs.php?filter=" . get_request_var_request("filter") . "&host_id=" . get_request_var_request("host_id"));
    $nav = "<tr bgcolor='#" . $colors["header"] . "'>\r\n\t\t\t<td colspan='5'>\r\n\t\t\t\t<table width='100%' cellspacing='0' cellpadding='0' border='0'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td align='left' class='textHeaderDark'>\r\n\t\t\t\t\t\t\t<strong>&lt;&lt; ";
    if (get_request_var_request("page") > 1) {
        $nav .= "<a class='linkOverDark' href='" . htmlspecialchars("graphs.php?filter=" . get_request_var_request("filter") . "&host_id=" . get_request_var_request("host_id") . "&page=" . (get_request_var_request("page") - 1)) . "'>";
    }
    $nav .= "Previous";
    if (get_request_var_request("page") > 1) {
        $nav .= "</a>";
    }
    $nav .= "</strong>\r\n\t\t\t\t\t\t</td>\n\r\n\t\t\t\t\t\t<td align='center' class='textHeaderDark'>\r\n\t\t\t\t\t\t\tShowing Rows " . (get_request_var_request("graph_rows") * (get_request_var_request("page") - 1) + 1) . " to " . ($total_rows < get_request_var_request("graph_rows") || $total_rows < get_request_var_request("graph_rows") * get_request_var_request("page") ? $total_rows : get_request_var_request("graph_rows") * get_request_var_request("page")) . " of {$total_rows} [{$url_page_select}]\r\n\t\t\t\t\t\t</td>\n\r\n\t\t\t\t\t\t<td align='right' class='textHeaderDark'>\r\n\t\t\t\t\t\t\t<strong>";
    if (get_request_var_request("page") * get_request_var_request("graph_rows") < $total_rows) {
        $nav .= "<a class='linkOverDark' href='" . htmlspecialchars("graphs.php?filter=" . get_request_var_request("filter") . "&host_id=" . get_request_var_request("host_id") . "&page=" . (get_request_var_request("page") + 1)) . "'>";
    }
    $nav .= "Next";
    if (get_request_var_request("page") * get_request_var_request("graph_rows") < $total_rows) {
        $nav .= "</a>";
    }
    $nav .= " &gt;&gt;</strong>\r\n\t\t\t\t\t\t</td>\n\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t</td>\r\n\t\t</tr>\n";
    print $nav;
    $display_text = array("title_cache" => array("Graph Title", "ASC"), "local_graph_id" => array("ID", "ASC"), "name" => array("Template Name", "ASC"), "height" => array("Size", "ASC"));
    html_header_sort_checkbox($display_text, get_request_var_request("sort_column"), get_request_var_request("sort_direction"), false);
    $i = 0;
    if (sizeof($graph_list) > 0) {
        foreach ($graph_list as $graph) {
            /* we're escaping strings here, so no need to escape them on form_selectable_cell */
            $template_name = empty($graph["name"]) ? "<em>None</em>" : htmlspecialchars($graph["name"]);
            form_alternate_row_color($colors["alternate"], $colors["light"], $i, 'line' . $graph["local_graph_id"]);
            $i++;
            form_selectable_cell("<a class='linkEditMain' href='" . htmlspecialchars("graphs.php?action=graph_edit&id=" . $graph["local_graph_id"]) . "' title='" . htmlspecialchars($graph["title_cache"]) . "'>" . (get_request_var_request("filter") != "" ? preg_replace("/(" . preg_quote(get_request_var_request("filter")) . ")/i", "<span style='background-color: #F8D93D;'>\\1</span>", title_trim(htmlspecialchars($graph["title_cache"]), read_config_option("max_title_graph"))) : title_trim(htmlspecialchars($graph["title_cache"]), read_config_option("max_title_graph"))) . "</a>", $graph["local_graph_id"]);
            form_selectable_cell($graph["local_graph_id"], $graph["local_graph_id"]);
            form_selectable_cell(get_request_var_request("filter") != "" ? preg_replace("/(" . preg_quote(get_request_var_request("filter")) . ")/i", "<span style='background-color: #F8D93D;'>\\1</span>", $template_name) : $template_name, $graph["local_graph_id"]);
            form_selectable_cell($graph["height"] . "x" . $graph["width"], $graph["local_graph_id"]);
            form_checkbox_cell($graph["title_cache"], $graph["local_graph_id"]);
            form_end_row();
        }
        /* put the nav bar on the bottom as well */
        print $nav;
    } else {
        print "<tr><td><em>No Graphs Found</em></td></tr>";
    }
    html_end_box(false);
    /* add a list of tree names to the actions dropdown */
    add_tree_names_to_actions_array();
    /* draw the dropdown containing a list of available actions for this form */
    draw_actions_dropdown($graph_actions);
    print "</form>\n";
}
Ejemplo n.º 22
0
function log_cacti_stats($loop_start, $method, $concurrent_processes, $max_threads, $num_hosts, $hosts_per_process, $num_polling_items, $rrds_processed)
{
    /* take time and log performance data */
    list($micro, $seconds) = explode(" ", microtime());
    $loop_end = $seconds + $micro;
    $cacti_stats = sprintf("Time:%01.4f " . "Method:%s " . "Processes:%s " . "Threads:%s " . "Hosts:%s " . "HostsPerProcess:%s " . "DataSources:%s " . "RRDsProcessed:%s", round($loop_end - $loop_start, 4), $method, $concurrent_processes, $max_threads, $num_hosts, $hosts_per_process, $num_polling_items, $rrds_processed);
    cacti_log("STATS: " . $cacti_stats, true, "SYSTEM");
    /* insert poller stats into the settings table */
    db_execute("REPLACE INTO settings (name,value) VALUES ('stats_poller','{$cacti_stats}')");
    api_plugin_hook_function('cacti_stats_update', array(round($loop_end - $loop_start, 4), $method, $concurrent_processes, $max_threads, $num_hosts, $hosts_per_process, $num_polling_items, $rrds_processed));
}
Ejemplo n.º 23
0
 |                                                                         |
 | This program is distributed in the hope that it will be useful,         |
 | but WITHOUT ANY WARRANTY; without even the implied warranty of          |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           |
 | GNU General Public License for more details.                            |
 +-------------------------------------------------------------------------+
 | Cacti: The Complete RRDTool-based Graphing Solution                     |
 +-------------------------------------------------------------------------+
 | This code is designed, written, and maintained by the Cacti Group. See  |
 | about.php and/or the AUTHORS file for specific developer information.   |
 +-------------------------------------------------------------------------+
 | http://www.cacti.net/                                                   |
 +-------------------------------------------------------------------------+
*/
if (!defined('VALID_HOST_FIELDS')) {
    $string = api_plugin_hook_function('valid_host_fields', '(hostname|host_id|snmp_community|snmp_username|snmp_password|snmp_auth_protocol|snmp_priv_passphrase|snmp_priv_protocol|snmp_context|snmp_version|snmp_port|snmp_timeout)');
    define('VALID_HOST_FIELDS', $string);
}
/* file: cdef.php, action: edit */
$fields_cdef_edit = array("name" => array("method" => "textbox", "friendly_name" => "Name", "description" => "A useful name for this CDEF.", "value" => "|arg1:name|", "max_length" => "255", "size" => "60"), "id" => array("method" => "hidden_zero", "value" => "|arg1:id|"), "save_component_cdef" => array("method" => "hidden", "value" => "1"));
/* file: color.php, action: edit */
$fields_color_edit = array("hex" => array("method" => "textbox", "friendly_name" => "Hex Value", "description" => "The hex value for this color; valid range: 000000-FFFFFF.", "value" => "|arg1:hex|", "max_length" => "6"), "id" => array("method" => "hidden_zero", "value" => "|arg1:id|"), "save_component_color" => array("method" => "hidden", "value" => "1"));
/* file: data_input.php, action: edit */
$fields_data_input_edit = array("name" => array("method" => "textbox", "friendly_name" => "Name", "description" => "Enter a meaningful name for this data input method.", "value" => "|arg1:name|", "max_length" => "255"), "type_id" => array("method" => "drop_array", "friendly_name" => "Input Type", "description" => "Choose the method you wish to use to collect data for this Data Input method.", "value" => "|arg1:type_id|", "array" => $input_types), "input_string" => array("method" => "textarea", "friendly_name" => "Input String", "description" => "The data that is sent to the script, which includes the complete path to the script and input sources in &lt;&gt; brackets.", "value" => "|arg1:input_string|", "textarea_rows" => "4", "textarea_cols" => "60", "class" => "textAreaNotes", "max_length" => "255"), "id" => array("method" => "hidden_zero", "value" => "|arg1:id|"), "save_component_data_input" => array("method" => "hidden", "value" => "1"));
/* file: data_input.php, action: field_edit (dropdown) */
$fields_data_input_field_edit_1 = array("data_name" => array("method" => "drop_array", "friendly_name" => "Field [|arg1:|]", "description" => "Choose the associated field from the |arg1:| field.", "value" => "|arg3:data_name|", "array" => "|arg2:|"));
/* file: data_input.php, action: field_edit (textbox) */
$fields_data_input_field_edit_2 = array("data_name" => array("method" => "textbox", "friendly_name" => "Field [|arg1:|]", "description" => "Enter a name for this |arg1:| field.", "value" => "|arg2:data_name|", "max_length" => "50"));
/* file: data_input.php, action: field_edit */
$fields_data_input_field_edit = array("name" => array("method" => "textbox", "friendly_name" => "Friendly Name", "description" => "Enter a meaningful name for this data input method.", "value" => "|arg1:name|", "max_length" => "200"), "update_rra" => array("method" => "checkbox", "friendly_name" => "Update RRD File", "description" => "Whether data from this output field is to be entered into the rrd file.", "value" => "|arg1:update_rra|", "default" => "on", "form_id" => "|arg1:id|"), "regexp_match" => array("method" => "textbox", "friendly_name" => "Regular Expression Match", "description" => "If you want to require a certain regular expression to be matched againt input data, enter it here (ereg format).", "value" => "|arg1:regexp_match|", "max_length" => "200", "size" => "70"), "allow_nulls" => array("method" => "checkbox", "friendly_name" => "Allow Empty Input", "description" => "Check here if you want to allow NULL input in this field from the user.", "value" => "|arg1:allow_nulls|", "default" => "", "form_id" => false), "type_code" => array("method" => "textbox", "friendly_name" => "Special Type Code", "description" => "If this field should be treated specially by host templates, indicate so here. Valid keywords for this field are " . str_replace(")", "'", str_replace("(", "'", str_replace("|", "', '", VALID_HOST_FIELDS))), "value" => "|arg1:type_code|", "max_length" => "40"), "id" => array("method" => "hidden_zero", "value" => "|arg1:id|"), "input_output" => array("method" => "hidden", "value" => "|arg2:|"), "sequence" => array("method" => "hidden_zero", "value" => "|arg1:sequence|"), "data_input_id" => array("method" => "hidden_zero", "value" => "|arg3:data_input_id|"), "save_component_field" => array("method" => "hidden", "value" => "1"));
/* file: data_templates.php, action: template_edit */
Ejemplo n.º 24
0
*/
global $config, $refresh;
$script = basename($_SERVER['SCRIPT_NAME']);
if ($script == 'graph_view.php' || $script == 'graph.php') {
    if (isset($_SESSION['custom']) && $_SESSION['custom'] == true) {
        $refreshIsLogout = 'true';
    } else {
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'zoom') {
            $refreshIsLogout = 'true';
        } else {
            $refresh = api_plugin_hook_function('top_graph_refresh', read_graph_config_option('page_refresh'));
            $refreshIsLogout = 'false';
        }
    }
} elseif (strstr($_SERVER['SCRIPT_NAME'], 'plugins')) {
    $refresh = api_plugin_hook_function('top_graph_refresh', $refresh);
    if (empty($refresh)) {
        $refreshIsLogout = 'true';
    } else {
        $refreshIsLogout = 'false';
    }
}
if (!empty($refresh)) {
    $refreshIsLogout = 'false';
    if (!is_array($refresh)) {
        $myrefresh['seconds'] = $refresh;
        $myrefresh['page'] = $_SERVER['REQUEST_URI'] . (strpos($_SERVER['REQUEST_URI'], '?') ? '&' : '?') . 'header=false';
    } else {
        $myrefresh = $refresh;
        $myrefresh['page'] .= (strpos($myrefresh['page'], '?') ? '&' : '?') . 'header=false';
    }
Ejemplo n.º 25
0
    api_plugin_hook('page_head');
    ?>
</head>
<?php 
    if ($oper_mode == OPER_MODE_NATIVE) {
        ?>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" <?php 
        print api_plugin_hook_function("body_style", "");
        ?>
>
<a name='page_top'></a>
<?php 
    } else {
        ?>
<body leftmargin="15" topmargin="15" marginwidth="15" marginheight="15" <?php 
        print api_plugin_hook_function("body_style", "");
        ?>
>
<?php 
    }
    ?>

<table width="100%" height="100%" cellspacing="0" cellpadding="0">
<?php 
    if ($oper_mode == OPER_MODE_NATIVE) {
        ?>
	<tr height="37" bgcolor="#a9a9a9" class="noprint">
		<td colspan="2" valign="bottom" nowrap>
			<table width="100%" cellspacing="0" cellpadding="0">
				<tr style="background: transparent url('<?php 
        print $config['url_path'];
Ejemplo n.º 26
0
Archivo: rrd.php Proyecto: MrWnn/cacti
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;
    }
}
Ejemplo n.º 27
0
function utilities_view_tech($php_info = "")
{
    global $database_default, $config, $rrdtool_versions, $poller_options, $input_types;
    /* Get table status */
    $tables = db_fetch_assoc("SHOW TABLES");
    $skip_tables = array();
    $table_status = array();
    if (sizeof($tables)) {
        foreach ($tables as $table) {
            $create_syntax = db_fetch_row("SHOW CREATE TABLE " . $table["Tables_in_" . $database_default]);
            if (sizeof($create_syntax)) {
                if (substr_count(strtoupper($create_syntax["Create Table"]), "INNODB")) {
                    $skip_tables[] = $table["Tables_in_" . $database_default];
                } else {
                    $include_tables[] = $table["Tables_in_" . $database_default];
                }
            }
        }
    }
    if (sizeof($include_tables)) {
        foreach ($include_tables as $table) {
            $status = db_fetch_row("SHOW TABLE STATUS LIKE '{$table}'");
            array_push($table_status, $status);
        }
    }
    /* Get poller stats */
    $poller_item = db_fetch_assoc("SELECT action, count(action) as total FROM poller_item GROUP BY action");
    /* Get system stats */
    $host_count = db_fetch_cell("SELECT COUNT(*) FROM host");
    $graph_count = db_fetch_cell("SELECT COUNT(*) FROM graph_local");
    $data_count = db_fetch_assoc("SELECT i.type_id, COUNT(i.type_id) AS total FROM data_template_data AS d, data_input AS i WHERE d.data_input_id = i.id AND local_data_id <> 0 GROUP BY i.type_id");
    /* Get RRDtool version */
    $rrdtool_version = "Unknown";
    if (file_exists(read_config_option("path_rrdtool")) && (function_exists('is_executable') && is_executable(read_config_option("path_rrdtool")))) {
        $out_array = array();
        exec(cacti_escapeshellcmd(read_config_option("path_rrdtool")), $out_array);
        if (sizeof($out_array) > 0) {
            if (preg_match("/^RRDtool 1\\.4/", $out_array[0])) {
                $rrdtool_version = "rrd-1.4.x";
            } else {
                if (preg_match("/^RRDtool 1\\.3\\./", $out_array[0])) {
                    $rrdtool_version = "rrd-1.3.x";
                } else {
                    if (preg_match("/^RRDtool 1\\.2\\./", $out_array[0])) {
                        $rrdtool_version = "rrd-1.2.x";
                    } else {
                        if (preg_match("/^RRDtool 1\\.0\\./", $out_array[0])) {
                            $rrdtool_version = "rrd-1.0.x";
                        }
                    }
                }
            }
        }
    }
    /* Get SNMP cli version */
    $snmp_version = read_config_option("snmp_version");
    if (file_exists(read_config_option("path_snmpget")) && (function_exists('is_executable') && is_executable(read_config_option("path_snmpget")))) {
        $snmp_version = shell_exec(cacti_escapeshellcmd(read_config_option("path_snmpget")) . " -V 2>&1");
    }
    /* Check RRDTool issues */
    $rrdtool_error = "";
    if ($rrdtool_version != read_config_option("rrdtool_version")) {
        $rrdtool_error .= "<br><font color='red'>ERROR: Installed RRDTool version does not match configured version.<br>Please visit the <a href='" . htmlspecialchars("settings.php?tab=general") . "'>Configuration Settings</a> and select the correct RRDTool Utility Version.</font><br>";
    }
    $graph_gif_count = db_fetch_cell("SELECT COUNT(*) FROM graph_templates_graph WHERE image_format_id = 2");
    if ($graph_gif_count > 0 && read_config_option("rrdtool_version") != "rrd-1.0.x") {
        $rrdtool_error .= "<br><font color='red'>ERROR: RRDTool 1.2.x does not support the GIF images format, but " . $graph_gif_count . " graph(s) and/or templates have GIF set as the image format.</font><br>";
    }
    /* Get spine version */
    $spine_version = "Unknown";
    if (file_exists(read_config_option("path_spine")) && (function_exists('is_executable') && is_executable(read_config_option("path_spine")))) {
        $out_array = array();
        exec(read_config_option("path_spine") . " --version", $out_array);
        if (sizeof($out_array) > 0) {
            $spine_version = $out_array[0];
        }
    }
    /* Display tech information */
    html_start_box("<strong>Technical Support</strong>", "100%", "", "3", "center", "");
    html_header(array("General Information"), 2);
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Date</td>\n";
    print "\t\t<td class='textArea'>" . date("r") . "</td>\n";
    print "</tr>\n";
    api_plugin_hook_function('custom_version_info');
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>Cacti Version</td>\n";
    print "\t\t<td class='textArea'>" . $config["cacti_version"] . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Cacti OS</td>\n";
    print "\t\t<td class='textArea'>" . $config["cacti_server_os"] . "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>SNMP Version</td>\n";
    print "\t\t<td class='textArea'>" . $snmp_version . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>RRDTool Version</td>\n";
    print "\t\t<td class='textArea'>" . $rrdtool_versions[$rrdtool_version] . " " . $rrdtool_error . "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>Hosts</td>\n";
    print "\t\t<td class='textArea'>" . $host_count . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Graphs</td>\n";
    print "\t\t<td class='textArea'>" . $graph_count . "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>Data Sources</td>\n";
    print "\t\t<td class='textArea'>";
    $data_total = 0;
    if (sizeof($data_count)) {
        foreach ($data_count as $item) {
            print $input_types[$item["type_id"]] . ": " . $item["total"] . "<br>";
            $data_total += $item["total"];
        }
        print "Total: " . $data_total;
    } else {
        print "<font color='red'>0</font>";
    }
    print "</td>\n";
    print "</tr>\n";
    html_header(array("Poller Information"), 2);
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Interval</td>\n";
    print "\t\t<td class='textArea'>" . read_config_option("poller_interval") . "</td>\n";
    if (file_exists(read_config_option("path_spine")) && $poller_options[read_config_option("poller_type")] == 'spine') {
        $type = $spine_version;
    } else {
        $type = $poller_options[read_config_option("poller_type")];
    }
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>Type</td>\n";
    print "\t\t<td class='textArea'>" . $type . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Items</td>\n";
    print "\t\t<td class='textArea'>";
    $total = 0;
    if (sizeof($poller_item)) {
        foreach ($poller_item as $item) {
            print "Action[" . $item["action"] . "]: " . $item["total"] . "<br>";
            $total += $item["total"];
        }
        print "Total: " . $total;
    } else {
        print "<font color='red'>No items to poll</font>";
    }
    print "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>Concurrent Processes</td>\n";
    print "\t\t<td class='textArea'>" . read_config_option("concurrent_processes") . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Max Threads</td>\n";
    print "\t\t<td class='textArea'>" . read_config_option("max_threads") . "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>PHP Servers</td>\n";
    print "\t\t<td class='textArea'>" . read_config_option("php_servers") . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Script Timeout</td>\n";
    print "\t\t<td class='textArea'>" . read_config_option("script_timeout") . "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>Max OID</td>\n";
    print "\t\t<td class='textArea'>" . read_config_option("max_get_size") . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>Last Run Statistics</td>\n";
    print "\t\t<td class='textArea'>" . read_config_option("stats_poller") . "</td>\n";
    print "</tr>\n";
    html_header(array("PHP Information"), 2);
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>PHP Version</td>\n";
    print "\t\t<td class='textArea'>" . phpversion() . "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>PHP OS</td>\n";
    print "\t\t<td class='textArea'>" . PHP_OS . "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>PHP uname</td>\n";
    print "\t\t<td class='textArea'>";
    if (function_exists("php_uname")) {
        print php_uname();
    } else {
        print "N/A";
    }
    print "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>PHP SNMP</td>\n";
    print "\t\t<td class='textArea'>";
    if (function_exists("snmpget")) {
        print "Installed";
    } else {
        print "Not Installed";
    }
    print "</td>\n";
    print "</tr>\n";
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea'>max_execution_time</td>\n";
    print "\t\t<td class='textArea'>" . ini_get("max_execution_time") . "</td>\n";
    print "</tr>\n";
    print "<tr class='even'>\n";
    print "\t\t<td class='textArea'>memory_limit</td>\n";
    print "\t\t<td class='textArea'>" . ini_get("memory_limit");
    /* Calculate memory suggestion based off of data source count */
    $memory_suggestion = $data_total * 32768;
    /* Set minimum - 16M */
    if ($memory_suggestion < 16777216) {
        $memory_suggestion = 16777216;
    }
    /* Set maximum - 512M */
    if ($memory_suggestion > 536870912) {
        $memory_suggestion = 536870912;
    }
    /* Suggest values in 8M increments */
    $memory_suggestion = round($memory_suggestion / 8388608) * 8388608;
    if (memory_bytes(ini_get('memory_limit')) < $memory_suggestion) {
        print "<br><font color='red'>";
        if (ini_get('memory_limit') == -1) {
            print "You've set memory limit to 'unlimited'.<br/>";
        }
        print "It is highly suggested that you alter you php.ini memory_limit to " . memory_readable($memory_suggestion) . " or higher. <br/>\n\t\t\tThis suggested memory value is calculated based on the number of data source present and is only to be used as a suggestion, actual values may vary system to system based on requirements.";
        print "</font><br>";
    }
    print "</td>\n";
    print "</tr>\n";
    html_header(array("MySQL Table Information"), 2);
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea' colspan='2' align='center'>";
    if (sizeof($table_status) > 0) {
        print "<table border='1' cellpadding='2' cellspacing='0'>\n";
        print "<tr>\n";
        print "  <th>Name</th>\n";
        print "  <th>Rows</th>\n";
        print "  <th>Engine</th>\n";
        print "  <th>Collation</th>\n";
        print "</tr>\n";
        foreach ($table_status as $item) {
            print "<tr>\n";
            print "  <td>" . $item["Name"] . "</td>\n";
            print "  <td>" . $item["Rows"] . "</td>\n";
            if (isset($item["Engine"])) {
                print "  <td>" . $item["Engine"] . "</td>\n";
            } else {
                print "  <td>Unknown</td>\n";
            }
            if (isset($item["Collation"])) {
                print "  <td>" . $item["Collation"] . "</td>\n";
            } else {
                print "  <td>Unknown</td>\n";
            }
            print "</tr>\n";
        }
        if (sizeof($skip_tables)) {
            print "<tr><td colspan='20' align='center'><strong>The Following Tables were Skipped Due to being INNODB</strong></td></tr>";
            foreach ($skip_tables as $table) {
                print "<tr><td colspan='20' align='center'>" . $table . "</td></tr>";
            }
        }
        print "</table>\n";
    } else {
        print "Unable to retrieve table status";
    }
    print "</td>\n";
    print "</tr>\n";
    html_header(array("PHP Module Information"), 2);
    print "<tr class='odd'>\n";
    print "\t\t<td class='textArea' colspan='2'>" . $php_info . "</td>\n";
    print "</tr>\n";
    html_end_box();
}
Ejemplo n.º 28
0
Archivo: auth.php Proyecto: MrWnn/cacti
function user_remove($user_id)
{
    /* ================= input validation ================= */
    input_validate_input_number($user_id);
    /* ==================================================== */
    /* check for guest or template user */
    $username = db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($user_id));
    if ($username != get_request_var_post('username')) {
        if ($username == read_config_option('user_template')) {
            raise_message(21);
            return;
        }
        if ($username == read_config_option('guest_user')) {
            raise_message(21);
            return;
        }
    }
    db_execute_prepared('DELETE FROM user_auth WHERE id = ?', array($user_id));
    db_execute_prepared('DELETE FROM user_auth_realm WHERE user_id = ?', array($user_id));
    db_execute_prepared('DELETE FROM user_auth_perms WHERE user_id = ?', array($user_id));
    db_execute_prepared('DELETE FROM user_auth_group_members WHERE user_id = ?', array($user_id));
    db_execute_prepared('DELETE FROM settings_graphs WHERE user_id = ?', array($user_id));
    db_execute_prepared('DELETE FROM settings_tree WHERE user_id = ?', array($user_id));
    api_plugin_hook_function('user_remove', $user_id);
}
Ejemplo n.º 29
0
function do_hook_function($name, $parm = NULL)
{
    return api_plugin_hook_function($name, $parm);
}
Ejemplo n.º 30
0
/* remove flagged messages */
syslog_db_execute('DELETE FROM `' . $syslogdb_default . '`.`syslog_incoming` WHERE status=' . $uniqueID);
syslog_debug('Deleted ' . db_affected_rows($syslog_cnn) . ',  Already Processed Message(s) from incoming');
/* remove stats messages */
if (read_config_option('syslog_statistics') == 'on') {
    if (read_config_option('syslog_retention') > 0) {
        syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog_statistics`\n\t\t\tWHERE insert_time<'" . date('Y-m-d H:i:s', time() - read_config_option('syslog_retention') * 86400) . "'");
        syslog_debug('Deleted ' . db_affected_rows($syslog_cnn) . ',  Syslog Statistics Record(s)');
    }
} else {
    syslog_db_execute('TRUNCATE `' . $syslogdb_default . '`.`syslog_statistics`');
}
/* remove alert log messages */
if (read_config_option('syslog_alert_retention') > 0) {
    $delete_time = date('Y-m-d H:i:s', time() - read_config_option('syslog_alert_retention') * 86400);
    api_plugin_hook_function('syslog_delete_hostsalarm', $delete_time);
    syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog_logs`\n\t\tWHERE logtime<'" . date('Y-m-d H:i:s', time() - read_config_option('syslog_alert_retention') * 86400) . "'");
    syslog_debug('Deleted ' . db_affected_rows($syslog_cnn) . ',  Syslog alarm log Record(s)');
    syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog_hosts`\n\t\tWHERE last_updated<'" . date('Y-m-d H:i:s', time() - read_config_option('syslog_alert_retention') * 86400) . "'");
    syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog_programs`\n\t\tWHERE last_updated<'" . date('Y-m-d H:i:s', time() - read_config_option('syslog_alert_retention') * 86400) . "'");
    syslog_debug('Deleted ' . db_affected_rows($syslog_cnn) . ',  Syslog Host Record(s)');
    syslog_db_execute('DELETE FROM `' . $syslogdb_default . "`.`syslog_host_facilities`\n\t\tWHERE last_updated<'" . date('Y-m-d H:i:s', time() - read_config_option('syslog_alert_retention') * 86400) . "'");
    syslog_debug('Deleted ' . db_affected_rows($syslog_cnn) . ',  Syslog Host/Facility Record(s)');
}
/* OPTIMIZE THE TABLES ONCE A DAY, JUST TO HELP CLEANUP */
if (date('G') == 0 && date('i') < 5) {
    syslog_debug('Optimizing Tables');
    if (!syslog_is_partitioned()) {
        syslog_db_execute('OPTIMIZE TABLE
			`' . $syslogdb_default . '`.`syslog_incoming`,
			`' . $syslogdb_default . '`.`syslog`,