Example #1
0
File: cdef.php Project: MrWnn/cacti
function get_cdef_item_name($cdef_item_id)
{
    global $cdef_functions, $cdef_operators;
    $cdef_item = db_fetch_row_prepared('SELECT type, value FROM cdef_items WHERE id = ?', array($cdef_item_id));
    $current_cdef_value = $cdef_item['value'];
    switch ($cdef_item['type']) {
        case '1':
            return $cdef_functions[$current_cdef_value];
            break;
        case '2':
            return $cdef_operators[$current_cdef_value];
            break;
        case '4':
            return $current_cdef_value;
            break;
        case '5':
            return db_fetch_cell_prepared('SELECT name FROM cdef WHERE id = ?', array($current_cdef_value));
            break;
        case '6':
            return $current_cdef_value;
            break;
    }
}
Example #2
0
File: tree.php Project: MrWnn/cacti
function tree_remove()
{
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    /* ==================================================== */
    if (read_config_option('deletion_verification') == 'on' && !isset($_REQUEST['confirm'])) {
        top_header();
        form_confirm('Are You Sure?', "Are you sure you want to delete the tree <strong>'" . htmlspecialchars(db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array($_REQUEST['id'])), ENT_QUOTES) . "'</strong>?", htmlspecialchars('tree.php'), htmlspecialchars('tree.php?action=remove&id=' . $_REQUEST['id']));
        bottom_footer();
        exit;
    }
    if (read_config_option('deletion_verification') == '' || isset($_REQUEST['confirm'])) {
        db_execute_prepared('DELETE FROM graph_tree WHERE id = ?', array($_REQUEST['id']));
        db_execute_prepared('DELETE FROM graph_tree_items WHERE graph_tree_id = ?', array($_REQUEST['id']));
    }
    /* clear graph tree cache on save - affects current user only, other users should see changes in <5 minutes */
    if (isset($_SESSION['dhtml_tree'])) {
        unset($_SESSION['dhtml_tree']);
    }
}
Example #3
0
File: host.php Project: MrWnn/cacti
function host_edit()
{
    global $fields_host_edit, $reindex_types;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    /* ==================================================== */
    api_plugin_hook('host_edit_top');
    if (!empty($_REQUEST['id'])) {
        $host = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($_REQUEST['id']));
        $header_label = '[edit: ' . htmlspecialchars($host['description']) . ']';
    } else {
        $header_label = '[new]';
    }
    if (!empty($host['id'])) {
        ?>
		<table width='100%' align='center'>
			<tr>
				<td class='textInfo' colspan='2'>
					<?php 
        print htmlspecialchars($host['description']);
        ?>
 (<?php 
        print htmlspecialchars($host['hostname']);
        ?>
)
				</td>
				<td rowspan='2' class='textInfo' valign='top' align='right'>
					<span class='linkMarker'>*</span><a class='hyperLink' href='<?php 
        print htmlspecialchars('graphs_new.php?host_id=' . $host['id']);
        ?>
'>Create Graphs for this Device</a><br>
					<span class='linkMarker'>*</span><a class='hyperLink' href='<?php 
        print htmlspecialchars('data_sources.php?host_id=' . $host['id'] . '&ds_rows=30&filter=&template_id=-1&method_id=-1&page=1');
        ?>
'>Data Source List</a><br>
					<span class='linkMarker'>*</span><a class='hyperLink' href='<?php 
        print htmlspecialchars('graphs.php?host_id=' . $host['id'] . '&graph_rows=30&filter=&template_id=-1&page=1');
        ?>
'>Graph List</a>
					<?php 
        api_plugin_hook('device_edit_top_links');
        ?>
				</td>
			</tr>
			<tr>
				<td valign='top' class='textHeader'>
					<div id='ping_results'>Pinging Device&nbsp;<i style='font-size:12px;' class='fa fa-spin fa-spinner'></i><br><br></div>
				</td>
			</tr>
		</table>
		<?php 
    }
    html_start_box("<strong>Device</strong> {$header_label}", '100%', '', '3', 'center', '');
    /* preserve the host template id if passed in via a GET variable */
    if (!empty($_REQUEST['host_template_id'])) {
        $fields_host_edit['host_template_id']['value'] = $_REQUEST['host_template_id'];
    }
    draw_edit_form(array('config' => array('form_name' => 'chk'), 'fields' => inject_form_variables($fields_host_edit, isset($host) ? $host : array())));
    /* we have to hide this button to make a form change in the main form trigger the correct
     * submit action */
    echo "<div style='display:none;'><input type='submit' value='Default Submit Button'></div>";
    html_end_box();
    ?>
	<script type="text/javascript">
	<!--

	// default snmp information
	var snmp_community       = $('#snmp_community').val();
	var snmp_username        = $('#snmp_username').val();
	var snmp_password        = $('#snmp_password').val();
	var snmp_auth_protocol   = $('#snmp_auth_protocol').val();
	var snmp_priv_passphrase = $('#snmp_priv_passphrase').val();
	var snmp_priv_protocol   = $('#snmp_priv_protocol').val();
	var snmp_context         = $('#snmp_context').val();
	var snmp_port            = $('#snmp_port').val();
	var snmp_timeout         = $('#snmp_timeout').val();
	var max_oids             = $('#max_oids').val();

	// default ping methods
	var ping_method    = $('#ping_method').val();
	var ping_port      = $('#ping_port').val();
	var ping_timeout   = $('#ping_timeout').val();
	var ping_retries   = $('#ping_retries').val();

	function setPing() {
		availability_method = $('#availability_method').val();
		ping_method         = $('#ping_method').val();

		switch(availability_method) {
		case '0': // none
			$('#row_ping_method').css('display', 'none');
			$('#row_ping_port').css('display', 'none');
			$('#row_ping_timeout').css('display', 'none');
			$('#row_ping_retries').css('display', 'none');

			break;
		case '2': // snmp
		case '5': // snmp sysDesc
		case '6': // snmp getNext
			$('#row_ping_method').css('display', 'none');
			$('#row_ping_port').css('display', 'none');
			$('#row_ping_timeout').css('display', '');
			$('#row_ping_retries').css('display', '');

			break;
		default: // ping ok
			switch(ping_method) {
			case '1': // ping icmp
				$('#row_ping_method').css('display', '');
				$('#row_ping_port').css('display', 'none');
				$('#row_ping_timeout').css('display', '');
				$('#row_ping_retries').css('display', '');

				break;
			case '2': // ping udp
			case '3': // ping tcp
				$('#row_ping_method').css('display', '');
				$('#row_ping_port').css('display', '');
				$('#row_ping_timeout').css('display', '');
				$('#row_ping_retries').css('display', '');

				break;
			}

			break;
		}
	}

	function setAvailability() {
		if ($('#snmp_version').val() == '0') {
			methods = [ 
				{ value: '0', text: 'None' }, 
				{ value: '3', text: 'Ping' }
			];

			if ($('#availability_method').val() != '3' && $('#availability_method').val() != '0') {
				$('#availability_method').val('3');
			}

			$('#availability_method').replaceOptions(methods, $('#availability_method').val());
		}else{
			methods = [
				{ value: '0', text: 'None' }, 
				{ value: '1', text: 'Ping and SNMP Uptime' }, 
				{ value: '2', text: 'SNMP Uptime' }, 
				{ value: '3', text: 'Ping' }, 
				{ value: '4', text: 'Ping or SNMP Uptime' }, 
				{ value: '5', text: 'SNMP Desc' }, 
				{ value: '6', text: 'SNMP GetNext' }
			];

			$('#availability_method').replaceOptions(methods, $('#availability_method').val());
		}

		switch($('#availibility_method').val()) {
			case '0': // availability none
				$('#row_ping_method').hide();
				$('#ping_method').val(0);
				$('#row_ping_timeout').hide();
				$('#row_ping_port').hide();
				$('#row_ping_timeout').hide();
				$('#row_ping_retrie').hide();

				break;
			case '1': // ping and snmp sysUptime
			case '3': // ping
			case '4': // ping or snmp sysUptime
				if (($('#row_ping_method').css('display', 'none')) ||
					($('#row_ping_method').css('display') == undefined)) {
					$('#ping_method').val(ping_method);
					$('#row_ping_method').css('display', '');
				}

				break;
			case '2': // snmp sysUptime
			case '5': // snmp sysDesc
			case '6': // snmp getNext
				$('#row_ping_method').css('display', 'none');
				$('#ping_method').val(0);

				break;
		}

		if ($('#availability_method-button').length) {
			$('#availability_method').selectmenu('refresh');
		}
	}

	function changeHostForm() {
		setSNMP();
		setAvailability();
		setPing();
	}

	function setSNMP() {
		snmp_version = $('#snmp_version').val();
		switch(snmp_version) {
		case '0': // No SNMP
			$('#row_snmp_username').hide();
			$('#row_snmp_password').hide();
			$('#row_snmp_community').hide();
			$('#row_snmp_auth_protocol').hide();
			$('#row_snmp_priv_passphrase').hide();
			$('#row_snmp_priv_protocol').hide();
			$('#row_snmp_context').hide();
			$('#row_snmp_port').hide();
			$('#row_snmp_timeout').hide();
			$('#row_max_oids').hide();
			break;
		case '1': // SNMP v1
		case '2': // SNMP v2c
			$('#row_snmp_username').hide();
			$('#row_snmp_password').hide();
			$('#row_snmp_community').show();
			$('#row_snmp_auth_protocol').hide();
			$('#row_snmp_priv_passphrase').hide();
			$('#row_snmp_priv_protocol').hide();
			$('#row_snmp_context').hide();
			$('#row_snmp_port').show();
			$('#row_snmp_timeout').show();
			$('#row_max_oids').show();
			break;
		case '3': // SNMP v3
			$('#row_snmp_username').show();
			$('#row_snmp_password').show();
			$('#row_snmp_community').hide();
			$('#row_snmp_auth_protocol').show();
			$('#row_snmp_priv_passphrase').show();
			$('#row_snmp_priv_protocol').show();
			$('#row_snmp_context').show();
			$('#row_snmp_port').show();
			$('#row_snmp_timeout').show();
			$('#row_max_oids').show();
			break;
		}
	}

	$(function() {
		changeHostForm();
		$('#dbghide').click(function(data) {
			$('#dqdebug').fadeOut('fast');
		});

		$.get('host.php?action=ping_host&id='+$('#id').val(), function(data) {
			$('#ping_results').html(data);
		});
	});

	-->
	</script>
	<?php 
    if (isset($_REQUEST['display_dq_details']) && isset($_SESSION['debug_log']['data_query'])) {
        print "<table id='dqdebug' width='100%' class='cactiDebugTable' cellpadding='0' cellspacing='0' border='0' align='center'><tr><td>\n";
        print "<table width='100%' class='cactiTableTitle' cellspacing='0' cellpadding='3' border='0'>\n";
        print "<tr><td class='textHeaderDark'><a name='dqdbg'></a><strong>Data Query Debug Information</strong></td><td class='textHeaderDark' align='right'><a style='cursor:pointer;' id='dbghide' class='linkOverDark'>Hide</a></td></tr>\n";
        print "</table>\n";
        print "<table width='100%' class='cactiTable' cellspacing='0' cellpadding='3' border='0'>\n";
        print "<tr><td class='odd'><span style='font-family: monospace;'>" . debug_log_return('data_query') . "</span></td></tr>";
        print "</table>\n";
        print "</table>\n";
    }
    if (!empty($host['id'])) {
        html_start_box('<strong>Associated Graph Templates</strong>', '100%', '', '3', 'center', '');
        html_header(array('Graph Template Name', 'Status'), 2);
        $selected_graph_templates = db_fetch_assoc_prepared('SELECT
			graph_templates.id,
			graph_templates.name
			FROM (graph_templates, host_graph)
			WHERE graph_templates.id = host_graph.graph_template_id
			AND host_graph.host_id = ?
			ORDER BY graph_templates.name', array($_REQUEST['id']));
        $available_graph_templates = db_fetch_assoc('SELECT
			graph_templates.id, graph_templates.name
			FROM snmp_query_graph RIGHT JOIN graph_templates
			ON (snmp_query_graph.graph_template_id = graph_templates.id)
			WHERE (((snmp_query_graph.name) Is Null)) ORDER BY graph_templates.name');
        $i = 0;
        if (sizeof($selected_graph_templates) > 0) {
            foreach ($selected_graph_templates as $item) {
                form_alternate_row('', true);
                /* get status information for this graph template */
                $is_being_graphed = sizeof(db_fetch_assoc_prepared('SELECT id FROM graph_local WHERE graph_template_id = ? AND host_id = ?', array($item['id'], $_REQUEST['id']))) > 0 ? true : false;
                ?>
					<td style="padding: 4px;">
						<strong><?php 
                print $i;
                ?>
)</strong> <?php 
                print htmlspecialchars($item['name']);
                ?>
					</td>
					<td>
						<?php 
                print $is_being_graphed == true ? "<span style='color: green;'>Is Being Graphed</span> (<a href='" . htmlspecialchars('graphs.php?action=graph_edit&id=' . db_fetch_cell_prepared('SELECT id FROM graph_local WHERE graph_template_id = ? AND host_id = ? LIMIT 0,1', array($item['id'], $_REQUEST['id']))) . "'>Edit</a>)" : "<span style='color: #484848;'>Not Being Graphed</span>";
                ?>
					</td>
					<td align='right' nowrap>
						<a href='<?php 
                print htmlspecialchars('host.php?action=gt_remove&id=' . $item['id'] . '&host_id=' . $_REQUEST['id']);
                ?>
'><img src='images/delete_icon_large.gif' title='Delete Graph Template Association' alt='Delete Graph Template Association' border='0' align='middle'></a>
					</td>
				<?php 
                form_end_row();
                $i++;
            }
        } else {
            print "<tr class='tableRow'><td colspan='2'><em>No associated graph templates.</em></td></tr>";
        }
        ?>
		<tr class='odd'>
			<td class='saveRow' colspan="4">
				<table cellspacing="0" cellpadding="1" width="100%">
					<td nowrap>Add Graph Template:&nbsp;
						<?php 
        form_dropdown('graph_template_id', $available_graph_templates, 'name', 'id', '', '', '');
        ?>
					</td>
					<td align="right">
						&nbsp;<input type="submit" value="Add" name="add_gt_x" title="Add Graph Template to Device">
					</td>
				</table>
			</td>
		</tr>

		<?php 
        html_end_box();
        html_start_box('<strong>Associated Data Queries</strong>', '100%', '', '3', 'center', '');
        html_header(array('Data Query Name', 'Debugging', 'Re-Index Method', 'Status'), 2);
        $selected_data_queries = db_fetch_assoc_prepared('SELECT
			snmp_query.id,
			snmp_query.name,
			host_snmp_query.reindex_method
			FROM (snmp_query, host_snmp_query)
			WHERE snmp_query.id = host_snmp_query.snmp_query_id
			AND host_snmp_query.host_id = ?
			ORDER BY snmp_query.name', array($_REQUEST['id']));
        $available_data_queries = db_fetch_assoc('SELECT
			snmp_query.id,
			snmp_query.name
			FROM snmp_query
			ORDER BY snmp_query.name');
        $keeper = array();
        foreach ($available_data_queries as $item) {
            if (sizeof(db_fetch_assoc_prepared('SELECT snmp_query_id FROM host_snmp_query WHERE host_id = ? AND snmp_query_id = ?', array($_REQUEST['id'], $item['id']))) > 0) {
                /* do nothing */
            } else {
                array_push($keeper, $item);
            }
        }
        $available_data_queries = $keeper;
        $i = 0;
        if (sizeof($selected_data_queries) > 0) {
            foreach ($selected_data_queries as $item) {
                form_alternate_row('', true);
                /* get status information for this data query */
                $num_dq_items = sizeof(db_fetch_assoc_prepared('SELECT snmp_index FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ?', array($_REQUEST['id'], $item['id'])));
                $num_dq_rows = sizeof(db_fetch_assoc_prepared('SELECT snmp_index FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ? GROUP BY snmp_index', array($_REQUEST['id'], $item['id'])));
                $status = 'success';
                ?>
					<td style="padding: 4px;">
						<strong><?php 
                print $i;
                ?>
)</strong> <?php 
                print htmlspecialchars($item['name']);
                ?>
					</td>
					<td>
						(<a href="<?php 
                print htmlspecialchars('host.php?action=query_verbose&id=' . $item['id'] . '&host_id=' . $_REQUEST['id']);
                ?>
">Verbose Query</a>)
					</td>
					<td>
					<?php 
                print $reindex_types[$item['reindex_method']];
                ?>
					</td>
					<td>
						<?php 
                print $status == 'success' ? "<span style='color: green;'>Success</span>" : "<span style='color: green;'>Fail</span>";
                ?>
 [<?php 
                print $num_dq_items;
                ?>
 Item<?php 
                print $num_dq_items == 1 ? '' : 's';
                ?>
, <?php 
                print $num_dq_rows;
                ?>
 Row<?php 
                print $num_dq_rows == 1 ? '' : 's';
                ?>
]
					</td>
					<td align='right' nowrap>
						<a href='<?php 
                print htmlspecialchars('host.php?action=query_reload&id=' . $item['id'] . '&host_id=' . $_REQUEST['id']);
                ?>
'><img src='images/reload_icon_small.gif' title='Reload Data Query' alt='Reload Data Query' border='0' align='middle'></a>&nbsp;
						<a href='<?php 
                print htmlspecialchars('host.php?action=query_remove&id=' . $item['id'] . '&host_id=' . $_REQUEST['id']);
                ?>
'><img src='images/delete_icon_large.gif' title='Delete Data Query Association' alt='Delete Data Query Association' border='0' align='middle'></a>
					</td>
				<?php 
                form_end_row();
                $i++;
            }
        } else {
            print "<tr class='tableRow'><td colspan='4'><em>No associated data queries.</em></td></tr>";
        }
        ?>
		<tr class='odd'>
			<td class='saveRow' colspan="5">
				<table cellspacing="0" cellpadding="1" width="100%">
					<td nowrap>Add Data Query:&nbsp;
						<?php 
        form_dropdown('snmp_query_id', $available_data_queries, 'name', 'id', '', '', '');
        ?>
					</td>
					<td nowrap>Re-Index Method:&nbsp;
						<?php 
        form_dropdown('reindex_method', $reindex_types, '', '', read_config_option('reindex_method'), '', '');
        ?>
					</td>
					<td align="right">
						&nbsp;<input type="submit" value="Add" name="add_dq_x" title="Add Data Query to Device">
					</td>
				</table>
				<a name='dqtop'></a>
			</td>
		</tr>

		<?php 
        html_end_box();
    }
    form_save_button('host.php', 'return');
    api_plugin_hook('host_edit_bottom');
}
Example #4
0
function add_host_based_graphs()
{
    global $config, $device_hashes, $device_query_hashes, $device_health_hashes;
    debug('Adding Host Based Graphs');
    /* check for host level graphs next data queries */
    $host_cpu_dq = read_config_option('mikrotik_dq_host_cpu');
    $host_users_dq = mikrotik_data_query_by_hash('ce63249e6cc3d52bc69659a3f32194fe');
    $hosts = db_fetch_assoc("SELECT host_id, host.description, host.hostname \n\t\tFROM plugin_mikrotik_system\n\t\tINNER JOIN host\n\t\tON host.id=plugin_mikrotik_system.host_id\n\t\tWHERE host_status IN(0,3) AND host.disabled=''");
    if (sizeof($hosts)) {
        foreach ($hosts as $h) {
            debug('Processing Host: ' . $h['description'] . ' [' . $h['hostname'] . ']');
            foreach ($device_hashes as $hash) {
                $template = mikrotik_template_by_hash($hash);
                if (!empty($template)) {
                    debug('Processing ' . db_fetch_cell_prepared('SELECT name FROM graph_templates WHERE hash = ?', array($hash)));
                    mikrotik_gt_graph($h['host_id'], $template);
                }
            }
            foreach ($device_query_hashes as $hash) {
                $query = mikrotik_data_query_by_hash($hash);
                if (!empty($query)) {
                    debug('Processing ' . db_fetch_cell_prepared('SELECT name FROM snmp_query WHERE hash = ?', array($hash)));
                    if ($hash == '7dd90372956af1dc8ec7b859a678f227') {
                        $exclusion = read_config_option('mikrotik_user_exclusion');
                        add_host_dq_graphs($h['host_id'], $query, 'userName', $exclusion, false);
                    } else {
                        add_host_dq_graphs($h['host_id'], $query);
                    }
                }
            }
            $health = db_fetch_row_prepared('SELECT * FROM plugin_mikrotik_system_health WHERE host_id = ?', array($h['host_id']));
            debug('Processing Health');
            if (sizeof($health)) {
                foreach ($device_health_hashes as $column => $hash) {
                    if (!empty($health[$column]) && $health[$column] != 'NULL') {
                        $template = mikrotik_template_by_hash($hash);
                        if (!empty($template)) {
                            debug('Processing ' . db_fetch_cell_prepared('SELECT name FROM graph_templates WHERE hash = ?', array($hash)));
                            mikrotik_gt_graph($h['host_id'], $template);
                        }
                    }
                }
            }
        }
    } else {
        debug('No Hosts Found');
    }
}
Example #5
0
function thold_add_graphs_action_execute()
{
    global $config;
    include_once $config['base_path'] . '/plugins/thold/thold_functions.php';
    $host_id = get_filter_request_var('host_id');
    $local_graph_id = get_filter_request_var('local_data_id');
    $thold_template_id = get_filter_request_var('thold_template_id');
    $message = '';
    $template = db_fetch_row_prepared('SELECT * FROM thold_template WHERE id = ?', array($thold_template_id));
    $temp = db_fetch_row_prepared('SELECT dtr.*
		 FROM data_template_rrd AS dtr
		 LEFT JOIN graph_templates_item AS gti
		 ON gti.task_item_id=dtr.id
		 LEFT JOIN graph_local AS gl
		 ON gl.id=gti.local_graph_id
		 WHERE gl.id = ?', array($local_graph_id));
    $data_template_id = $temp['data_template_id'];
    $local_data_id = $temp['local_data_id'];
    $data_source = db_fetch_row_prepared('SELECT * FROM data_local WHERE id = ?', array($local_data_id));
    $data_template_id = $data_source['data_template_id'];
    /* allow duplicate thresholds, but only from differing templates */
    $existing = db_fetch_assoc('SELECT id
		FROM thold_data
		WHERE local_data_id=' . $local_data_id . '
		AND data_template_rrd_id=' . $data_template_id . '
		AND thold_template_id=' . $template['id'] . " AND template_enabled='on'");
    if (count($existing) == 0 && count($template)) {
        if ($local_graph_id) {
            $rrdlookup = db_fetch_cell("SELECT id FROM data_template_rrd WHERE local_data_id={$local_data_id} ORDER BY id LIMIT 1");
            $grapharr = db_fetch_row("SELECT graph_template_id FROM graph_templates_item WHERE task_item_id={$rrdlookup} AND local_graph_id = {$local_graph_id}");
            $desc = db_fetch_cell_prepared('SELECT name_cache FROM data_template_data WHERE local_data_id = ? LIMIT 1', array($local_data_id));
            $data_source_name = $template['data_source_name'];
            $insert = array();
            $name = thold_format_name($template, $local_graph_id, $local_data_id, $data_source_name);
            $insert['name'] = $name;
            $insert['host_id'] = $data_source['host_id'];
            $insert['local_data_id'] = $local_data_id;
            $insert['local_graph_id'] = $local_graph_id;
            $insert['data_template_id'] = $data_template_id;
            $insert['graph_template_id'] = $grapharr['graph_template_id'];
            $insert['thold_hi'] = $template['thold_hi'];
            $insert['thold_low'] = $template['thold_low'];
            $insert['thold_fail_trigger'] = $template['thold_fail_trigger'];
            $insert['thold_enabled'] = $template['thold_enabled'];
            $insert['thold_warning_hi'] = $template['thold_warning_hi'];
            $insert['thold_warning_low'] = $template['thold_warning_low'];
            $insert['thold_warning_fail_trigger'] = $template['thold_warning_fail_trigger'];
            $insert['bl_ref_time_range'] = $template['bl_ref_time_range'];
            $insert['bl_pct_down'] = $template['bl_pct_down'];
            $insert['bl_pct_up'] = $template['bl_pct_up'];
            $insert['bl_fail_trigger'] = $template['bl_fail_trigger'];
            $insert['bl_alert'] = $template['bl_alert'];
            $insert['repeat_alert'] = $template['repeat_alert'];
            $insert['notify_extra'] = $template['notify_extra'];
            $insert['cdef'] = $template['cdef'];
            $insert['thold_template_id'] = $template['id'];
            $insert['template_enabled'] = 'on';
            $rrdlist = db_fetch_assoc("SELECT id, data_input_field_id\n\t\t\t\tFROM data_template_rrd\n\t\t\t\tWHERE local_data_id='{$local_data_id}'\n\t\t\t\tAND data_source_name='{$data_source_name}'");
            $int = array('id', 'data_template_id', 'data_source_id', 'thold_fail_trigger', 'bl_ref_time_range', 'bl_pct_down', 'bl_pct_up', 'bl_fail_trigger', 'bl_alert', 'repeat_alert', 'cdef');
            foreach ($rrdlist as $rrdrow) {
                $data_rrd_id = $rrdrow['id'];
                $insert['data_template_rrd_id'] = $data_rrd_id;
                $existing = db_fetch_assoc("SELECT id\n\t\t\t\t\tFROM thold_data\n\t\t\t\t\tWHERE local_data_id='{$local_data_id}'\n\t\t\t\t\tAND data_template_rrd_id='{$data_rrd_id}'\n\t\t\t\t\tAND thold_template_id='" . $template['id'] . "' AND template_enabled='on'");
                if (count($existing) == 0) {
                    $insert['id'] = 0;
                    $id = sql_save($insert, 'thold_data');
                    if ($id) {
                        thold_template_update_threshold($id, $insert['template']);
                        $l = db_fetch_assoc("SELECT name FROM data_template where id={$data_template_id}");
                        $tname = $l[0]['name'];
                        $name = $data_source_name;
                        if ($rrdrow['data_input_field_id'] != 0) {
                            $l = db_fetch_assoc('SELECT name FROM data_input_fields where id=' . $rrdrow['data_input_field_id']);
                            $name = $l[0]['name'];
                        }
                        plugin_thold_log_changes($id, 'created', " {$tname} [{$name}]");
                        $message .= "Created threshold for the Graph '<i>{$tname}</i>' using the Data Source '<i>{$name}</i>'<br>";
                    }
                }
            }
        }
    }
    if (strlen($message)) {
        $_SESSION['thold_message'] = "<font size=-2>{$message}</font>";
    } else {
        $_SESSION['thold_message'] = "<font size=-2>" . __('Threshold(s) Already Exists - No Thresholds Created') . "</font>";
    }
    raise_message('thold_message');
    if (isset($_SESSION['graph_return'])) {
        $return_to = $_SESSION['graph_return'];
        unset($_SESSION['graph_return']);
        kill_session_var('graph_return');
        header('Location: ' . $return_to . (strpos($return_to, '?') !== false ? '&' : '?') . 'header=false');
    } else {
        header('Location:' . $config['url_path'] . 'plugins/thold/thold.php?header=false');
    }
}
Example #6
0
function boost_rrdtool_function_create($local_data_id, $initial_time, $show_source)
{
    global $config;
    include $config['include_path'] . '/global_arrays.php';
    $data_source_path = get_data_source_path($local_data_id, true);
    /* ok, if that passes lets check to make sure an rra does not already
    	exist, the last thing we want to do is overright data! */
    if ($show_source != true) {
        if (file_exists($data_source_path) == true) {
            return -1;
        }
    }
    /* the first thing we must do is make sure there is at least one
    	rra associated with this data source... *
    	UPDATE: As of version 0.6.6, we are splitting this up into two
    	SQL strings because of the multiple DS per RRD support. This is
    	not a big deal however since this function gets called once per
    	data source */
    $rras = db_fetch_assoc_prepared('SELECT
		data_template_data.rrd_step,
		rra.x_files_factor,
		rra.steps,
		rra.rows,
		rra_cf.consolidation_function_id,
		(rra.rows * rra.steps) AS rra_order
		FROM data_template_data
		LEFT JOIN data_template_data_rra ON (data_template_data.id = data_template_data_rra.data_template_data_id)
		LEFT JOIN rra ON (data_template_data_rra.rra_id = rra.id)
		LEFT JOIN rra_cf ON (rra.id = rra_cf.rra_id)
		WHERE data_template_data.local_data_id = ?
		AND (rra.steps is not null OR rra.rows is not null)
		ORDER BY rra_cf.consolidation_function_id, rra_order', array($local_data_id));
    /* if we find that this DS has no RRA associated; get out.  This would
     * indicate that a data sources has been deleted
     */
    if (sizeof($rras) <= 0) {
        return false;
    }
    /* back off the initial time to allow updates */
    $initial_time -= 300;
    /* create the "--step" line */
    $create_ds = RRD_NL . '--start ' . $initial_time . ' --step ' . $rras[0]['rrd_step'] . ' ' . RRD_NL;
    /* query the data sources to be used in this .rrd file */
    $data_sources = db_fetch_assoc_prepared('SELECT
		data_template_rrd.id,
		data_template_rrd.rrd_heartbeat,
		data_template_rrd.rrd_minimum,
		data_template_rrd.rrd_maximum,
		data_template_rrd.data_source_type_id
		FROM data_template_rrd
		WHERE data_template_rrd.local_data_id = ?
		ORDER BY local_data_template_rrd_id', array($local_data_id));
    /* ONLY make a new DS entry if:
    	- There is multiple data sources and this item is not the main one.
    	- There is only one data source (then use it) */
    if (sizeof($data_sources) > 0) {
        foreach ($data_sources as $data_source) {
            /* use the cacti ds name by default or the user defined one, if entered */
            $data_source_name = get_data_source_item_name($data_source['id']);
            if (empty($data_source['rrd_maximum'])) {
                /* in case no maximum is given, use "Undef" value */
                $data_source['rrd_maximum'] = 'U';
            } elseif (strpos($data_source['rrd_maximum'], '|query_') !== false) {
                $data_local = db_fetch_row_prepared('SELECT * FROM data_local WHERE id = ?', array($local_data_id));
                if ($data_source['rrd_maximum'] == '|query_ifSpeed|' || $data_source['rrd_maximum'] == '|query_ifHighSpeed|') {
                    $highSpeed = db_fetch_cell_prepared("SELECT field_value\n\t\t\t\t\tFROM host_snmp_cache\n\t\t\t\t\tWHERE host_id = ?\n\t\t\t\t\tAND snmp_query_id = ?\n\t\t\t\t\tAND snmp_index = ?\n\t\t\t\t\tAND field_name = 'ifHighSpeed'", array($data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index']));
                    if (!empty($highSpeed)) {
                        $data_source['rrd_maximum'] = $highSpeed * 1000000;
                    } else {
                        $data_source['rrd_maximum'] = substitute_snmp_query_data('|query_ifSpeed|', $data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index']);
                    }
                } else {
                    $data_source['rrd_maximum'] = substitute_snmp_query_data($data_source['rrd_maximum'], $data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index']);
                }
            } elseif ($data_source['rrd_maximum'] != 'U' && (int) $data_source['rrd_maximum'] <= (int) $data_source['rrd_minimum']) {
                /* max > min required, but take care of an "Undef" value */
                $data_source['rrd_maximum'] = (int) $data_source['rrd_minimum'] + 1;
            }
            /* min==max==0 won't work with rrdtool */
            if ($data_source['rrd_minimum'] == 0 && $data_source['rrd_maximum'] == 0) {
                $data_source['rrd_maximum'] = 'U';
            }
            $create_ds .= "DS:{$data_source_name}:" . $data_source_types[$data_source['data_source_type_id']] . ':' . $data_source['rrd_heartbeat'] . ':' . $data_source['rrd_minimum'] . ':' . $data_source['rrd_maximum'] . RRD_NL;
        }
    }
    $create_rra = '';
    /* loop through each available RRA for this DS */
    foreach ($rras as $rra) {
        $create_rra .= 'RRA:' . $consolidation_functions[$rra['consolidation_function_id']] . ':' . $rra['x_files_factor'] . ':' . $rra['steps'] . ':' . $rra['rows'] . RRD_NL;
    }
    /* check for structured path configuration, if in place verify directory
    	   exists and if not create it.
    	 */
    if (read_config_option('extended_paths') == 'on') {
        if (!is_dir(dirname($data_source_path))) {
            if (mkdir(dirname($data_source_path), 0775)) {
                if ($config['cacti_server_os'] != 'win32') {
                    $owner_id = fileowner($config['rra_path']);
                    $group_id = filegroup($config['rra_path']);
                    if (chown(dirname($data_source_path), $owner_id) && chgrp(dirname($data_source_path), $group_id)) {
                        /* permissions set ok */
                    } else {
                        cacti_log("ERROR: Unable to set directory permissions for '" . dirname($data_source_path) . "'", false);
                    }
                }
            } else {
                cacti_log("ERROR: Unable to create directory '" . dirname($data_source_path) . "'", false);
            }
        }
    }
    if ($show_source == true) {
        return read_config_option('path_rrdtool') . ' create' . RRD_NL . "{$data_source_path}{$create_ds}{$create_rra}";
    } else {
        return boost_rrdtool_execute("create {$data_source_path} {$create_ds}{$create_rra}", false, RRDTOOL_OUTPUT_STDOUT);
    }
}
Example #7
0
function settings()
{
    global $tabs_graphs, $settings_graphs, $current_user, $graph_views, $current_user;
    /* you cannot have per-user graph settings if cacti's user management is not turned on */
    if (read_config_option('auth_method') == 0) {
        raise_message(6);
        display_output_messages();
        return;
    }
    if ($_REQUEST['action'] == 'edit') {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $timespan_sel_pos = strpos($_SERVER['HTTP_REFERER'], '&predefined_timespan');
            if ($timespan_sel_pos) {
                $_SERVER['HTTP_REFERER'] = substr($_SERVER['HTTP_REFERER'], 0, $timespan_sel_pos);
            }
        }
        $_SESSION['profile_referer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'graph_view.php';
    }
    print "<form method='post' action='auth_profile.php'>\n";
    html_start_box('<strong>User Settings</strong>', '100%', '', '3', 'center', '');
    $current_user = db_fetch_row_prepared('SELECT * FROM user_auth WHERE id = ?', array($_SESSION['sess_user_id']));
    if (!sizeof($current_user)) {
        return;
    }
    /* file: user_admin.php, action: user_edit (host) */
    $fields_user = array('username' => array('method' => 'value', 'friendly_name' => 'User Name', 'description' => 'The login name for this user.', 'value' => '|arg1:username|', 'max_length' => '40', 'size' => '40'), 'full_name' => array('method' => 'textbox', 'friendly_name' => 'Full Name', 'description' => 'A more descriptive name for this user, that can include spaces or special characters.', 'value' => '|arg1:full_name|', 'max_length' => '120', 'size' => '60'), 'email_address' => array('method' => 'textbox', 'friendly_name' => 'E-Mail Address', 'description' => 'An E-Mail Address you be reached at.', 'value' => '|arg1:email_address|', 'max_length' => '60', 'size' => '60'));
    draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => inject_form_variables($fields_user, isset($current_user) ? $current_user : array())));
    html_end_box();
    if (is_view_allowed('graph_settings') == true) {
        if (read_config_option('auth_method') != 0) {
            $settings_graphs['tree']['default_tree_id']['sql'] = get_graph_tree_array(true);
        }
        html_start_box('<strong>Graph Settings</strong>', '100%', '', '3', 'center', '');
        while (list($tab_short_name, $tab_fields) = each($settings_graphs)) {
            $collapsible = true;
            print "<tr class='spacer tableHeader" . ($collapsible ? ' collapsible' : '') . "' id='row_{$tab_short_name}'><td colspan='2' style='cursor:pointer;' class='tableSubHeaderColumn'>" . $tabs_graphs[$tab_short_name] . ($collapsible ? "<div style='float:right;padding-right:4px;'><i class='fa fa-angle-double-up'></i></div>" : "") . "</td></tr>\n";
            $form_array = array();
            while (list($field_name, $field_array) = each($tab_fields)) {
                $form_array += array($field_name => $tab_fields[$field_name]);
                if (isset($field_array['items']) && is_array($field_array['items'])) {
                    while (list($sub_field_name, $sub_field_array) = each($field_array['items'])) {
                        if (graph_config_value_exists($sub_field_name, $_SESSION['sess_user_id'])) {
                            $form_array[$field_name]['items'][$sub_field_name]['form_id'] = 1;
                        }
                        $form_array[$field_name]['items'][$sub_field_name]['value'] = db_fetch_cell_prepared('SELECT value FROM settings_graphs WHERE name = ? AND user_id = ?', array($sub_field_name, $_SESSION['sess_user_id']));
                    }
                } else {
                    if (graph_config_value_exists($field_name, $_SESSION['sess_user_id'])) {
                        $form_array[$field_name]['form_id'] = 1;
                    }
                    $form_array[$field_name]['value'] = db_fetch_cell_prepared('SELECT value FROM settings_graphs WHERE name = ? AND user_id = ?', array($field_name, $_SESSION['sess_user_id']));
                }
            }
            draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array));
        }
        html_end_box();
    }
    ?>
	<script type="text/javascript">
	<!--
	var themeFonts=<?php 
    print read_config_option('font_method');
    ?>
;

	function graphSettings() {
		if (themeFonts == 1) {
				$('#row_fonts').hide();
				$('#row_custom_fonts').hide();
				$('#row_title_size').hide();
				$('#row_title_font').hide();
				$('#row_legend_size').hide();
				$('#row_legend_font').hide();
				$('#row_axis_size').hide();
				$('#row_axis_font').hide();
				$('#row_unit_size').hide();
				$('#row_unit_font').hide();
		}else{
			var custom_fonts = $('#custom_fonts').is(':checked');

			switch(custom_fonts) {
			case true:
				$('#row_fonts').show();
				$('#row_title_size').show();
				$('#row_title_font').show();
				$('#row_legend_size').show();
				$('#row_legend_font').show();
				$('#row_axis_size').show();
				$('#row_axis_font').show();
				$('#row_unit_size').show();
				$('#row_unit_font').show();
				break;
			case false:
				$('#row_fonts').show();
				$('#row_title_size').hide();
				$('#row_title_font').hide();
				$('#row_legend_size').hide();
				$('#row_legend_font').hide();
				$('#row_axis_size').hide();
				$('#row_axis_font').hide();
				$('#row_unit_size').hide();
				$('#row_unit_font').hide();
				break;
			}
		}

		if ($('#timespan_sel').is(':checked')) {
			$('#row_default_rra_id').hide();
			$('#row_default_timespan').show();
			$('#row_default_timeshift').show();
			$('#row_allow_graph_dates_in_future').show();
			$('#row_first_weekdayid').show();
			$('#row_day_shift_start').show();
			$('#row_day_shift_end').show();
		} else {
			$('#row_default_rra_id').show();
			$('#row_default_timespan').hide();
			$('#row_default_timeshift').hide();
			$('#row_allow_graph_dates_in_future').hide();
			$('#row_first_weekdayid').hide();
			$('#row_day_shift_start').hide();
			$('#row_day_shift_end').hide();
		}
	}

	$(function() {
		graphSettings();

		$('#navigation').show();
		$('#navigation_right').show();

		$('input[value="Save"]').unbind().click(function(event) {
			event.preventDefault();
			href='<?php 
    print $_SERVER['HTTP_REFERER'];
    ?>
';
			href=href+(href.indexOf('?') > 0 ? '&':'?')+'header=false';
			$.post('auth_profile.php?header=false', $('input, select, textarea').serialize()).done(function(data) {
				$.get('auth_profile.php?action=noreturn&header=false', function(data) {
					$('#main').html(data);
					applySkin();
				});
			});
		});

		$('input[value="Return"]').unbind().click(function(event) {
			console.log('The refer is:<?php 
    print $_SESSION['profile_referer'];
    ?>
');
			document.location = '<?php 
    print $_SESSION['profile_referer'];
    ?>
';
		});

		$('#timespan_sel').change(function() {
			graphSettings();
		});
	});

	-->
	</script>
	<?php 
    form_hidden_box('save_component_graph_config', '1', '');
    form_save_buttons(array(array('id' => 'return', 'value' => 'Return'), array('id' => 'save', 'value' => 'Save')));
}
Example #8
0
function mactrack_snmp_remove()
{
    /* ================= input validation ================= */
    get_filter_request_var('id');
    /* ==================================================== */
    if (read_config_option('deletion_verification') == 'on' && !isset_request_var('confirm')) {
        general_header();
        form_confirm(__('Are You Sure?'), __('Are you sure you want to delete the SNMP Option Set(s) %s?', db_fetch_cell_prepared('SELECT name FROM mactrack WHERE id = ?', array(get_request_var('id')))), 'mactrack_snmp.php', 'mactrack_snmp.php?action=remove&id=' . get_request_var('id'));
        bottom_footer();
        exit;
    }
    if (read_config_option('deletion_verification') == '' || isset_request_var('confirm')) {
        db_execute_prepared('DELETE FROM mac_track_snmp_items WHERE snmp_id = ?', array(get_request_var('id')));
        db_execute_prepared('DELETE FROM mac_track_snmp WHERE id = ?', array(get_request_var('id')));
    }
}
Example #9
0
function api_reapply_suggested_data_source_title($local_data_id)
{
    global $config;
    $data_template_data_id = db_fetch_cell_prepared('SELECT id FROM data_template_data WHERE local_data_id = ?', array($local_data_id));
    if (empty($data_template_data_id)) {
        return;
    }
    /* require query type data sources only (snmp_query_id > 0) */
    $data_local = db_fetch_row_prepared('SELECT id, host_id, data_template_id, snmp_query_id, snmp_index FROM data_local WHERE snmp_query_id > 0 AND id = ?', array($local_data_id));
    /* if this is not a data query graph, simply return */
    if (!isset($data_local['host_id'])) {
        return;
    }
    $snmp_query_graph_id = db_fetch_cell_prepared("SELECT \n\t\tdata_input_data.value FROM data_input_data \n\t\tJOIN data_input_fields ON (data_input_data.data_input_field_id = data_input_fields.id) \n\t\tJOIN data_template_data ON (data_template_data.id = data_input_data.data_template_data_id) \n\t\tWHERE data_input_fields.type_code = 'output_type' \n\t\tAND data_template_data.local_data_id = ?", array($data_local['id']));
    /* no snmp query graph id found */
    if ($snmp_query_graph_id == 0) {
        return;
    }
    $suggested_values = db_fetch_assoc_prepared("SELECT \n\t\ttext, \n\t\tfield_name \n\t\tFROM snmp_query_graph_rrd_sv \n\t\tWHERE snmp_query_graph_id = ?\n\t\tAND data_template_id = ?\n\t\tAND field_name = 'name'\n\t\tORDER BY sequence", array($snmp_query_graph_id, $data_local['data_template_id']));
    $suggested_values_data = array();
    if (sizeof($suggested_values) > 0) {
        foreach ($suggested_values as $suggested_value) {
            if (!isset($suggested_values_data[$suggested_value['field_name']])) {
                $subs_string = substitute_snmp_query_data($suggested_value['text'], $data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index'], read_config_option('max_data_query_field_length'));
                /* if there are no '|query' characters, all of the substitutions were successful */
                if (!substr_count($subs_string, '|query')) {
                    db_execute_prepared('UPDATE data_template_data SET ' . $suggested_value['field_name'] . ' = ? WHERE local_data_id = ?', array($suggested_value['text'], $local_data_id));
                    /* once we find a working value for that very field, stop */
                    $suggested_values_data[$suggested_value['field_name']] = true;
                }
            }
        }
    }
}
Example #10
0
function thold_edit()
{
    global $config;
    if (isset_request_var('id')) {
        $thold_data = db_fetch_row_prepared('SELECT * 
			FROM thold_data 
			WHERE id = ?', array(get_request_var('id')));
    } elseif (isset_request_var('local_data_id') && isset_request_var('local_graph_id') && isset_request_var('host_id') && isset_request_var('data_template_id') && isset_request_var('data_template_rrd_id')) {
        $thold_data['id'] = '0';
        $thold_data['local_data_id'] = get_filter_request_var('local_data_id');
        $thold_data['local_graph_id'] = get_filter_request_var('local_graph_id');
        $thold_data['data_template_id'] = get_filter_request_var('data_template_id');
        $thold_data['host_id'] = get_filter_request_var('host_id');
        $thold_data['data_template_rrd_id'] = get_filter_request_var('data_template_rrd_id');
        $thold_data['thold_template_id'] = get_filter_request_var('thold_template_id');
    } else {
        exit;
    }
    $desc = db_fetch_cell_prepared('SELECT name_cache 
		FROM data_template_data 
		WHERE local_data_id = ? 
		LIMIT 1', array($thold_data['local_data_id']));
    $rrdsql = array_rekey(db_fetch_assoc_prepared("SELECT id \n\t\tFROM data_template_rrd \n\t\tWHERE local_data_id = ? ORDER BY id", array($thold_data['local_data_id'])), 'id', 'id');
    $grapharr = db_fetch_assoc('SELECT DISTINCT local_graph_id 
		FROM graph_templates_item 
		WHERE task_item_id IN (' . implode(', ', $rrdsql) . ') AND graph_template_id>0');
    if (empty($thold_data['local_graph_id'])) {
        $thold_data['local_graph_id'] = db_fetch_cell_prepared('SELECT gl.id
			FROM graph_local AS gl
			INNER JOIN graph_templates_item AS gti
			ON gl.id=gti.local_graph_id
			INNER JOIN data_template_rrd AS dtr
			ON gti.task_item_id=dtr.id
			WHERE dtr.local_data_id = ?
			LIMIT 1', array($thold_data['local_data_id']));
    }
    if (empty($thold_data['data_template_rrd_id'])) {
        $thold_data['data_template_rrd_id'] = db_fetch_cell_prepared('SELECT id
			FROM data_template_rrd AS dtr
			WHERE local_data_id = ? 
			LIMIT 1', array($thold_data['local_data_id']));
    }
    $dt_sql = 'SELECT DISTINCT dtr.local_data_id
		FROM data_template_rrd AS dtr
		LEFT JOIN graph_templates_item AS gti
		ON gti.task_item_id=dtr.id
		LEFT JOIN graph_local AS gl
		ON gl.id=gti.local_graph_id
		WHERE gl.id=' . $thold_data['local_graph_id'];
    $template_data_rrds = db_fetch_assoc("SELECT td.id AS thold_id, dtr.id, dtr.data_source_name, dtr.local_data_id \n\t\tFROM data_template_rrd AS dtr\n\t\tLEFT JOIN thold_data AS td\n\t\tON dtr.id=td.data_template_rrd_id\n\t\tWHERE dtr.local_data_id IN ({$dt_sql}) \n\t\tORDER BY dtr.id");
    form_start('thold.php', 'thold');
    html_start_box(__('Graph Data'), '100%', '', '3', 'center', '');
    ?>
	<tr>
		<td class='textArea'>
			<?php 
    if (isset($banner)) {
        echo $banner . '<br><br>';
    }
    ?>
			<?php 
    print __('Data Source Description:');
    ?>
 <br><?php 
    echo $desc;
    ?>
<br><br>
			<?php 
    print __('Associated Graph (graphs that use this RRD):');
    ?>
 <br>
			<select name='element'>
				<?php 
    foreach ($grapharr as $g) {
        $graph_desc = db_fetch_row_prepared('SELECT local_graph_id, title, title_cache
						FROM graph_templates_graph
						WHERE local_graph_id = ?', array($g['local_graph_id']));
        echo "<option value='" . $graph_desc['local_graph_id'] . "'";
        if ($graph_desc['local_graph_id'] == $thold_data['local_graph_id']) {
            echo ' selected';
        }
        echo '>' . $graph_desc['local_graph_id'] . ' - ' . $graph_desc['title_cache'] . " </option>\n";
    }
    ?>
			</select>
			<br>
			<br>
		</td>
		<td class='textArea'>
			<img id='graphimage' src='<?php 
    echo htmlspecialchars($config['url_path'] . 'graph_image.php?local_graph_id=' . $thold_data['local_graph_id'] . '&rra_id=0&graph_start=-32400&graph_height=140&graph_width=500');
    ?>
'>
		</td>
	</tr>
	<?php 
    html_end_box();
    $template_rrd = db_fetch_row_prepared('SELECT * 
		FROM data_template_rrd 
		WHERE id = ?', array($thold_data['data_template_rrd_id']));
    //-----------------------------
    // Tabs (if more than one item)
    //-----------------------------
    $i = 0;
    $ds = 0;
    if (isset($template_data_rrds)) {
        if (sizeof($template_data_rrds)) {
            /* draw the data source tabs on the top of the page */
            print "<br><div class='tabs'><nav><ul>\n";
            foreach ($template_data_rrds as $template_data_rrd) {
                if ($template_data_rrd['id'] == $thold_data['data_template_rrd_id']) {
                    $ds = $template_data_rrd['data_source_name'];
                }
                if (!empty($template_data_rrd['thold_id'])) {
                    $td = db_fetch_row('SELECT * 
						FROM thold_data 
						WHERE id=' . $template_data_rrd['thold_id']);
                } else {
                    $td = array();
                }
                $cur_setting = '';
                if (!sizeof($td)) {
                    $cur_setting .= "<span style='padding-right:4px;'>" . __('N/A') . "</span>";
                } else {
                    $cur_setting = '<span style="padding-right:4px;">' . __('Last:') . '</span>' . ($td['lastread'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceDown'>" . thold_format_number($td['lastread'], 4) . "</span>");
                    if ($td['thold_type'] != 1) {
                        if ($td['thold_warning_fail_trigger'] != 0) {
                            if ($td['thold_warning_hi'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('WHi:') . '</span>' . ($td['thold_warning_hi'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_warning_hi'], 2) . '</span>');
                            }
                            if ($td['thold_warning_low'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('WLo:') . '</span>' . ($td['thold_warning_low'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_warning_low'], 2) . '</span>');
                            }
                        }
                        if ($td['thold_fail_trigger'] != 0) {
                            if ($td['thold_hi'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('AHi:') . '</span>' . ($td['thold_hi'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_hi'], 2) . '</span>');
                            }
                            if ($td['thold_low'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('ALo:') . '</span>' . ($td['thold_low'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_low'], 2) . '</span>');
                            }
                        }
                    } else {
                        $cur_setting .= '<span style="padding:4px">' . __('AHi:') . '</span>' . ($td['thold_hi'] == '' ? "<span>" . __('N/A') . "</span>" : "<span clas='deviceRecovering'>" . thold_format_number($td['thold_hi'], 2) . '</span>');
                        $cur_setting .= '<span style="padding:4px">' . __('ALo:') . '</span>' . ($td['thold_low'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_low'], 2) . '</span>');
                        $cur_setting .= '<span>' . __('BL: (Up %s %/Down %s %)', $td['bl_pct_up'], $td['bl_pct_down']) . '</span>';
                    }
                }
                if ($template_data_rrd['id'] == $thold_data['data_template_rrd_id']) {
                    $selected = 'selected';
                } else {
                    $selected = '';
                }
                if (!empty($template_data_rrd['thold_id'])) {
                    echo "<li class='textEditTitle'><a class='hyperLink {$selected}' href='" . htmlspecialchars('thold.php?action=edit&id=' . $template_data_rrd['thold_id']) . "'>" . $template_data_rrd['data_source_name'] . '<br>' . $cur_setting . '</a></li>';
                } else {
                    echo "<li class='textEditTitle'><a class='hyperLink {$selected}' href='" . htmlspecialchars('thold.php?action=edit&local_data_id=' . $template_data_rrd['local_data_id'] . '&data_template_rrd_id=' . $template_data_rrd['id']) . '&local_graph_id=' . $thold_data['local_graph_id'] . '&host_id=' . $thold_data['host_id'] . '&data_template_id=' . $thold_data['data_template_id'] . '&thold_template_id=0' . "'>" . $template_data_rrd['data_source_name'] . '<br>' . $cur_setting . '</a></li>';
                }
            }
            echo "<li class='textEditTitle'><a class='hyperLink' href='" . htmlspecialchars('thold.php?action=add' . '&local_graph_id=' . $thold_data['local_graph_id'] . '&host_id=' . $thold_data['host_id']) . "'>new thold<br>n/a</a></li>";
            print "</ul></nav></div>\n";
        } elseif (sizeof($template_data_rrds) == 1) {
            set_request_var('data_template_rrd_id', $template_data_rrds[0]['id']);
        }
    }
    //----------------------
    // Data Source Item Form
    //----------------------
    $thold_data_cdef = isset($thold_data['cdef']) ? $thold_data['cdef'] : 0;
    if (isset($thold_data['template'])) {
        $thold_data['template_name'] = db_fetch_cell_prepared('SELECT name 
			FROM thold_template 
			WHERE id = ?', array($thold_data['thold_template_id']));
    }
    $header_text = __('Data Source Item [%s] ' . ' - Current value: [%s]', isset($template_rrd) ? $template_rrd['data_source_name'] : '', get_current_value($thold_data['local_data_id'], $ds, $thold_data_cdef));
    html_start_box($header_text, '100%', '', '3', 'center', '');
    $send_notification_array = array();
    $users = db_fetch_assoc("SELECT plugin_thold_contacts.id, plugin_thold_contacts.data,\n\t\tplugin_thold_contacts.type, user_auth.full_name\n\t\tFROM plugin_thold_contacts, user_auth\n\t\tWHERE user_auth.id=plugin_thold_contacts.user_id\n\t\tAND plugin_thold_contacts.data!=''\n\t\tORDER BY user_auth.full_name ASC, plugin_thold_contacts.type ASC");
    if (!empty($users)) {
        foreach ($users as $user) {
            $send_notification_array[$user['id']] = $user['full_name'] . ' - ' . ucfirst($user['type']);
        }
    }
    if (isset($thold_data['id'])) {
        $sql = 'SELECT contact_id as id FROM plugin_thold_threshold_contact WHERE thold_id=' . $thold_data['id'];
        $step = db_fetch_cell('SELECT rrd_step FROM data_template_data WHERE local_data_id = ' . $thold_data['local_data_id'], FALSE);
    } else {
        $sql = 'SELECT contact_id as id FROM plugin_thold_threshold_contact WHERE thold_id=0';
        $step = db_fetch_cell('SELECT rrd_step FROM data_template_data WHERE local_data_id = ' . $thold_data['local_data_id'], FALSE);
    }
    include $config['base_path'] . '/plugins/thold/includes/arrays.php';
    $data_fields = array();
    $reference_types = get_reference_types($thold_data['local_data_id'], $step, $timearray);
    $temp = db_fetch_assoc('SELECT id, local_data_template_rrd_id, data_source_name, data_input_field_id
		FROM data_template_rrd
		WHERE local_data_id=' . $thold_data['local_data_id']);
    foreach ($temp as $d) {
        if ($d['data_input_field_id'] != 0) {
            $name = db_fetch_cell('SELECT name FROM data_input_fields WHERE id=' . $d['data_input_field_id']);
        } else {
            $name = $d['data_source_name'];
        }
        if ($d['id'] != $thold_data['data_template_rrd_id']) {
            $data_fields[$d['data_source_name']] = $name;
        }
    }
    $replacements = db_fetch_assoc_prepared('SELECT DISTINCT field_name
		FROM data_local AS dl
		INNER JOIN host_snmp_cache AS hsc
		ON dl.snmp_query_id=hsc.snmp_query_id
		AND dl.host_id=hsc.host_id
		WHERE dl.id = ?', array($thold_data['data_template_id']));
    $nr = array();
    if (sizeof($replacements)) {
        foreach ($replacements as $r) {
            $nr[] = "<span class='deviceUp'>|query_" . $r['field_name'] . "|</span>";
        }
    }
    $vhf = explode('|', trim(VALID_HOST_FIELDS, '()'));
    if (sizeof($vhf)) {
        foreach ($vhf as $r) {
            $nr[] = "<span class='deviceUp'>|" . $r . "|</span>";
        }
    }
    $replacements = "<br>" . __('Replacement Fields: %s', implode(", ", $nr));
    $dss = db_fetch_assoc_prepared('SELECT data_source_name FROM data_template_rrd WHERE local_data_id = ?', array($thold_data['local_data_id']));
    if (sizeof($dss)) {
        foreach ($dss as $ds) {
            $dsname[] = "<span class='deviceUp'>|ds:" . $ds["data_source_name"] . "|</span>";
        }
    }
    $datasources = "<br>" . __('Data Sources: %s', implode(", ", $dsname));
    $form_array = array('template_header' => array('friendly_name' => __('Template Settings'), 'method' => 'spacer'), 'template_enabled' => array('friendly_name' => __('Template Propagation Enabled'), 'method' => 'checkbox', 'default' => '', 'description' => __('Whether or not these settings will be propagates from the threshold template.'), 'value' => !empty($thold_data['template_enabled']) ? $thold_data['template_enabled'] : ''), 'template_name' => array('friendly_name' => __('Template Name'), 'method' => 'custom', 'default' => '', 'description' => __('Name of the Threshold Template the threshold was created from.'), 'value' => isset($thold_data['template_name']) ? $thold_data['template_name'] : 'N/A'), 'general_header' => array('friendly_name' => __('General Settings'), 'method' => 'spacer'), 'name' => array('friendly_name' => __('Threshold Name'), 'method' => 'textbox', 'max_length' => 100, 'size' => '70', 'default' => $desc . ' [' . $template_rrd['data_source_name'] . ']', 'description' => __('Provide the Thresholds a meaningful name'), 'value' => isset($thold_data['name']) ? $thold_data['name'] : ''), 'thold_enabled' => array('friendly_name' => __('Threshold Enabled'), 'method' => 'checkbox', 'default' => 'on', 'description' => __('Whether or not this threshold will be checked and alerted upon.'), 'value' => isset($thold_data['thold_enabled']) ? $thold_data['thold_enabled'] : ''), 'exempt' => array('friendly_name' => __('Weekend Exemption'), 'description' => __('If this is checked, this Threshold will not alert on weekends.'), 'method' => 'checkbox', 'default' => '', 'value' => isset($thold_data['exempt']) ? $thold_data['exempt'] : ''), 'restored_alert' => array('friendly_name' => __('Disable Restoration Email'), 'description' => __('If this is checked, Thold will not send an alert when the threshold has returned to normal status.'), 'method' => 'checkbox', 'default' => '', 'value' => isset($thold_data['restored_alert']) ? $thold_data['restored_alert'] : ''), 'thold_type' => array('friendly_name' => __('Threshold Type'), 'method' => 'drop_array', 'on_change' => 'changeTholdType()', 'array' => $thold_types, 'default' => read_config_option('thold_type'), 'description' => __('The type of Threshold that will be monitored.'), 'value' => isset($thold_data['thold_type']) ? $thold_data['thold_type'] : ''), 'repeat_alert' => array('friendly_name' => __('Re-Alert Cycle'), 'method' => 'drop_array', 'array' => $repeatarray, 'default' => read_config_option('alert_repeat'), 'description' => __('Repeat alert after this amount of time has pasted since the last alert.'), 'value' => isset($thold_data['repeat_alert']) ? $thold_data['repeat_alert'] : ''), 'thold_warning_header' => array('friendly_name' => __('Warning - High / Low Settings'), 'method' => 'spacer'), 'thold_warning_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, warning will be triggered'), 'value' => isset($thold_data['thold_warning_hi']) ? $thold_data['thold_warning_hi'] : ''), 'thold_warning_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, warning will be triggered'), 'value' => isset($thold_data['thold_warning_low']) ? $thold_data['thold_warning_low'] : ''), 'thold_warning_fail_trigger' => array('friendly_name' => __('Breach Duration'), 'method' => 'drop_array', 'array' => $alertarray, 'description' => __('The amount of time the data source must be in breach of the threshold for a warning to be raised.'), 'value' => isset($thold_data['thold_warning_fail_trigger']) ? $thold_data['thold_warning_fail_trigger'] : read_config_option('alert_trigger')), 'thold_header' => array('friendly_name' => __('Alert - High / Low Settings'), 'method' => 'spacer'), 'thold_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, alert will be triggered'), 'value' => isset($thold_data['thold_hi']) ? $thold_data['thold_hi'] : ''), 'thold_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, alert will be triggered'), 'value' => isset($thold_data['thold_low']) ? $thold_data['thold_low'] : ''), 'thold_fail_trigger' => array('friendly_name' => __('Breach Duration'), 'method' => 'drop_array', 'array' => $alertarray, 'description' => __('The amount of time the data source must be in breach of the threshold for an alert to be raised.'), 'value' => isset($thold_data['thold_fail_trigger']) ? $thold_data['thold_fail_trigger'] : read_config_option('alert_trigger')), 'time_warning_header' => array('friendly_name' => __('Warning - Time Based Settings'), 'method' => 'spacer'), 'time_warning_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, warning will be triggered'), 'value' => isset($thold_data['time_warning_hi']) ? $thold_data['time_warning_hi'] : ''), 'time_warning_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, warning will be triggered'), 'value' => isset($thold_data['time_warning_low']) ? $thold_data['time_warning_low'] : ''), 'time_warning_fail_trigger' => array('friendly_name' => __('Breach Count'), 'method' => 'textbox', 'max_length' => 5, 'size' => 10, 'description' => __('The number of times the data source must be in breach of the threshold.'), 'value' => isset($thold_data['time_warning_fail_trigger']) ? $thold_data['time_warning_fail_trigger'] : read_config_option('thold_warning_time_fail_trigger')), 'time_warning_fail_length' => array('friendly_name' => __('Breach Window'), 'method' => 'drop_array', 'array' => $timearray, 'description' => __('The amount of time in the past to check for threshold breaches.'), 'value' => isset($thold_data['time_warning_fail_length']) ? $thold_data['time_warning_fail_length'] : (read_config_option('thold_warning_time_fail_length') > 0 ? read_config_option('thold_warning_time_fail_length') : 1)), 'time_header' => array('friendly_name' => __('Alert - Time Based Settings'), 'method' => 'spacer'), 'time_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, alert will be triggered'), 'value' => isset($thold_data['time_hi']) ? $thold_data['time_hi'] : ''), 'time_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, alert will be triggered'), 'value' => isset($thold_data['time_low']) ? $thold_data['time_low'] : ''), 'time_fail_trigger' => array('friendly_name' => __('Breach Count'), 'method' => 'textbox', 'max_length' => 5, 'size' => 10, 'default' => read_config_option('thold_time_fail_trigger'), 'description' => __('The number of times the data source must be in breach of the threshold.'), 'value' => isset($thold_data['time_fail_trigger']) ? $thold_data['time_fail_trigger'] : read_config_option('thold_time_fail_trigger')), 'time_fail_length' => array('friendly_name' => __('Breach Window'), 'method' => 'drop_array', 'array' => $timearray, 'description' => __('The amount of time in the past to check for threshold breaches.'), 'value' => isset($thold_data['time_fail_length']) ? $thold_data['time_fail_length'] : (read_config_option('thold_time_fail_length') > 0 ? read_config_option('thold_time_fail_length') : 1)), 'baseline_header' => array('friendly_name' => __('Baseline Settings'), 'method' => 'spacer'), 'bl_ref_time_range' => array('friendly_name' => __('Time range'), 'method' => 'drop_array', 'array' => $reference_types, 'description' => __('Specifies the point in the past (based on rrd resolution) that will be used as a reference'), 'value' => isset($thold_data['bl_ref_time_range']) ? $thold_data['bl_ref_time_range'] : read_config_option('alert_bl_timerange_def')), 'bl_pct_up' => array('friendly_name' => __('Deviation UP'), 'method' => 'textbox', 'max_length' => 3, 'size' => 10, 'description' => __('Specifies allowed deviation in percentage for the upper bound threshold. If not set, upper bound threshold will not be checked at all.'), 'value' => isset($thold_data['bl_pct_up']) ? $thold_data['bl_pct_up'] : ''), 'bl_pct_down' => array('friendly_name' => __('Deviation DOWN'), 'method' => 'textbox', 'max_length' => 3, 'size' => 10, 'description' => __('Specifies allowed deviation in percentage for the lower bound threshold. If not set, lower bound threshold will not be checked at all.'), 'value' => isset($thold_data['bl_pct_down']) ? $thold_data['bl_pct_down'] : ''), 'bl_fail_trigger' => array('friendly_name' => __('Baseline Trigger Count'), 'method' => 'textbox', 'max_length' => 3, 'size' => 10, 'description' => __('Number of consecutive times the data source must be in breach of the baseline threshold for an alert to be raised.<br>Leave empty to use default value (<b>Default: %s cycles</b>)', read_config_option('alert_bl_trigger')), 'value' => isset($thold_data['bl_fail_trigger']) ? $thold_data['bl_fail_trigger'] : read_config_option("alert_bl_trigger")), 'data_manipulation' => array('friendly_name' => __('Data Manipulation'), 'method' => 'spacer'), 'data_type' => array('friendly_name' => __('Data Type'), 'method' => 'drop_array', 'on_change' => 'changeDataType()', 'array' => $data_types, 'default' => read_config_option('data_type'), 'description' => __('Special formatting for the given data.'), 'value' => isset($thold_data['data_type']) ? $thold_data['data_type'] : ''), 'cdef' => array('friendly_name' => __('Threshold CDEF'), 'method' => 'drop_array', 'default' => 'NULL', 'description' => __('Apply this CDEF before returning the data.'), 'value' => isset($thold_data['cdef']) ? $thold_data['cdef'] : 0, 'array' => thold_cdef_select_usable_names()), 'percent_ds' => array('friendly_name' => __('Percent Datasource'), 'method' => 'drop_array', 'default' => 'NULL', 'description' => __('Second Datasource Item to use as total value to calculate percentage from.'), 'value' => isset($thold_data['percent_ds']) ? $thold_data['percent_ds'] : 0, 'array' => $data_fields), 'expression' => array('friendly_name' => __('RPN Expression'), 'method' => 'textarea', 'textarea_rows' => 3, 'textarea_cols' => 80, 'default' => '', 'description' => __('An RPN Expression is an RRDtool Compatible RPN Expression.  Syntax includes all functions below in addition to both Device and Data Query replacement expressions such as <span class="deviceUp">|query_ifSpeed|</span>.  To use a Data Source in the RPN Expression, you must use the syntax: <span class="deviceUp">|ds:dsname|</span>.  For example, <span class="deviceUp">|ds:traffic_in|</span> will get the current value of the traffic_in Data Source for the RRDfile(s) associated with the Graph. Any Data Source for a Graph can be included.<br><br>Math Operators: <span class="deviceUp">+, -, /, *, &#37;, ^</span><br>Functions: <span class="deviceUp">SIN, COS, TAN, ATAN, SQRT, FLOOR, CEIL, DEG2RAD, RAD2DEG, ABS, EXP, LOG, ATAN, ADNAN</span><br>Flow Operators: <span class="deviceUp">UN, ISINF, IF, LT, LE, GT, GE, EQ, NE</span><br>Comparison Functions: <span class="deviceUp">MAX, MIN, INF, NEGINF, NAN, UNKN, COUNT, PREV</span>%s %s', $replacements, $datasources), 'value' => isset($thold_data['expression']) ? $thold_data['expression'] : '', 'max_length' => '255', 'size' => '80'), 'other_header' => array('friendly_name' => __('Other Settings'), 'method' => 'spacer'), 'notify_warning' => array('friendly_name' => __('Warning Notification List'), 'method' => 'drop_sql', 'description' => __('You may specify choose a Notification List to receive Warnings for this Data Source'), 'value' => isset($thold_data['notify_warning']) ? $thold_data['notify_warning'] : '', 'none_value' => __('None'), 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name'), 'notify_alert' => array('friendly_name' => __('Alert Notification List'), 'method' => 'drop_sql', 'description' => __('You may specify choose a Notification List to receive Alerts for this Data Source'), 'value' => isset($thold_data['notify_alert']) ? $thold_data['notify_alert'] : '', 'none_value' => __('None'), 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name'));
    if (read_config_option("thold_alert_snmp") == 'on') {
        $extra = array('snmp_event_category' => array('friendly_name' => __('SNMP Notification - Event Category'), 'method' => 'textbox', 'description' => __('To allow a NMS to categorize different SNMP notifications more easily please fill in the category SNMP notifications for this template should make use of. E.g.: "disk_usage", "link_utilization", "ping_test", "nokia_firewall_cpu_utilization" ...'), 'value' => isset($thold_data['snmp_event_category']) ? $thold_data['snmp_event_category'] : '', 'default' => '', 'max_length' => '255'), 'snmp_event_severity' => array('friendly_name' => __('SNMP Notification - Alert Event Severity'), 'method' => 'drop_array', 'default' => '3', 'description' => __('Severity to be used for alerts. (low impact -> critical impact)'), 'value' => isset($thold_data['snmp_event_severity']) ? $thold_data['snmp_event_severity'] : 3, 'array' => array(1 => __('Low'), 2 => __('Medium'), 3 => __('High'), 4 => __('Critical'))));
        $form_array += $extra;
        if (read_config_option('thold_alert_snmp_warning') != 'on') {
            $extra = array('snmp_event_warning_severity' => array('friendly_name' => __('SNMP Notification - Warning Event Severity'), 'method' => 'drop_array', 'default' => '2', 'description' => __('Severity to be used for warnings. (Low impact -> Critical impact).<br>Note: The severity of warnings has to be equal or lower than the severity being defined for alerts.'), 'value' => isset($thold_data['snmp_event_warning_severity']) ? $thold_data['snmp_event_warning_severity'] : 2, 'array' => array(1 => __('Low'), 2 => __('Medium'), 3 => __('High'), 4 => __('Critical'))));
        }
        $form_array += $extra;
    }
    if (read_config_option('thold_disable_legacy') != 'on') {
        $extra = array('notify_accounts' => array('friendly_name' => __('Notify accounts'), 'method' => 'drop_multi', 'description' => __('This is a listing of accounts that will be notified when this threshold is breached.<br><br><br><br>'), 'array' => $send_notification_array, 'sql' => $sql), 'notify_extra' => array('friendly_name' => __('Alert Emails'), 'method' => 'textarea', 'textarea_rows' => 3, 'textarea_cols' => 50, 'description' => __('You may specify here extra Emails to receive alerts for this data source (comma separated)'), 'value' => isset($thold_data['notify_extra']) ? $thold_data['notify_extra'] : ''), 'notify_warning_extra' => array('friendly_name' => __('Warning Emails'), 'method' => 'textarea', 'textarea_rows' => 3, 'textarea_cols' => 50, 'description' => __('You may specify here extra Emails to receive warnings for this data source (comma separated)'), 'value' => isset($thold_data['notify_warning_extra']) ? $thold_data['notify_warning_extra'] : ''));
        $form_array += $extra;
    } else {
        $extra = array('notify_accounts' => array('method' => 'hidden', 'value' => 'ignore'), 'notify_extra' => array('method' => 'hidden', 'value' => isset($thold_data['notify_extra']) ? $thold_data['notify_extra'] : ''), 'notify_warning_extra' => array('method' => 'hidden', 'value' => isset($thold_data['notify_warning_extra']) ? $thold_data['notify_warning_extra'] : ''));
        $form_array += $extra;
    }
    draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array + array('id' => array('method' => 'hidden', 'value' => !empty($thold_data['id']) ? $thold_data['id'] : '0'), 'data_template_rrd_id' => array('method' => 'hidden', 'value' => isset($template_rrd) ? $template_rrd['id'] : '0'), 'host_id' => array('method' => 'hidden', 'value' => $thold_data['host_id']), 'local_data_id' => array('method' => 'hidden', 'value' => $thold_data['local_data_id']))));
    html_end_box();
    if (isset($_SESSION['data_return'])) {
        $ajax = false;
    } else {
        $ajax = true;
    }
    form_save_button('thold.php' . (!empty($thold_data['id']) ? '?id=' . $thold_data['id'] : ''), 'return', 'id', $ajax);
    ?>

	<script type='text/javascript'>

	function templateEnableDisable() {
		var status = $('#template_enabled').is(':checked');

		$('#name').prop('disabled', status);
		$('#thold_type').prop('disabled', status);
		$('#thold_hi').prop('disabled', status);
		$('#thold_low').prop('disabled', status);
		$('#thold_fail_trigger').prop('disabled', status);
		$('#thold_warning_hi').prop('disabled', status);
		$('#thold_warning_low').prop('disabled', status);
		$('#thold_warning_fail_trigger').prop('disabled', status);
		$('#repeat_alert').prop('disabled', status);
		$('#notify_extra').prop('disabled', status);
		$('#notify_warning_extra').prop('disabled', status);
		$('#notify_warning').prop('disabled', status);
		$('#notify_alert').prop('disabled', status);
		$('#cdef').prop('disabled', status);
		$('#thold_enabled').prop('disabled', status);

		if ($('#notify_accounts')) $('#notify_accounts').prop('disabled', status);

		$('#time_hi').prop('disabled', status);
		$('#time_low').prop('disabled', status);
		$('#time_fail_trigger').prop('disabled', status);
		$('#time_fail_length').prop('disabled', status);
		$('#time_warning_hi').prop('disabled', status);
		$('#time_warning_low').prop('disabled', status);
		$('#time_warning_fail_trigger').prop('disabled', status);
		$('#time_warning_fail_length').prop('disabled', status);
		$('#data_type').prop('disabled', status);
		$('#percent_ds').prop('disabled', status);
		$('#expression').prop('disabled', status);
		$('#exempt').prop('disabled', status);
		$('#restored_alert').prop('disabled', status);

		if ($('#snmp_event_category')) $('#snmp_event_category').prop('disabled', status);
		if ($('#snmp_event_severity')) $('#snmp_event_severity').prop('disabled', status);
		if ($('#snmp_event_warning_severity')) $('#snmp_event_warning_severity').prop('disabled', status);
	}

	function changeTholdType() {
		switch($('#thold_type').val()) {
		case '0':
			thold_toggle_hilow('');
			thold_toggle_baseline('none');
			thold_toggle_time('none');
			break;
		case '1':
			thold_toggle_hilow('none');
			thold_toggle_baseline('');
			thold_toggle_time('none');
			break;
		case '2':
			thold_toggle_hilow('none');
			thold_toggle_baseline('none');
			thold_toggle_time('');
			break;
		}
	}

	function changeDataType () {
		switch($('#data_type').val()) {
		case '0':
			$('#row_cdef').hide();
			$('#row_percent_ds').hide();
			$('#row_expression').hide();
			break;
		case '1':
			$('#row_cdef').show();
			$('#row_percent_ds').hide();
			$('#row_expression').hide();
			break;
		case '2':
			$('#row_cdef').hide()
			$('#row_percent_ds').show();
			$('#row_expression').hide();
			break;
		case '3':
			$('#row_expression').show();
			$('#row_cdef').hide();
			$('#row_percent_ds').hide();
			break;
		}
	}

	function thold_toggle_hilow (status) {
		if (status == '') {
			$('#row_thold_header, #row_thold_hi, #row_thold_low, #row_thold_fail_trigger').show();
			$('#row_thold_warning_header, #row_thold_warning_hi').show();
			$('#row_thold_warning_low, #row_thold_warning_fail_trigger').show();
		}else{
			$('#row_thold_header, #row_thold_hi, #row_thold_low, #row_thold_fail_trigger').hide();
			$('#row_thold_warning_header, #row_thold_warning_hi').hide();
			$('#row_thold_warning_low, #row_thold_warning_fail_trigger').hide();
		}
	}

	function thold_toggle_baseline(status) {
		if (status == '') {
			$('#row_baseline_header, #row_bl_ref_time_range').show();
			$('#row_bl_pct_up, #row_bl_pct_down, #row_bl_fail_trigger').show();
		}else{
			$('#row_baseline_header, #row_bl_ref_time_range').hide();
			$('#row_bl_pct_up, #row_bl_pct_down, #row_bl_fail_trigger').hide();
		}
	}

	function thold_toggle_time(status) {
		if (status == '') {
			$('#row_time_header, #row_time_hi, #row_time_low, #row_time_fail_trigger, #row_time_fail_length').show();
			$('#row_time_warning_header, #row_time_warning_hi, #row_time_warning_low').show();
			$('#row_time_warning_fail_trigger, #row_time_warning_fail_length').show();
		}else{
			$('#row_time_header, #row_time_hi, #row_time_low, #row_time_fail_trigger, #row_time_fail_length').hide();
			$('#row_time_warning_header, #row_time_warning_hi, #row_time_warning_low').hide();
			$('#row_time_warning_fail_trigger, #row_time_warning_fail_length').hide();
		}
	}

	function graphImage() {
		var id = $('#element').val();
		$('#graphimage').attr(src, '../../graph_image.php?local_graph_id=' + id + '&rra_id=0&graph_start=-32400&graph_height=100&graph_width=300&graph_nolegend=true').change();
	}

	$(function() {
		if ('<?php 
    print $thold_data['thold_template_id'];
    ?>
' == '0') {
			$('#template_enabled').prop('disabled', true);
		}

		if ($('#notify_accounts option').length == 0) {
			$('#row_notify_accounts').hide();
		}

		if ($('#notify_warning option').length == 0) {
			$('#row_notify_warning').hide();
		}

		if ($('#notify_alert option').length == 0) {
			$('#row_notify_alert').hide();
		}

		$('#notify_accounts').multiselect({
			minWidth: '400',
			noneSelectedText: '<?php 
    print __('Select Users(s)');
    ?>
', 
			selectedText: function(numChecked, numTotal, checkedItems) {
				myReturn = numChecked + ' <?php 
    print __('Users Selected');
    ?>
';
				$.each(checkedItems, function(index, value) {
					if (value.value == '0') {
						myReturn='<?php 
    print __('All Users Selected');
    ?>
';
						return false;
					}
				});
				return myReturn;
			},
			checkAllText: 'All', 
			uncheckAllText: 'None',
			uncheckall: function() {
				$(this).multiselect('widget').find(':checkbox:first').each(function() {
					$(this).prop('checked', true);
				});
			},
			open: function() {
				size = $('#notify_accounts option').length * 18 + 20;
				if (size > 100) {
					size = 100;
				}
				$('ul.ui-multiselect-checkboxes').css('height', size + 'px');
			},
			click: function(event, ui) {
				checked=$(this).multiselect('widget').find('input:checked').length;

				if (ui.value == '0') {
					if (ui.checked == true) {
						$('#host').multiselect('uncheckAll');
						$(this).multiselect('widget').find(':checkbox:first').each(function() {
							$(this).prop('checked', true);
						});
					}
				}else if (checked == 0) {
					$(this).multiselect('widget').find(':checkbox:first').each(function() {
						$(this).click();
					});
				}else if ($(this).multiselect('widget').find('input:checked:first').val() == '0') {
					if (checked > 0) {
						$(this).multiselect('widget').find(':checkbox:first').each(function() {
							$(this).click();
							$(this).prop('disable', true);
						});
					}
				}
			}
		}).multiselectfilter( {
			label: 'Search', width: '150'
		});

		templateEnableDisable();

		$('#template_enabled').click(function() {
			templateEnableDisable();
		});

		<?php 
    if (!isset($thold_data['thold_template_id']) || $thold_data['thold_template_id'] == '') {
        ?>
		$('#templated_enabled').prop('disabled', true);
		<?php 
    }
    ?>

		changeTholdType ();
		changeDataType ();

		$('#element').change(function() {
			graphImage;
		});
	});

	</script>
	<?php 
}
Example #11
0
function db_fetch_cell($sql, $col_name = '', $log = TRUE, $db_conn = FALSE)
{
    return db_fetch_cell_prepared($sql, array(), $col_name, $log, $db_conn);
}
function form_actions()
{
    global $config, $mactrack_view_macs_actions;
    /* ================= input validation ================= */
    get_filter_request_var('drp_action');
    /* ==================================================== */
    /* if we are to save this form, instead of display it */
    if (isset_request_var('selected_items')) {
        $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items'));
        if ($selected_items != false) {
            if (get_request_var('drp_action') == '1') {
                /* Authorize */
                if (sizeof($selected_items)) {
                    foreach ($selected_items as $mac) {
                        $mac = sanitize_search_string($mac);
                        api_mactrack_authorize_mac_addresses($mac);
                    }
                }
            } elseif (get_request_var('drp_action') == '2') {
                /* Revoke */
                $errors = '';
                if (sizeof($selected_items)) {
                    foreach ($selected_items as $mac) {
                        $mac = sanitize_search_string($mac);
                        $mac_found = db_fetch_cell_prepared('SELECT mac_address FROM mac_track_macauth WHERE mac_address = ?', array($mac));
                        if ($mac_found) {
                            api_mactrack_revoke_mac_addresses($mac);
                        } else {
                            $errors .= ', ' . $mac;
                        }
                    }
                }
                if ($errors) {
                    $_SESSION['sess_messages'] = __('The following MAC Addresses Could not be revoked because they are members of Group Authorizations %s', $errors);
                }
            }
        }
        header('Location: mactrack_view_macs.php');
        exit;
    }
    /* setup some variables */
    $mac_address_list = '';
    $delim = read_config_option('mt_mac_delim');
    /* loop through each of the device types selected on the previous page and get more info about them */
    while (list($var, $val) = each($_POST)) {
        if (substr($var, 0, 4) == 'chk_') {
            $matches = substr($var, 4);
            /* clean up the mac_address */
            if (isset($matches)) {
                $matches = sanitize_search_string($matches);
                $parts = explode('-', $matches);
                $mac = str_replace('_', $delim, $parts[0]);
            }
            if (!isset($mac_address_array[$mac])) {
                $mac_address_list .= '<li>' . $mac . '</li>';
                $mac_address_array[$mac] = $mac;
            }
        }
    }
    top_header();
    html_start_box($mactrack_view_macs_actions[get_request_var('drp_action')], '60%', '', '3', 'center', '');
    form_start('mmactrack_view_macs.php');
    if (get_request_var('drp_action') == '1') {
        /* Authorize Macs */
        print "<tr>\n\t\t\t\t<td class='textArea'>\n\t\t\t\t\t<p>" . __('Are you sure you want to Authorize the following MAC Addresses?') . "</p>\n\t\t\t\t\t<p>{$mac_address_list}</p>\n\t\t\t\t</td>\n\t\t\t</tr>";
    } elseif (get_request_var('drp_action') == '2') {
        /* Revoke Macs */
        print "<tr>\n\t\t\t\t<td class='textArea'>\n\t\t\t\t\t<p>" . __('Are you sure you want to Revoke the following MAC Addresses?') . "</p>\n\t\t\t\t\t<p>{$mac_address_list}</p>\n\t\t\t\t</td>\n\t\t\t</tr>";
    }
    if (!isset($mac_address_array)) {
        print "<tr><td class='even'><span class='textError'>" . __('You must select at least one MAC Address.') . "</span></td></tr>\n";
        $save_html = '';
    } else {
        if (!mactrack_check_user_realm(2122)) {
            print "<tr><td clsas='even'><span class='textError'>" . __('You are not permitted to change Mac Authorizations.') . "</span></td></tr>\n";
            $save_html = '';
        } else {
            $save_html = "<input type='submit' name='save' value='" . __('Yes') . "'>";
        }
    }
    print "<tr>\n\t\t<td colspan='2' class='saveRow'>\n\t\t\t<input type='hidden' name='action' value='actions'>\n\t\t\t<input type='hidden' name='selected_items' value='" . (isset($mac_address_array) ? serialize($mac_address_array) : '') . "'>\n\t\t\t<input type='hidden' name='drp_action' value='" . get_request_var('drp_action') . "'>" . (strlen($save_html) ? "\n\t\t\t<input type='submit' name='cancel' value='" . __('No') . "'>\n\t\t\t{$save_html}" : "<input type='submit' name='cancel' value='" . __('Return') . "'>") . "\n\t\t</td>\n\t</tr>";
    html_end_box();
    bottom_footer();
}
function mactrack_device_remove()
{
    global $config;
    /* ================= input validation ================= */
    get_filter_request_var('device_id');
    get_filter_request_var('type_id');
    /* ==================================================== */
    if (read_config_option('remove_verification') == 'on' && !isset_request_var('confirm')) {
        top_header();
        form_confirm(__('Are You Sure?'), __('Are you sure you want to delete the host %s', db_fetch_cell_prepared('SELECT device_name FROM host WHERE id = ?', array(get_request_var('device_id')))), 'mactrack_devices.php', 'mactrack_devices.php?action=remove&id=' . get_request_var('device_id'));
        bottom_footer();
        exit;
    }
    if (read_config_option('remove_verification') == '' || isset_request_var('confirm')) {
        api_mactrack_device_remove(get_request_var('device_id'));
    }
}
function mactrack_get_vendor_name($mac)
{
    $vendor_mac = substr($mac, 0, 8);
    $vendor_name = db_fetch_cell_prepared('SELECT vendor_name FROM mac_track_oui_database WHERE vendor_mac = ?', array($vendor_mac));
    if (strlen($vendor_name)) {
        return $vendor_name;
    } else {
        return __('Unknown');
    }
}
Example #15
0
File: html.php Project: MrWnn/cacti
function html_host_filter($host_id)
{
    $theme = read_config_option('selected_theme');
    if ($theme == 'classic') {
        ?>
		<td width='50'>
			Device
		</td>
		<td width='1'>
			<select id='host_id' name='host_id' onChange='applyFilter()'>
				<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>
		<?php 
    } else {
        if ($host_id > 0) {
            $hostname = db_fetch_cell_prepared("SELECT description FROM host WHERE id = ?", array($host_id));
        } elseif ($host_id == 0) {
            $hostname = 'None';
        } else {
            $hostname = 'Any';
        }
        ?>
		<td width='50'>
			Device
		</td>
		<td width='1'>
			<span id='host_wrapper' style='width:200px;' class='ui-selectmenu-button ui-widget ui-state-default ui-corner-all'>
				<span id='host_click' class='ui-icon ui-icon-triangle-1-s'></span>
				<input size='28' id='host' value='<?php 
        print $hostname;
        ?>
'>
			</span>
			<input type='hidden' id='host_id' name='host_id' value='<?php 
        print $host_id;
        ?>
'>
		</td>
	<?php 
    }
}
Example #16
0
function item_edit()
{
    global $struct_graph_item, $graph_item_types, $consolidation_functions;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('host_id'));
    input_validate_input_number(get_request_var_request('graph_template_id'));
    input_validate_input_number(get_request_var_request('local_graph_id'));
    input_validate_input_number(get_request_var_request('host_id'));
    input_validate_input_number(get_request_var_request('data_template_id'));
    /* ==================================================== */
    /* remember these search fields in session vars so we don't have to keep passing them around */
    load_current_session_value('local_graph_id', 'sess_local_graph_id', '');
    load_current_session_value('host_id', 'sess_ds_host_id', '-1');
    load_current_session_value('data_template_id', 'sess_data_template_id', '-1');
    $id = !empty($_REQUEST['id']) ? '&id=' . $_REQUEST['id'] : '';
    $host = db_fetch_row_prepared('SELECT hostname FROM host WHERE id = ?', array(get_request_var_request('host_id')));
    html_start_box('<strong>Data Sources</strong> [host: ' . (empty($host['hostname']) ? 'No Device' : $host['hostname']) . ']', '100%', '', '3', 'center', '');
    ?>
	<tr class='even noprint'>
		<form name="form_graph_items" action="graphs_items.php">
		<td>
			<table cellpadding="2" cellspacing="0">
				<tr>
					<td width="50">
						Device
					</td>
					<td>
						<select name="cbo_host_id" onChange="window.location=document.form_graph_items.cbo_host_id.options[document.form_graph_items.cbo_host_id.selectedIndex].value">
							<option value="graphs_items.php?action=item_edit<?php 
    print $id;
    ?>
&local_graph_id=<?php 
    print get_request_var_request('local_graph_id');
    ?>
&host_id=-1&data_template_id=<?php 
    print get_request_var_request('data_template_id');
    ?>
"<?php 
    if (get_request_var_request('host_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
							<option value="graphs_items.php?action=item_edit<?php 
    print $id;
    ?>
&local_graph_id=<?php 
    print get_request_var_request('local_graph_id');
    ?>
&host_id=0&data_template_id=<?php 
    print get_request_var_request('data_template_id');
    ?>
"<?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='graphs_items.php?action=item_edit" . $id . '&local_graph_id=' . get_request_var_request('local_graph_id') . '&host_id=' . $host['id'] . '&data_template_id=' . get_request_var_request('data_template_id') . "'";
            if (get_request_var_request('host_id') == $host['id']) {
                print ' selected';
            }
            print '>' . $host['name'] . "</option>\n";
        }
    }
    ?>

						</select>
					</td>
				</tr>
				<tr>
					<td style='white-space: nowrap;'>
						Data Template
					</td>
					<td>
						<select name="cbo_data_template_id" onChange="window.location=document.form_graph_items.cbo_data_template_id.options[document.form_graph_items.cbo_data_template_id.selectedIndex].value">
							<option value="graphs_items.php?action=item_edit<?php 
    print $id;
    ?>
&local_graph_id=<?php 
    print get_request_var_request('local_graph_id');
    ?>
&data_template_id=-1&host_id=<?php 
    print get_request_var_request('host_id');
    ?>
"<?php 
    if (get_request_var_request('data_template_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
							<option value="graphs_items.php?action=item_edit<?php 
    print $id;
    ?>
&local_graph_id=<?php 
    print get_request_var_request('local_graph_id');
    ?>
&data_template_id=0&host_id=<?php 
    print get_request_var_request('host_id');
    ?>
"<?php 
    if (get_request_var_request('data_template_id') == '0') {
        ?>
 selected<?php 
    }
    ?>
>None</option>
							<?php 
    $data_templates = db_fetch_assoc('SELECT id, name FROM data_template ORDER BY name');
    if (sizeof($data_templates) > 0) {
        foreach ($data_templates as $data_template) {
            print "<option value='graphs_items.php?action=item_edit" . $id . '&local_graph_id=' . get_request_var_request('local_graph_id') . '&data_template_id=' . $data_template['id'] . '&host_id=' . get_request_var_request('host_id') . "'";
            if (get_request_var_request('data_template_id') == $data_template['id']) {
                print ' selected';
            }
            print '>' . $data_template['name'] . "</option>\n";
        }
    }
    ?>

						</select>
					</td>
				</tr>
			</table>
		</td>
		</form>
	</tr>
	<?php 
    html_end_box();
    if (get_request_var_request('host_id') == '-1') {
        $sql_where = '';
    } elseif (get_request_var_request('host_id') == '0') {
        $sql_where = ' data_local.host_id=0 AND ';
    } elseif (!empty($_REQUEST['host_id'])) {
        $sql_where = ' data_local.host_id=' . get_request_var_request('host_id') . ' AND ';
    }
    if (get_request_var_request('data_template_id') == '-1') {
        $sql_where .= '';
    } elseif (get_request_var_request('data_template_id') == '0') {
        $sql_where .= ' data_local.data_template_id=0 AND ';
    } elseif (!empty($_REQUEST['data_template_id'])) {
        $sql_where .= ' data_local.data_template_id=' . get_request_var_request('data_template_id') . ' AND ';
    }
    if (!empty($_REQUEST['id'])) {
        $template_item = db_fetch_row_prepared('SELECT * FROM graph_templates_item WHERE id = ?', array(get_request_var_request('id')));
        $host_id = db_fetch_cell_prepared('SELECT host_id FROM graph_local WHERE id = ?', array(get_request_var_request('local_graph_id')));
    }
    $header_label = '[edit graph: ' . db_fetch_cell_prepared('SELECT title_cache FROM graph_templates_graph WHERE local_graph_id = ?' . array(get_request_var_request('local_graph_id'))) . ']';
    html_start_box("<strong>Graph Items</strong> {$header_label}", '100%', '', '3', 'center', '');
    /* by default, select the LAST DS chosen to make everyone's lives easier */
    if (!empty($_REQUEST['local_graph_id'])) {
        $default = db_fetch_row_prepared('SELECT task_item_id FROM graph_templates_item WHERE local_graph_id = ? ORDER BY sequence DESC', array(get_request_var_request('local_graph_id')));
        if (sizeof($default) > 0) {
            $struct_graph_item['task_item_id']['default'] = $default['task_item_id'];
        } else {
            $struct_graph_item['task_item_id']['default'] = 0;
        }
        /* modifications to the default graph items array */
        $struct_graph_item['task_item_id']['sql'] = "select\n\t\t\tCONCAT_WS('',data_template_data.name_cache,' (',data_template_rrd.data_source_name,')') as name,\n\t\t\tdata_template_rrd.id\n\t\t\tfrom (data_template_data,data_template_rrd,data_local)\n\t\t\tleft join host on (data_local.host_id=host.id)\n\t\t\twhere data_template_rrd.local_data_id=data_local.id\n\t\t\tand data_template_data.local_data_id=data_local.id ";
        /* Make sure we don't limit the list so that the selected DS isn't in the list in edit mode */
        if (strlen($sql_where) > 0) {
            $sql_where = substr($sql_where, 0, -5);
            if (!empty($_REQUEST['id'])) {
                $struct_graph_item['task_item_id']['sql'] .= ' AND ((' . $sql_where . ') OR (data_template_rrd.id = ' . $template_item['task_item_id'] . '))';
            } else {
                $struct_graph_item['task_item_id']['sql'] .= ' and (' . $sql_where . ')';
            }
        }
        $struct_graph_item['task_item_id']['sql'] .= ' ORDER BY name';
    }
    $form_array = array();
    while (list($field_name, $field_array) = each($struct_graph_item)) {
        $form_array += array($field_name => $struct_graph_item[$field_name]);
        $form_array[$field_name]['value'] = isset($template_item) ? $template_item[$field_name] : '';
        $form_array[$field_name]['form_id'] = isset($template_item) ? $template_item['id'] : '0';
    }
    draw_edit_form(array('config' => array(), 'fields' => $form_array));
    form_hidden_box('local_graph_id', get_request_var_request('local_graph_id'), '0');
    form_hidden_box('graph_template_item_id', isset($template_item) ? $template_item['id'] : '0', '');
    form_hidden_box('local_graph_template_item_id', isset($template_item) ? $template_item['local_graph_template_item_id'] : '0', '');
    form_hidden_box('graph_template_id', isset($template_item) ? $template_item['graph_template_id'] : '0', '');
    form_hidden_box('sequence', isset($template_item) ? $template_item['sequence'] : '0', '');
    form_hidden_box('_graph_type_id', isset($template_item) ? $template_item['graph_type_id'] : '0', '');
    form_hidden_box('save_component_item', '1', '');
    form_hidden_box('invisible_alpha', $form_array['alpha']['value'], 'FF');
    form_hidden_box('rrdtool_version', read_config_option('rrdtool_version'), '');
    html_end_box();
    form_save_button('graphs.php?action=graph_edit&id=' . get_request_var_request('local_graph_id'));
    ?>
	<script type='text/javascript'>

	$(function() {
		setRowVisibility();
		$('#graph_type_id').change(function(data) {
			setRowVisibility();
		});
	});

	/* 
	columns - task_item_id color_id alpha graph_type_id consolidation_function_id cdef_id value gprint_id text_format hard_return

	graph_type_ids - 1 - Comment 2 - HRule 3 - Vrule 4 - Line1 5 - Line2 6 - Line3 7 - Area 8 - Stack 9 - Gprint 10 - Legend
	*/

	function setRowVisibility() {
		switch($('#graph_type_id').val()) {
		case "1":
			$('#row_task_item_id').hide();
			$('#row_color_id').hide();
			$('#row_alpha').hide();
			$('#row_consolidation_function_id').hide();
			$('#row_cdef_id').hide();
			$('#row_value').hide();
			$('#row_gprint_id').hide();
			$('#row_text_format').show();
			$('#row_hard_return').show();
			break;
		case "2":
		case "3":
			$('#row_task_item_id').hide();
			$('#row_color_id').hide();
			$('#row_alpha').hide();
			$('#row_consolidation_function_id').hide();
			$('#row_cdef_id').hide();
			$('#row_value').show();
			$('#row_gprint_id').hide();
			$('#row_text_format').hide();
			$('#row_hard_return').show();
			break;
		case "4":
		case "5":
		case "6":
		case "7":
		case "8":
			$('#row_task_item_id').show();
			$('#row_color_id').show();
			$('#row_alpha').show();
			$('#row_consolidation_function_id').show();
			$('#row_cdef_id').show();
			$('#row_value').hide();
			$('#row_gprint_id').show();
			$('#row_text_format').show();
			$('#row_hard_return').show();

			break;
		case "9":
		case "10":
			$('#row_task_item_id').show();
			$('#row_color_id').hide();
			$('#row_alpha').hide();
			$('#row_consolidation_function_id').hide();
			$('#row_cdef_id').show();
			$('#row_value').hide();
			$('#row_gprint_id').show();
			$('#row_text_format').hide();
			if ($('#graph_type_id').val() == 9) {
				$('#row_hard_return').show();
			}else{
				$('#row_hard_return').hide();
			}

			break;
		}

		$('#alpha').prop('disabled', true);
		if ($('#color_id').val() != 0) {
			$('#alpha').prop('disabled', false);
		}
	}

	</script>
	<?php 
}
Example #17
0
function syslog_db_fetch_cell_prepared($sql, $params = array(), $col_name = '', $log = TRUE)
{
    global $syslog_cnn;
    return db_fetch_cell_prepared($sql, $params, $col_name, $log, $syslog_cnn);
}
Example #18
0
function get_hash_round_robin_archive($rra_id)
{
    $hash = db_fetch_cell_prepared('SELECT hash FROM rra WHERE id = ?', array($rra_id));
    if (preg_match('/[a-fA-F0-9]{32}/', $hash)) {
        return $hash;
    } else {
        return generate_hash();
    }
}
Example #19
0
function field_edit()
{
    global $registered_cacti_names, $fields_data_input_field_edit_1, $fields_data_input_field_edit_2, $fields_data_input_field_edit;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('data_input_id'));
    input_validate_input_regex(get_request_var_request('type'), '^(in|out)$');
    /* ==================================================== */
    if (!empty($_REQUEST['id'])) {
        $field = db_fetch_row_prepared('SELECT * FROM data_input_fields WHERE id = ?', array(get_request_var_request('id')));
    }
    if (!empty($_REQUEST['type'])) {
        $current_field_type = $_REQUEST['type'];
    } else {
        $current_field_type = $field['input_output'];
    }
    if ($current_field_type == 'out') {
        $header_name = 'Output';
    } elseif ($current_field_type == 'in') {
        $header_name = 'Input';
    }
    $data_input = db_fetch_row_prepared('SELECT type_id, name FROM data_input WHERE id = ?', array(get_request_var_request('data_input_id')));
    /* obtain a list of available fields for this given field type (input/output) */
    if ($current_field_type == 'in' && preg_match_all('/<([_a-zA-Z0-9]+)>/', db_fetch_cell_prepared('SELECT input_string FROM data_input WHERE id = ?', array($_REQUEST['data_input_id'] ? $_REQUEST['data_input_id'] : $field['data_input_id'])), $matches)) {
        for ($i = 0; $i < count($matches[1]); $i++) {
            if (in_array($matches[1][$i], $registered_cacti_names) == false) {
                $current_field_name = $matches[1][$i];
                $array_field_names[$current_field_name] = $current_field_name;
            }
        }
    }
    /* if there are no input fields to choose from, complain */
    if (!isset($array_field_names) && (isset($_REQUEST['type']) ? $_REQUEST['type'] == 'in' : false) && $data_input['type_id'] == '1') {
        display_custom_error_message('This script appears to have no input values, therefore there is nothing to add.');
        return;
    }
    html_start_box("<strong>{$header_name} Fields</strong> [edit: " . htmlspecialchars($data_input['name']) . ']', '100%', '', '3', 'center', '');
    $form_array = array();
    /* field name */
    if (($data_input['type_id'] == '1' || $data_input['type_id'] == '5') && $current_field_type == 'in') {
        /* script */
        $form_array = inject_form_variables($fields_data_input_field_edit_1, $header_name, $array_field_names, isset($field) ? $field : array());
    } elseif ($data_input['type_id'] == '2' || $data_input['type_id'] == '3' || $data_input['type_id'] == '4' || $data_input['type_id'] == '6' || $data_input['type_id'] == '7' || $data_input['type_id'] == '8' || $current_field_type == 'out') {
        /* snmp */
        $form_array = inject_form_variables($fields_data_input_field_edit_2, $header_name, isset($field) ? $field : array());
    }
    /* ONLY if the field is an input */
    if ($current_field_type == 'in') {
        unset($fields_data_input_field_edit['update_rra']);
    } elseif ($current_field_type == 'out') {
        unset($fields_data_input_field_edit['regexp_match']);
        unset($fields_data_input_field_edit['allow_nulls']);
        unset($fields_data_input_field_edit['type_code']);
    }
    draw_edit_form(array('config' => array(), 'fields' => $form_array + inject_form_variables($fields_data_input_field_edit, isset($field) ? $field : array(), $current_field_type, $_REQUEST)));
    html_end_box();
    form_save_button('data_input.php?action=edit&id=' . $_REQUEST['data_input_id']);
}
Example #20
0
function displayTreeNodes($tree_id, $nodeType = '', $parentNode = 0, $quietMode = FALSE)
{
    global $tree_sort_types, $tree_item_types, $host_group_types;
    if ($parentNode == 0) {
        if (!$quietMode) {
            echo "Known Tree Nodes:\n";
            echo "type\tid\tparentid\ttitle\tattribs\n";
        }
    }
    $parentID = 0;
    $nodes = db_fetch_assoc_prepared('SELECT id, local_graph_id, rra_id, title,
		host_id, host_grouping_type, sort_children_type
		FROM graph_tree_items
		WHERE graph_tree_id = ?
		AND parent = ?
		ORDER BY position', array($tree_id, $parentNode));
    if (sizeof($nodes)) {
        foreach ($nodes as $node) {
            /* taken from tree.php, funtion item_edit() */
            $current_type = TREE_ITEM_TYPE_HEADER;
            if ($node['local_graph_id'] > 0) {
                $current_type = TREE_ITEM_TYPE_GRAPH;
            }
            if ($node['host_id'] > 0) {
                $current_type = TREE_ITEM_TYPE_HOST;
            }
            switch ($current_type) {
                case TREE_ITEM_TYPE_HEADER:
                    if ($nodeType == '' || $nodeType == 'header') {
                        echo $tree_item_types[$current_type] . "\t";
                        echo $node['id'] . "\t";
                        if ($parentNode == 0) {
                            echo "N/A\t";
                        } else {
                            echo $parentNode . "\t";
                        }
                        echo $node['title'] . "\t";
                        echo $tree_sort_types[$node['sort_children_type']] . "\t";
                        echo "\n";
                    }
                    displayTreeNodes($tree_id, $nodeType, $node['id'], $quietMode);
                    break;
                case TREE_ITEM_TYPE_GRAPH:
                    if ($nodeType == '' || $nodeType == 'graph') {
                        echo $tree_item_types[$current_type] . "\t";
                        echo $node['id'] . "\t";
                        if ($parentNode == 0) {
                            echo "N/A\t";
                        } else {
                            echo $parentNode . "\t";
                        }
                        /* fetch the title for that graph */
                        $graph_title = db_fetch_cell_prepared('SELECT gtg.title_cache AS name
							FROM graph_templates_graph AS gtg
							WHERE gtg.local_graph_id = ?', array($node['local_graph_id']));
                        $rra = db_fetch_cell_prepared('SELECT name FROM rra WHERE id = ?', array($node['rra_id']));
                        echo $graph_title . "\t";
                        echo $rra . "\t";
                        echo "\n";
                    }
                    break;
                case TREE_ITEM_TYPE_HOST:
                    if ($nodeType == '' || $nodeType == 'host') {
                        echo $tree_item_types[$current_type] . "\t";
                        echo $node['id'] . "\t";
                        if ($parentNode == 0) {
                            echo "N/A\t";
                        } else {
                            echo $parentNode . "\t";
                        }
                        $name = db_fetch_cell_prepared('SELECT hostname FROM host WHERE id = ?', array($node['host_id']));
                        echo $name . "\t";
                        echo $host_group_types[$node['host_grouping_type']] . "\t";
                        echo "\n";
                    }
                    break;
            }
        }
    }
    if ($parentNode == 0) {
        if (!$quietMode) {
            echo "\n";
        }
    }
}
Example #21
0
function api_plugin_movedown($plugin)
{
    $id = db_fetch_cell_prepared('SELECT id FROM plugin_config WHERE directory = ?', array($plugin));
    $temp_id = db_fetch_cell('SELECT MAX(id) FROM plugin_config') + 1;
    $next_id = db_fetch_cell_prepared('SELECT MIN(id) FROM plugin_config WHERE id > ?', array($id));
    /* update the above plugin to the prior temp id */
    db_execute_prepared('UPDATE plugin_config SET id = ? WHERE id = ?', array($temp_id, $next_id));
    db_execute_prepared('UPDATE plugin_config SET id = ? WHERE id = ?', array($next_id, $id));
    db_execute_prepared('UPDATE plugin_config SET id = ? WHERE id = ?', array($id, $temp_id));
}
Example #22
0
File: cmd.php Project: MrWnn/cacti
				ORDER by host_id', array($first, $last));
            $script_server_calls = db_fetch_cell_prepared('SELECT count(*)
				FROM poller_item
				WHERE (action = 2 AND host_id >= ? AND host_id <= ? AND rrd_next_step <= 0)', array($first, $last));
            /* setup next polling interval */
            db_execute_prepared('UPDATE poller_item
				SET rrd_next_step = rrd_next_step - ' . $polling_interval . '
				WHERE (host_id >= ? AND host_id <= ?)', array($first, $last));
            db_execute_prepared('UPDATE poller_item
				SET rrd_next_step = rrd_step - ' . $polling_interval . '
				WHERE (rrd_next_step < 0 AND host_id >= ? AND host_id <= ?)', array($first, $last));
        } else {
            $polling_items = db_fetch_assoc_prepared('SELECT * FROM poller_item
					WHERE (host_id >= ? and host_id <= ?) 
					ORDER by host_id', array($first, $last));
            $script_server_calls = db_fetch_cell_prepared('SELECT count(*) FROM poller_item 
					WHERE (action IN (' . POLLER_ACTION_SCRIPT_PHP . ',' . POLLER_ACTION_SCRIPT_PHP_COUNT . ') AND (host_id >= ? AND host_id <= ?))', array($first, $last));
        }
    } else {
        print "ERROR: Invalid Arguments.  The first argument must be less than or equal to the first.\n";
        print "USAGE: CMD.PHP [[first_host] [second_host]]\n";
        cacti_log("ERROR: Invalid Arguments.  This rist argument must be less than or equal to the first.");
        /* record the process as having completed */
        record_cmdphp_done();
        exit('-1');
    }
}
if (sizeof($polling_items) > 0 && read_config_option('poller_enabled') == 'on') {
    $failure_type = '';
    $host_down = false;
    $new_host = true;
    $last_host = '';
Example #23
0
function substitute_data_input_data($string, $graph, $local_data_id, $max_chars = 0)
{
    if (empty($local_data_id)) {
        if (isset($graph['local_graph_id'])) {
            $local_data_ids = array_rekey(db_fetch_assoc_prepared('SELECT DISTINCT local_data_id
				FROM data_template_rrd
				INNER JOIN graph_templates_item
				ON data_template_rrd.id = graph_templates_item.task_item_id
				WHERE local_graph_id = ?', array($graph['local_graph_id'])), 'local_data_id', 'local_data_id');
            if (sizeof($local_data_ids)) {
                $data_template_data_id = db_fetch_cell('SELECT id FROM data_template_data WHERE local_data_id IN (' . implode(',', $local_data_ids) . ')');
            } else {
                $data_template_data_id = 0;
            }
        } else {
            $data_template_data_id = 0;
        }
    } else {
        $data_template_data_id = db_fetch_cell_prepared('SELECT id FROM data_template_data WHERE local_data_id = ?', array($local_data_id));
    }
    if (!empty($data_template_data_id)) {
        $data = db_fetch_assoc_prepared("SELECT\n\t\t\tdif.data_name, did.value\n\t\t\tFROM data_input_fields AS dif\n\t\t\tINNER JOIN data_input_data AS did\n\t\t\tON dif.id = did.data_input_field_id\n\t\t\tWHERE data_template_data_id = ?\n\t\t\tAND input_output = 'in'", array($data_template_data_id));
        if (sizeof($data)) {
            foreach ($data as $item) {
                if ($item['value'] != '') {
                    if ($max_chars > 0) {
                        $item['value'] = substr($item['field_value'], 0, $max_chars);
                    }
                    $string = stri_replace('|input_' . $item['data_name'] . '|', $item['value'], $string);
                }
            }
        }
    }
    return $string;
}
Example #24
0
function data_query_item_remove()
{
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('snmp_query_id'));
    /* ==================================================== */
    if (read_config_option('deletion_verification') == 'on' && !isset($_REQUEST['confirm'])) {
        top_header();
        form_confirm('Are You Sure?', "Are you sure you want to delete the Data Query Graph <strong>'" . htmlspecialchars(db_fetch_cell_prepared('SELECT name FROM snmp_query_graph WHERE id = ?', array($_REQUEST['id'])), ENT_QUOTES) . "'</strong>?", htmlspecialchars('data_queries.php?action=edit&id=' . $_REQUEST['snmp_query_id']), htmlspecialchars('data_queries.php?action=item_remove&id=' . $_REQUEST['id'] . '&snmp_query_id=' . $_REQUEST['snmp_query_id']));
        bottom_footer();
        exit;
    }
    if (read_config_option('deletion_verification') == '' || isset($_REQUEST['confirm'])) {
        db_execute_prepared('DELETE FROM snmp_query_graph WHERE id = ?', array($_REQUEST['id']));
        db_execute_prepared('DELETE FROM snmp_query_graph_rrd WHERE snmp_query_graph_id = ?', array($_REQUEST['id']));
        db_execute_prepared('DELETE FROM snmp_query_graph_rrd_sv WHERE snmp_query_graph_id = ?', array($_REQUEST['id']));
        db_execute_prepared('DELETE FROM snmp_query_graph_sv WHERE snmp_query_graph_id = ?', array($_REQUEST['id']));
    }
}
Example #25
0
function utilities_clear_user_log()
{
    $users = db_fetch_assoc('SELECT DISTINCT username FROM user_auth');
    if (sizeof($users)) {
        /* remove active users */
        foreach ($users as $user) {
            $total_rows = db_fetch_cell_prepared('SELECT COUNT(username) FROM user_log WHERE username = ? AND result = 1', array($user['username']));
            if ($total_rows > 1) {
                db_execute_prepared('DELETE FROM user_log WHERE username = ? AND result = 1 ORDER BY time LIMIT ' . ($total_rows - 1), array($user['username']));
            }
            db_execute_prepared('DELETE FROM user_log WHERE username = ? AND result = 0', array($user['username']));
        }
        /* delete inactive users */
        db_execute('DELETE FROM user_log WHERE user_id NOT IN (SELECT id FROM user_auth) OR username NOT IN (SELECT username FROM user_auth)');
    }
}
Example #26
0
function domains()
{
    global $domain_types, $actions, $item_rows;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('page'));
    input_validate_input_number(get_request_var_request('rows'));
    /* ==================================================== */
    /* clean up search string */
    if (isset($_REQUEST['filter'])) {
        $_REQUEST['filter'] = sanitize_search_string(get_request_var_request('filter'));
    }
    /* clean up sort_column */
    if (isset($_REQUEST['sort_column'])) {
        $_REQUEST['sort_column'] = sanitize_search_string(get_request_var_request('sort_column'));
    }
    /* clean up search string */
    if (isset($_REQUEST['sort_direction'])) {
        $_REQUEST['sort_direction'] = sanitize_search_string(get_request_var_request('sort_direction'));
    }
    /* if the user pushed the 'clear' button */
    if (isset($_REQUEST['clear_x'])) {
        kill_session_var('sess_domains_filter');
        kill_session_var('sess_domains_rows');
        kill_session_var('sess_domains_sort_column');
        kill_session_var('sess_domains_sort_direction');
        unset($_REQUEST['page']);
        unset($_REQUEST['rows']);
        unset($_REQUEST['filter']);
        unset($_REQUEST['sort_column']);
        unset($_REQUEST['sort_direction']);
        $_REQUEST['page'] = 1;
    }
    /* remember these search fields in session vars so we don't have to keep passing them around */
    load_current_session_value('filter', 'sess_domains_filter', '');
    load_current_session_value('rows', 'sess_table_rows', read_config_option('num_rows_table'));
    load_current_session_value('sort_column', 'sess_domains_sort_column', 'domain_name');
    load_current_session_value('sort_direction', 'sess_domains_sort_direction', 'ASC');
    load_current_session_value('page', 'sess_domains_current_page', '1');
    html_start_box('<strong>User Domains</strong>', '100%', '', '3', 'center', 'user_domains.php?action=edit');
    ?>
	<tr class='even' class='noprint'>
		<td class='noprint'>
		<form id='form_domains' method='get' action='user_domains.php'>
			<table cellpadding='2' cellspacing='0' border='0'>
				<tr class='noprint'>
					<td width='50'>
						Search
					</td>
					<td>
						<input id='filter' type='text' name='filter' size='25' value='<?php 
    print get_request_var_request('filter');
    ?>
'>
					</td>
					<td>
						Domains
					</td>
					<td>
						<select id='rows' name="rows" onChange="applyFilter()">
							<?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 '>' . htmlspecialchars($value) . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
					<td>
						<input id='refresh' type='button' value='Go' title='Set/Refresh Filters'>
					</td>
					<td>
						<input id='clear' type='button' name='clear_x' value='Clear' title='Clear Filters'>
					</td>
				</tr>
			</table>
			<input type='hidden' name='page' value='<?php 
    print $_REQUEST['page'];
    ?>
'>
		</form>
		<script type='text/javascript'>
		function applyFilter() {
			strURL = 'user_domains.php?rows=' + $('#rows').val();
			strURL = strURL + '&filter=' + $('#filter').val();
			strURL = strURL + '&page=' + $('#page').val();
			strURL = strURL + '&header=false';
			$.get(strURL, function(data) {
				$('#main').html(data);
				applySkin();
			});
		}

		function clearFilter() {
			strURL = 'user_domains.php?clear_x=1&header=false';
			$.get(strURL, function(data) {
				$('#main').html(data);
				applySkin();
			});
		}

		$(function(data) {
			$('#refresh').click(function() {
				applyFilter();
			});

			$('#clear').click(function() {
				clearFilter();
			});

			$('#form_domains').submit(function(event) {
				event.preventDefault();
				applyFilter();
			});
		});
		</script>
		</td>
	</tr>
	<?php 
    html_end_box();
    /* print checkbox form for validation */
    print "<form name='chk' method='post' action='user_domains.php'>\n";
    html_start_box('', '100%', '', '3', 'center', '');
    /* form the 'where' clause for our main sql query */
    if ($_REQUEST['filter'] != '') {
        $sql_where = "WHERE (domain_name LIKE '%%" . get_request_var_request('filter') . "%%') ||\n\t\t\t(type LIKE '%%" . get_request_var_request('filter') . "%%')";
    } else {
        $sql_where = '';
    }
    $total_rows = db_fetch_cell("SELECT\n\t\tcount(*)\n\t\tFROM user_domains\n\t\t{$sql_where}");
    $domains = db_fetch_assoc("SELECT *\n\t\tFROM user_domains\n\t\t{$sql_where}\n\t\tORDER BY " . get_request_var_request('sort_column') . ' ' . get_request_var_request('sort_direction') . '
		LIMIT ' . get_request_var_request('rows') * (get_request_var_request('page') - 1) . ',' . get_request_var_request('rows'));
    $nav = html_nav_bar('user_user_domains.php?filter=' . get_request_var_request('filter'), MAX_DISPLAY_PAGES, get_request_var_request('page'), get_request_var_request('rows'), $total_rows, 6, 'User Domains', 'page', 'main');
    print $nav;
    $display_text = array('domain_name' => array('Domain Name', 'ASC'), 'type' => array('Domain Type', 'ASC'), 'defdomain' => array('Default', 'ASC'), 'user_id' => array('Effective User', 'ASC'), 'enabled' => array('Enabled', 'ASC'));
    html_header_sort_checkbox($display_text, get_request_var_request('sort_column'), get_request_var_request('sort_direction'), false);
    $i = 0;
    if (sizeof($domains) > 0) {
        foreach ($domains as $domain) {
            /* hide system types */
            form_alternate_row('line' . $domain['domain_id'], true);
            form_selectable_cell("<a class='linkEditMain' href='" . htmlspecialchars('user_domains.php?action=edit&domain_id=' . $domain['domain_id']) . "'>" . (strlen(get_request_var_request('filter')) ? eregi_replace('(' . preg_quote(get_request_var_request('filter')) . ')', "<span class='filteredValue>\\1</span>", $domain['domain_name']) : $domain['domain_name']) . '</a>', $domain['domain_id']);
            form_selectable_cell($domain_types[$domain['type']], $domain['domain_id']);
            form_selectable_cell($domain['defdomain'] == '0' ? '--' : 'Yes', $domain['domain_id']);
            form_selectable_cell($domain['user_id'] == '0' ? 'None Selected' : db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($domain['user_id'])), $domain['domain_id']);
            form_selectable_cell($domain['enabled'] == 'on' ? 'Yes' : 'No', $domain['domain_id']);
            form_checkbox_cell($domain['domain_name'], $domain['domain_id']);
            form_end_row();
        }
        print $nav;
    } else {
        print '<tr><td><em>No User Domains Defined</em></td></tr>';
    }
    html_end_box(false);
    /* draw the dropdown containing a list of available actions for this form */
    draw_actions_dropdown($actions);
    print "</form>\n";
}
Example #27
0
function form_actions()
{
    global $host_actions;
    /* ================= 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'] == '1') {
            /* delete */
            db_execute('DELETE FROM host_template WHERE ' . array_to_sql_or($selected_items, 'id'));
            db_execute('DELETE FROM host_template_snmp_query WHERE ' . array_to_sql_or($selected_items, 'host_template_id'));
            db_execute('DELETE FROM host_template_graph WHERE ' . array_to_sql_or($selected_items, 'host_template_id'));
            /* "undo" any device that is currently using this template */
            db_execute('UPDATE host SET host_template_id=0 WHERE ' . array_to_sql_or($selected_items, 'host_template_id'));
        } elseif ($_POST['drp_action'] == '2') {
            /* duplicate */
            for ($i = 0; $i < count($selected_items); $i++) {
                /* ================= input validation ================= */
                input_validate_input_number($selected_items[$i]);
                /* ==================================================== */
                duplicate_host_template($selected_items[$i], $_POST['title_format']);
            }
        }
        header('Location: host_templates.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 name FROM host_template WHERE id = ?'), array($matches[1])) . '<br>';
            $host_array[$i] = $matches[1];
            $i++;
        }
    }
    top_header();
    html_start_box('<strong>' . $host_actions[$_POST['drp_action']] . '</strong>', '60%', '', '3', 'center', '');
    print "<form action='host_templates.php' autocomplete='off' method='post'>\n";
    if (isset($host_array) && sizeof($host_array)) {
        if ($_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>Are you sure you want to delete the following Device Template(s)? All Devices currently associated\n\t\t\t\t\t\twith these Device Template(s) will lose that assocation.</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</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 Template(s)'>";
        } elseif ($_POST['drp_action'] == '2') {
            /* duplicate */
            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 Template(s) will be duplicated. You can\n\t\t\t\t\t\toptionally change the title format for the new Device Template(s).</p>\n\t\t\t\t\t\t<p><ul>{$host_list}</ul></p>\n\t\t\t\t\t\t<p><strong>Title Format:</strong><br>";
            form_text_box('title_format', '<template_title> (1)', '', '255', '30', 'text');
            print "</p>\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='Duplicate Device Template(s)'>";
        }
    } else {
        print "<tr><td class='even'><span class='textError'>You must select at least one host template.</span></td></tr>\n";
        $save_html = "<input type='button' value='Return' onClick='window.history.back()'>";
    }
    print "\t<tr>\n\t\t\t<td 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();
}
Example #28
0
function draw_nontemplated_fields_graph_item($graph_template_id, $local_graph_id, $field_name_format = "|field|_|id|", $header_title = "", $alternate_colors = true, $locked = 'false')
{
    global $struct_graph_item;
    $form_array = array();
    $draw_any_items = false;
    /* fetch information about the graph template */
    $input_item_list = db_fetch_assoc("SELECT * FROM graph_template_input WHERE graph_template_id={$graph_template_id} ORDER BY column_name,name");
    /* modifications to the default graph items array */
    if (!empty($local_graph_id)) {
        $host_id = db_fetch_cell("SELECT host_id FROM graph_local WHERE id={$local_graph_id}");
        $struct_graph_item["task_item_id"]["sql"] = "SELECT\n\t\t\tCONCAT_WS('',\n\t\t\tcase\n\t\t\tWHEN host.description IS NULL THEN 'No Device - '\n\t\t\twhen host.description IS NOT NULL THEN ''\n\t\t\tend,data_template_data.name_cache,' (',data_template_rrd.data_source_name,')') AS name,\n\t\t\tdata_template_rrd.id\n\t\t\tFROM (data_template_data,data_template_rrd,data_local)\n\t\t\tLEFT JOIN host ON (data_local.host_id=host.id)\n\t\t\twhere data_template_rrd.local_data_id=data_local.id\n\t\t\tand data_template_data.local_data_id=data_local.id\n\t\t\t" . (empty($host_id) ? "" : " AND data_local.host_id={$host_id}") . "\n\t\t\torder by name";
    }
    if (sizeof($input_item_list) > 0) {
        foreach ($input_item_list as $item) {
            if (!empty($local_graph_id)) {
                $current_def_value = db_fetch_row("select\n\t\t\t\t\tgraph_templates_item." . $item["column_name"] . ",\n\t\t\t\t\tgraph_templates_item.id\n\t\t\t\t\tfrom (graph_templates_item,graph_template_input_defs)\n\t\t\t\t\twhere graph_template_input_defs.graph_template_item_id=graph_templates_item.local_graph_template_item_id\n\t\t\t\t\tand graph_template_input_defs.graph_template_input_id=" . $item["id"] . "\n\t\t\t\t\tand graph_templates_item.local_graph_id={$local_graph_id}\n\t\t\t\t\tlimit 0,1");
            } else {
                $current_def_value = db_fetch_row("select\n\t\t\t\t\tgraph_templates_item." . $item["column_name"] . ",\n\t\t\t\t\tgraph_templates_item.id\n\t\t\t\t\tfrom (graph_templates_item,graph_template_input_defs)\n\t\t\t\t\twhere graph_template_input_defs.graph_template_item_id=graph_templates_item.id\n\t\t\t\t\tand graph_template_input_defs.graph_template_input_id=" . $item["id"] . "\n\t\t\t\t\tand graph_templates_item.graph_template_id=" . $graph_template_id . "\n\t\t\t\t\tlimit 0,1");
            }
            /* find our field name */
            $form_field_name = str_replace("|field|", $item["column_name"], $field_name_format);
            $form_field_name = str_replace("|id|", $item["id"], $form_field_name);
            $form_array += array($form_field_name => $struct_graph_item[$item["column_name"]]);
            /* modifications to the default form array */
            $form_array[$form_field_name]["friendly_name"] = $item["name"];
            $form_array[$form_field_name]["value"] = $current_def_value[$item["column_name"]];
            if ($locked == 'true') {
                if (substr_count($form_field_name, 'task_item_id') > 0) {
                    $form_array[$form_field_name]['method'] = 'value';
                    $value = db_fetch_cell_prepared("SELECT\n                        CONCAT_WS('',CASE WHEN host.description IS NULL THEN 'No Device - ' ELSE '' END,data_template_data.name_cache,' (',data_template_rrd.data_source_name,')') AS name\n                        FROM (data_template_data,data_template_rrd,data_local)\n                        LEFT JOIN host ON (data_local.host_id=host.id)\n                        WHERE data_template_rrd.local_data_id=data_local.id\n                        AND data_template_data.local_data_id=data_local.id\n                        AND data_template_rrd.id = ?", array($current_def_value[$item["column_name"]]));
                    cacti_log("The Value is '{$value}'");
                    $form_array[$form_field_name]['value'] = $value;
                }
            }
            /* if we are drawing the graph input list in the pre-graph stage we should omit the data
            			source fields because they are basically meaningless at this point */
            if (empty($local_graph_id) && $item["column_name"] == "task_item_id") {
                unset($form_array[$form_field_name]);
            } else {
                if ($draw_any_items == false && $header_title != "") {
                    print "<tr class='tableHeader'><td colspan='2' class='tableSubHeaderColumn'>{$header_title}</td></tr>\n";
                }
                $draw_any_items = true;
            }
        }
    }
    /* setup form options */
    if ($alternate_colors == true) {
        $form_config_array = array("no_form_tag" => true);
    } else {
        $form_config_array = array("no_form_tag" => true, "force_row_color" => true);
    }
    if (sizeof($input_item_list > 0)) {
        draw_edit_form(array("config" => $form_config_array, "fields" => $form_array));
    }
    return isset($form_array) ? sizeof($form_array) : 0;
}
Example #29
0
function graphs()
{
    global $item_rows;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('host_id'));
    input_validate_input_number(get_request_var_request('graph_type'));
    input_validate_input_number(get_request_var_request('rows'));
    /* ==================================================== */
    /* clean up search string */
    if (isset($_REQUEST['filter'])) {
        $_REQUEST['filter'] = sanitize_search_string(get_request_var_request('filter'));
    }
    /* if the user pushed the 'clear' button */
    if (isset($_REQUEST['clear_x'])) {
        kill_session_var('sess_graphs_new_filter');
        kill_session_var('sess_default_rows');
        unset($_REQUEST['filter']);
        unset($_REQUEST['rows']);
        $changed = true;
    } else {
        /* if any of the settings changed, reset the page number */
        $changed = false;
        $changed += check_changed('host_id', 'sess_graphs_new_host_id');
        $changed += check_changed('graph_type', 'sess_graphs_new_graph_type');
        $changed += check_changed('filter', 'sess_graphs_new_filter');
        $changed += check_changed('rows', 'sess_default_rows');
    }
    load_current_session_value('host_id', 'sess_graphs_new_host_id', db_fetch_cell('SELECT id FROM host ORDER BY description, hostname LIMIT 1'));
    load_current_session_value('graph_type', 'sess_graphs_new_graph_type', read_config_option('default_graphs_new_dropdown'));
    load_current_session_value('filter', 'sess_graphs_new_filter', '');
    load_current_session_value('rows', 'sess_default_rows', read_config_option('num_rows_table'));
    if (!empty($_REQUEST['host_id'])) {
        $host = db_fetch_row_prepared('SELECT id, description, hostname, host_template_id FROM host WHERE id = ?', array($_REQUEST['host_id']));
        $header = ' [ ' . htmlspecialchars($host['description']) . ' (' . htmlspecialchars($host['hostname']) . ') ' . (!empty($host['host_template_id']) ? htmlspecialchars(db_fetch_cell_prepared('SELECT name FROM host_template WHERE id = ?', array($host['host_template_id']))) : '') . ' ]';
    } else {
        $host = array();
        $header = 'None Host Type';
    }
    $row_limit = get_request_var_request('rows');
    html_start_box("<strong>New Graphs for</strong> {$header}", '100%', '', '3', 'center', '');
    form_alternate_row();
    print '<td class="even">';
    ?>
	<script type='text/javascript'>
	<!--

	function applyFilter() {
		strURL = '?graph_type=' + $('#graph_type').val();
		strURL = strURL + '&host_id=' + $('#host_id').val();
		strURL = strURL + '&filter=' + $('#filter').val();;
		strURL = strURL + '&rows=' + $('#rows').val();;
		document.location = strURL;
	}

	-->
	</script>
	<form name='form_graphs_new' action='graphs_new.php'>
	<table width='100%' cellpadding='2' cellspacing='0' border='0' align='left'>
		<tr>
			<?php 
    print html_host_filter($_REQUEST['host_id']);
    ?>
			<td style='white-space:nowrap;' width='1'>
				Graph Types
			</td>
			<td width='1'>
				<select id='graph_type' name='graph_type' onChange='applyFilter()'>
					<option value='-2'<?php 
    if ($_REQUEST['graph_type'] == '-2') {
        ?>
 selected<?php 
    }
    ?>
>All</option>
					<option value='-1'<?php 
    if ($_REQUEST['graph_type'] == '-1') {
        ?>
 selected<?php 
    }
    ?>
>Graph Template Based</option>
					<?php 
    $snmp_queries = db_fetch_assoc_prepared('SELECT
						snmp_query.id,
						snmp_query.name,
						snmp_query.xml_path
						FROM (snmp_query, host_snmp_query)
						WHERE host_snmp_query.snmp_query_id = snmp_query.id
						AND host_snmp_query.host_id = ?
						ORDER BY snmp_query.name', array($host['id']));
    if (sizeof($snmp_queries) > 0) {
        foreach ($snmp_queries as $query) {
            print "<option value='" . $query['id'] . "'";
            if ($_REQUEST['graph_type'] == $query['id']) {
                print ' selected';
            }
            print '>' . $query['name'] . "</option>\n";
        }
    }
    ?>
				</select>
			</td>
			<td width='50'>
				Rows
			</td>
			<td>
				<select id='rows' name='rows' onChange='applyFilter()'>
					<?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 '>' . htmlspecialchars($value) . "</option>\n";
        }
    }
    ?>
				</select>
			</td>
			<td rowspan='3' class='textInfo' align='right' valign='top'>
				<span class='linkMarker'>*</span><a class='hyperLink' href='<?php 
    print htmlspecialchars('host.php?action=edit&id=' . $_REQUEST['host_id']);
    ?>
'>Edit this Device</a><br>
				<span class='linkMarker'>*</span><a class='hyperLink' href='<?php 
    print htmlspecialchars('host.php?action=edit');
    ?>
'>Create New Device</a><br>
				<?php 
    api_plugin_hook('graphs_new_top_links');
    ?>
			</td>
		</tr>
		<tr style='<?php 
    if ($_REQUEST['graph_type'] <= 0) {
        ?>
display:none;<?php 
    }
    ?>
'>
			<td width='50'>
				Search
			</td>
			<td style='white-space:nowrap;'>
				<input id='filter' type='text' name='filter' size='25' value='<?php 
    print htmlspecialchars(get_request_var_request('filter'));
    ?>
'>
			</td>
			<td colspan='3' style='white-space:nowrap;'>
				<input type='submit' value='Go' title='Set/Refresh Filters'>
				<input type='submit' name='clear_x' value='Clear' title='Clear Filters'>
			</td>
		</tr>
	</table>
	</form>
	</td>
	</tr>

	<?php 
    html_end_box();
    ?>

	<form name='chk' method='post' action='graphs_new.php'>
	<?php 
    $total_rows = sizeof(db_fetch_assoc_prepared('SELECT graph_template_id FROM host_graph WHERE host_id = ?', array($_REQUEST['host_id'])));
    $i = 0;
    if ($changed) {
        foreach ($snmp_queries as $query) {
            kill_session_var('sess_graphs_new_page' . $query['id']);
            unset($_REQUEST['page' . $query['id']]);
            load_current_session_value('page' . $query['id'], 'sess_graphs_new_page' . $query['id'], '1');
        }
    }
    if ($_REQUEST['graph_type'] > 0) {
        load_current_session_value('page' . $_REQUEST['graph_type'], 'sess_graphs_new_page' . $_REQUEST['graph_type'], '1');
    } else {
        if ($_REQUEST['graph_type'] == -2) {
            foreach ($snmp_queries as $query) {
                load_current_session_value('page' . $query['id'], 'sess_graphs_new_page' . $query['id'], '1');
            }
        }
    }
    $script = "<script type='text/javascript'>\nvar gt_created_graphs = new Array();\nvar created_graphs = new Array()\n";
    if ($_REQUEST['graph_type'] < 0) {
        html_start_box('<strong>Graph Templates</strong>', '100%', '', '3', 'center', '');
        print "<tr class='tableHeader'>\n\t\t\t\t<td class='tableSubHeaderColumn'>Graph Template Name</td>\n\t\t\t\t<td width='1%' align='center' class='tableSubHeaderCheckbox' style='" . get_checkbox_style() . "'><input type='checkbox' style='margin: 0px;' name='all_cg' title='Select All' onClick='SelectAll(\"sg\",this.checked);'></td>\n\n\t\t\t</tr>\n";
        $graph_templates = db_fetch_assoc_prepared('SELECT
			graph_templates.id AS graph_template_id,
			graph_templates.name AS graph_template_name
			FROM (host_graph, graph_templates)
			WHERE host_graph.graph_template_id = graph_templates.id
			AND host_graph.host_id = ?
			ORDER BY graph_templates.name', array($_REQUEST['host_id']));
        if (!empty($_REQUEST['host_id'])) {
            $template_graphs = db_fetch_assoc_prepared('SELECT
				graph_local.graph_template_id
				FROM (graph_local, host_graph)
				WHERE graph_local.graph_template_id = host_graph.graph_template_id
				AND graph_local.host_id = host_graph.host_id
				AND graph_local.host_id = ?
				GROUP BY graph_local.graph_template_id', array($host['id']));
            if (sizeof($template_graphs) > 0) {
                $script .= 'var gt_created_graphs = new Array(';
                $cg_ctr = 0;
                foreach ($template_graphs as $template_graph) {
                    $script .= ($cg_ctr > 0 ? ',' : '') . "'" . $template_graph['graph_template_id'] . "'";
                    $cg_ctr++;
                }
                $script .= ")\n";
            }
        }
        /* create a row for each graph template associated with the host template */
        if (sizeof($graph_templates) > 0) {
            foreach ($graph_templates as $graph_template) {
                $query_row = $graph_template['graph_template_id'];
                print "<tr id='gt_line{$query_row}' class='selectable " . ($i % 2 == 0 ? 'odd' : 'even') . "'>";
                $i++;
                print "<td>\n\t\t\t\t\t\t<span id='gt_text{$query_row}" . "_0'>" . htmlspecialchars($graph_template['graph_template_name']) . "</span>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td align='right' class='checkbox'>\n\t\t\t\t\t\t<input type='checkbox' name='cg_{$query_row}' id='cg_{$query_row}'>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>";
            }
        }
        html_end_box();
        html_start_box('', '100%', '', '3', 'center', '');
        $available_graph_templates = db_fetch_assoc('SELECT
			graph_templates.id, graph_templates.name
			FROM snmp_query_graph RIGHT JOIN graph_templates
			ON (snmp_query_graph.graph_template_id = graph_templates.id)
			WHERE (((snmp_query_graph.name) Is Null)) ORDER BY graph_templates.name');
        /* create a row at the bottom that lets the user create any graph they choose */
        print "\t<tr class='even'>\n\t\t\t\t<td width='1'><i>Create</i></td>\n\t\t\t\t<td align='left'>";
        form_dropdown('cg_g', $available_graph_templates, 'name', 'id', '', '(Select a graph type to create)', '', 'textArea');
        print '</td>
			</tr>';
        html_end_box();
    }
    if ($_REQUEST['graph_type'] != -1 && !empty($_REQUEST['host_id'])) {
        $snmp_queries = db_fetch_assoc('SELECT
			snmp_query.id,
			snmp_query.name,
			snmp_query.xml_path
			FROM (snmp_query,host_snmp_query)
			WHERE host_snmp_query.snmp_query_id=snmp_query.id
			AND host_snmp_query.host_id=' . $host['id'] . ($_REQUEST['graph_type'] != -2 ? ' AND snmp_query.id=' . $_REQUEST['graph_type'] : '') . '
			ORDER BY snmp_query.name');
        if (sizeof($snmp_queries) > 0) {
            foreach ($snmp_queries as $snmp_query) {
                unset($total_rows);
                if (!$changed) {
                    $page = $_REQUEST['page' . $snmp_query['id']];
                } else {
                    $page = 1;
                }
                $xml_array = get_data_query_array($snmp_query['id']);
                $num_input_fields = 0;
                $num_visible_fields = 0;
                if ($xml_array != false) {
                    /* loop through once so we can find out how many input fields there are */
                    reset($xml_array['fields']);
                    while (list($field_name, $field_array) = each($xml_array['fields'])) {
                        if ($field_array['direction'] == 'input') {
                            $num_input_fields++;
                            if (!isset($total_rows)) {
                                $total_rows = db_fetch_cell_prepared('SELECT count(*) FROM host_snmp_cache WHERE host_id = ? AND snmp_query_id = ? AND field_name = ?', array($host['id'], $snmp_query['id'], $field_name));
                            }
                        }
                    }
                }
                if (!isset($total_rows)) {
                    $total_rows = 0;
                }
                $snmp_query_graphs = db_fetch_assoc_prepared('SELECT snmp_query_graph.id,snmp_query_graph.name FROM snmp_query_graph WHERE snmp_query_graph.snmp_query_id = ? ORDER BY snmp_query_graph.name', array($snmp_query['id']));
                if (sizeof($snmp_query_graphs) > 0) {
                    foreach ($snmp_query_graphs as $snmp_query_graph) {
                        $created_graphs = db_fetch_assoc_prepared("SELECT DISTINCT\n\t\t\t\t\t\tdata_local. snmp_index\n\t\t\t\t\t\tFROM (data_local, data_template_data)\n\t\t\t\t\t\tLEFT JOIN data_input_data ON (data_template_data.id = data_input_data.data_template_data_id)\n\t\t\t\t\t\tLEFT JOIN data_input_fields ON (data_input_data.data_input_field_id = data_input_fields.id)\n\t\t\t\t\t\tWHERE data_local.id = data_template_data.local_data_id\n\t\t\t\t\t\tAND data_input_fields.type_code = 'output_type'\n\t\t\t\t\t\tAND data_input_data.value = ?\n\t\t\t\t\t\tAND data_local.host_id = ?", array($snmp_query_graph['id'], $host['id']));
                        $script .= 'created_graphs[' . $snmp_query_graph['id'] . '] = new Array(';
                        $cg_ctr = 0;
                        if (sizeof($created_graphs) > 0) {
                            foreach ($created_graphs as $created_graph) {
                                $script .= ($cg_ctr > 0 ? ',' : '') . "'" . encode_data_query_index($created_graph['snmp_index']) . "'";
                                $cg_ctr++;
                            }
                        }
                        $script .= ")\n";
                    }
                }
                print "\t<table width='100%' class='cactiTable' align='center' cellpadding='3' cellspacing='0'>\n\n\t\t\t\t\t<tr class='cactiTableTitle'>\n\t\t\t\t\t\t<td colspan='" . ($num_input_fields + 1) . "'>\n\t\t\t\t\t\t\t<table  cellspacing='0' cellpadding='0' width='100%' >\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class='textHeaderDark'>\n\t\t\t\t\t\t\t\t\t\t<strong>Data Query</strong> [" . $snmp_query['name'] . "]\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t<td align='right' nowrap>\n\t\t\t\t\t\t\t\t\t\t<a href='" . htmlspecialchars('graphs_new.php?action=query_reload&id=' . $snmp_query['id'] . '&host_id=' . $host['id']) . "'><img src='images/reload_icon_small.gif' title='Reload Associated Query' alt='' border='0' align='absmiddle'></a>\n\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>";
                if ($xml_array != false) {
                    $html_dq_header = '';
                    $snmp_query_indexes = array();
                    reset($xml_array['fields']);
                    /* if there is a where clause, get the matching snmp_indexes */
                    $sql_where = '';
                    if (strlen($_REQUEST['filter'])) {
                        $sql_where = '';
                        $indexes = db_fetch_assoc("SELECT DISTINCT snmp_index\n\t\t\t\t\t\tFROM host_snmp_cache\n\t\t\t\t\t\tWHERE field_value LIKE '%%" . $_REQUEST['filter'] . "%%'\n\t\t\t\t\t\tAND snmp_query_id=" . $snmp_query['id'] . "\n\t\t\t\t\t\tAND host_id=" . $host['id']);
                        if (sizeof($indexes)) {
                            foreach ($indexes as $index) {
                                if (strlen($sql_where)) {
                                    $sql_where .= ", '" . $index['snmp_index'] . "'";
                                } else {
                                    $sql_where .= " AND snmp_index IN('" . $index['snmp_index'] . "'";
                                }
                            }
                            $sql_where .= ')';
                        }
                    }
                    if (strlen($_REQUEST['filter']) == 0 || strlen($_REQUEST['filter']) && sizeof($indexes)) {
                        /* determine the sort order */
                        if (isset($xml_array['index_order_type'])) {
                            if ($xml_array['index_order_type'] == 'numeric') {
                                $sql_order = 'ORDER BY CAST(snmp_index AS unsigned)';
                            } else {
                                if ($xml_array['index_order_type'] == 'alphabetic') {
                                    $sql_order = 'ORDER BY snmp_index';
                                } else {
                                    if ($xml_array['index_order_type'] == 'natural') {
                                        $sql_order = 'ORDER BY INET_ATON(snmp_index)';
                                    } else {
                                        $sql_order = '';
                                    }
                                }
                            }
                        } else {
                            $sql_order = '';
                        }
                        /* get the unique field values from the database */
                        $field_names = db_fetch_assoc_prepared('SELECT DISTINCT field_name
						FROM host_snmp_cache
						WHERE host_id = ?
						AND snmp_query_id = ?', array($host['id'], $snmp_query['id']));
                        /* build magic query */
                        $sql_query = 'SELECT host_id, snmp_query_id, snmp_index';
                        $num_visible_fields = sizeof($field_names);
                        $i = 0;
                        if (sizeof($field_names) > 0) {
                            foreach ($field_names as $column) {
                                $field_name = $column['field_name'];
                                $sql_query .= ", MAX(CASE WHEN field_name='{$field_name}' THEN field_value ELSE NULL END) AS '{$field_name}'";
                                $i++;
                            }
                        }
                        $sql_query .= ' FROM host_snmp_cache
						WHERE host_id=' . $host['id'] . '
						AND snmp_query_id=' . $snmp_query['id'] . "\n\t\t\t\t\t\t{$sql_where}\n\t\t\t\t\t\tGROUP BY host_id, snmp_query_id, snmp_index\n\t\t\t\t\t\t{$sql_order}\n\t\t\t\t\t\tLIMIT " . $row_limit * ($page - 1) . ',' . $row_limit;
                        $rows_query = 'SELECT host_id, snmp_query_id, snmp_index
						FROM host_snmp_cache
						WHERE host_id=' . $host['id'] . '
						AND snmp_query_id=' . $snmp_query['id'] . "\n\t\t\t\t\t\t{$sql_where}\n\t\t\t\t\t\tGROUP BY host_id, snmp_query_id, snmp_index";
                        $snmp_query_indexes = db_fetch_assoc($sql_query);
                        $total_rows = sizeof(db_fetch_assoc($rows_query));
                        if (($page - 1) * $row_limit > $total_rows) {
                            $page = 1;
                            $_REQUEST['page' . $query['id']] = $page;
                            load_current_session_value('page' . $query['id'], 'sess_graphs_new_page' . $query['id'], '1');
                        }
                        $nav = html_nav_bar('graphs_new.php', MAX_DISPLAY_PAGES, $page, $row_limit, $total_rows, 15, 'Items', 'page' . $snmp_query['id']);
                        print $nav;
                        while (list($field_name, $field_array) = each($xml_array['fields'])) {
                            if ($field_array['direction'] == 'input' && sizeof($field_names)) {
                                foreach ($field_names as $row) {
                                    if ($row['field_name'] == $field_name) {
                                        $html_dq_header .= "<td class='tableSubHeaderColumn'>" . $field_array['name'] . "</td>\n";
                                        break;
                                    }
                                }
                            }
                        }
                        if (!sizeof($snmp_query_indexes)) {
                            print "<tr class='odd'><td>This Data Query returned 0 rows, perhaps there was a problem executing this\n\t\t\t\t\t\t\tData Query. You can <a href='" . htmlspecialchars('host.php?action=query_verbose&id=' . $snmp_query['id'] . '&host_id=' . $host['id']) . "'>run this Data Query in debug mode</a> to get more information.</td></tr>\n";
                        } else {
                            print "<tr class='tableHeader'>\n\t\t\t\t\t\t\t\t{$html_dq_header}\n\t\t\t\t\t\t\t\t<td width='1%' align='center' class='tableSubHeaderCheckbox' style='" . get_checkbox_style() . "'><input type='checkbox' style='margin: 0px;' name='all_" . $snmp_query['id'] . "' title='Select All' onClick='SelectAll(\"sg_" . $snmp_query['id'] . "\",this.checked)'></td>\n\n\t\t\t\t\t\t\t</tr>\n";
                        }
                        $row_counter = 0;
                        $column_counter = 0;
                        $fields = array_rekey($field_names, 'field_name', 'field_name');
                        if (sizeof($snmp_query_indexes) > 0) {
                            foreach ($snmp_query_indexes as $row) {
                                $query_row = $snmp_query['id'] . '_' . encode_data_query_index($row['snmp_index']);
                                print "<tr id='line{$query_row}' class='selectable " . ($row_counter % 2 == 0 ? 'odd' : 'even') . "'>";
                                $i++;
                                $column_counter = 0;
                                reset($xml_array['fields']);
                                while (list($field_name, $field_array) = each($xml_array['fields'])) {
                                    if ($field_array['direction'] == 'input') {
                                        if (in_array($field_name, $fields)) {
                                            if (isset($row[$field_name])) {
                                                print "<td><span id='text{$query_row}" . '_' . $column_counter . "'>" . (strlen($_REQUEST['filter']) ? preg_replace('/(' . preg_quote($_REQUEST['filter']) . ')/i', "<span class='filteredValue'>\\1</span>", $row[$field_name]) : $row[$field_name]) . '</span></td>';
                                            } else {
                                                print "<td><span id='text{$query_row}" . '_' . $column_counter . "'></span></td>";
                                            }
                                            $column_counter++;
                                        }
                                    }
                                }
                                print "<td class='checkbox' align='right'>";
                                print "<input type='checkbox' name='sg_{$query_row}' id='sg_{$query_row}'>";
                                print '</td>';
                                print "</tr>\n";
                                $row_counter++;
                            }
                        }
                        if ($total_rows > $row_limit) {
                            print $nav;
                        }
                    } else {
                        print "<tr class='odd'><td class='textError'>Search Returned no Rows.</td></tr>\n";
                    }
                } else {
                    print "<tr class='odd'><td class='textError'>Error in data query.</td></tr>\n";
                }
                print '</table>';
                /* draw the graph template drop down here */
                $data_query_graphs = db_fetch_assoc_prepared('SELECT snmp_query_graph.id, snmp_query_graph.name FROM snmp_query_graph WHERE snmp_query_graph.snmp_query_id = ? ORDER BY snmp_query_graph.name', array($snmp_query['id']));
                if (sizeof($data_query_graphs) == 1) {
                    echo "<input type='hidden' id='sgg_" . $snmp_query['id'] . "' name='sgg_" . $snmp_query['id'] . "' value='" . $data_query_graphs[0]['id'] . "'>\n";
                } elseif (sizeof($data_query_graphs) > 1) {
                    print "\t<table align='center' width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td width='100%' valign='middle'>\n\t\t\t\t\t\t\t\t<img src='images/arrow.gif' align='absmiddle' alt=''>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td style='white-space:nowrap;font-style: italic;'' align='right'>\n\t\t\t\t\t\t\t\tSelect a Graph Type to Create\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right'>\n\t\t\t\t\t\t\t\t<select name='sgg_" . $snmp_query['id'] . "' id='sgg_" . $snmp_query['id'] . "' onChange='dqUpdateDeps(" . $snmp_query['id'] . ',' . (isset($column_counter) ? $column_counter : '') . ");'>\n\t\t\t\t\t\t\t\t\t";
                    html_create_list($data_query_graphs, 'name', 'id', '0');
                    print "\n\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n";
                }
                print '<br>';
                $script .= 'dqUpdateDeps(' . $snmp_query['id'] . ',' . $num_visible_fields . ");\n";
            }
        }
    }
    if (strlen($script)) {
        $script .= "</script>\n";
        print $script;
    }
    form_hidden_box('save_component_graph', '1', '');
    if (!empty($_REQUEST['host_id'])) {
        form_hidden_box('host_id', $host['id'], '0');
        form_hidden_box('host_template_id', $host['host_template_id'], '0');
    }
    if (isset($_SERVER['HTTP_REFERER']) && !substr_count($_SERVER['HTTP_REFERER'], 'graphs_new')) {
        $_REQUEST['returnto'] = basename($_SERVER['HTTP_REFERER']);
    }
    load_current_session_value('returnto', 'sess_graphs_new_returnto', '');
    form_save_button($_REQUEST['returnto']);
}
Example #30
0
File: auth.php Project: MrWnn/cacti
function is_realm_allowed($realm)
{
    global $user_auth_realms;
    /* list all realms that this user has access to */
    if (isset($_SESSION['sess_user_id'])) {
        if (isset($_SESSION['sess_user_realms'][$realm])) {
            return true;
        } elseif (read_config_option('auth_method') != 0) {
            $user_realm = db_fetch_cell_prepared('SELECT realm_id 
				FROM user_auth_realm 
				WHERE user_id = ?
				AND realm_id = ?
				UNION
				SELECT realm_id
				FROM user_auth_group_realm AS uagr
				INNER JOIN user_auth_group AS uag
				ON uag.id = uagr.group_id
				INNER JOIN user_auth_group_members AS uagm
				ON uag.id = uagm.group_id
				WHERE uag.enabled = \'on\' AND uagr.realm_id = ?
				AND uagm.user_id = ?', array($_SESSION['sess_user_id'], $realm, $realm, $_SESSION['sess_user_id']));
            if (!empty($user_realm)) {
                $_SESSION['sess_user_realms'][$realm] = $realm;
                return true;
            } else {
                return false;
            }
        } else {
            $_SESSION['sess_user_realms'][$realm] = $realm;
        }
    } else {
        return false;
    }
}