コード例 #1
2
function collect_pppoe_users_api(&$host)
{
    $rows = array();
    $api = new RouterosAPI();
    $api->debug = false;
    $rekey_array = array('host_id', 'name', 'index', 'userType', 'serverID', 'domain', 'bytesIn', 'bytesOut', 'packetsIn', 'packetsOut', 'curBytesIn', 'curBytesOut', 'curPacketsIn', 'curPacketsOut', 'prevBytesIn', 'prevBytesOut', 'prevPacketsIn', 'prevPacketsOut', 'present', 'last_seen');
    // Put the queues into an array
    $users = array_rekey(db_fetch_assoc_prepared("SELECT \n\t\thost_id, '0' AS `index`, '1' AS userType, '0' AS serverID, SUBSTRING(name, 7) AS name, '' AS domain,\n\t\tBytesIn AS bytesIn, BytesOut AS bytesOut, PacketsIn as packetsIn, PacketsOut AS packetsOut,\n\t\tcurBytesIn, curBytesOut, curPacketsIn, curPacketsOut, \n\t\tprevBytesIn, prevBytesOut, prevPacketsIn, prevPacketsOut, present, last_seen\n\t\tFROM plugin_mikrotik_queues \n\t\tWHERE host_id = ? \n\t\tAND name LIKE 'PPPOE-%'", array($host['id'])), 'name', $rekey_array);
    $creds = db_fetch_row_prepared('SELECT * FROM plugin_mikrotik_credentials WHERE host_id = ?', array($host['id']));
    $start = microtime(true);
    if (sizeof($creds)) {
        if ($api->connect($host['hostname'], $creds['user'], $creds['password'])) {
            $api->write('/ppp/active/getall');
            $read = $api->read(false);
            $array = $api->parseResponse($read);
            $end = microtime(true);
            $sql = array();
            cacti_log('MIKROTIK RouterOS API STATS: API Returned ' . sizeof($array) . ' PPPoe Users in ' . round($end - $start, 2) . ' seconds.', false, 'SYSTEM');
            if (sizeof($array)) {
                foreach ($array as $row) {
                    if (!isset($row['name'])) {
                        continue;
                    }
                    $name = strtoupper($row['name']);
                    if (isset($users[$name])) {
                        $user = $users[$name];
                        $user['mac'] = $row['caller-id'];
                        $user['ip'] = $row['address'];
                        $user['connectTime'] = uptimeToSeconds($row['uptime']);
                        $user['host_id'] = $host['id'];
                        $user['radius'] = $row['radius'] == 'true' ? 1 : 0;
                        $user['limitBytesIn'] = $row['limit-bytes-in'];
                        $user['limitBytesOut'] = $row['limit-bytes-out'];
                        $user['userType'] = 1;
                        $sql[] = '(' . $user['host_id'] . ',' . $user['index'] . ',' . $user['userType'] . ',' . $user['serverID'] . ',' . db_qstr($user['name']) . ',' . db_qstr($user['domain']) . ',' . db_qstr($user['mac']) . ',' . db_qstr($user['ip']) . ',' . $user['connectTime'] . ',' . $user['bytesIn'] . ',' . $user['bytesOut'] . ',' . $user['packetsIn'] . ',' . $user['packetsOut'] . ',' . $user['curBytesIn'] . ',' . $user['curBytesOut'] . ',' . $user['curPacketsIn'] . ',' . $user['curPacketsOut'] . ',' . $user['prevBytesIn'] . ',' . $user['prevBytesOut'] . ',' . $user['prevPacketsIn'] . ',' . $user['prevPacketsOut'] . ',' . $user['limitBytesIn'] . ',' . $user['limitBytesOut'] . ',' . $user['radius'] . ',' . $user['present'] . ',' . db_qstr($user['last_seen']) . ')';
                    }
                }
                if (sizeof($sql)) {
                    db_execute('INSERT INTO plugin_mikrotik_users 
						(host_id, `index`, userType, serverID, name, domain, mac, ip, connectTime, 
						bytesIn, bytesOut, packetsIn, packetsOut, 
						curBytesIn, curBytesOut, curPacketsIn, curPacketsOut, 
						prevBytesIn, prevBytesOut, prevPacketsIn, prevPacketsOut, 
						limitBytesIn, limitBytesOut, radius, present, last_seen) 
						VALUES ' . implode(', ', $sql) . '
						ON DUPLICATE KEY UPDATE connectTime=VALUES(connectTime), 
						bytesIn=VALUES(bytesIn), bytesOut=VALUES(bytesOut), 
						packetsIn=VALUES(packetsIn), packetsOut=VALUES(packetsOut), 
						curBytesIn=VALUES(curBytesIn), curBytesOut=VALUES(curBytesOut),
						curPacketsIn=VALUES(curPacketsIn), curPacketsOut=VALUES(curPacketsOut),
						prevBytesIn=VALUES(prevBytesIn), prevBytesOut=VALUES(prevBytesOut),
						prevPacketsIn=VALUES(prevPacketsIn), prevPacketsOut=VALUES(prevPacketsOut),
						limitBytesIn=VALUES(limitBytesIn), limitBytesOut=VALUES(limitBytesOut),
						radius=VALUES(radius), present=VALUES(present), last_seen=VALUES(last_seen)');
                }
            }
            $idle_users = db_fetch_assoc_prepared('SELECT name 
				FROM plugin_mikrotik_users 
				WHERE last_seen < FROM_UNIXTIME(UNIX_TIMESTAMP() - ?) 
				AND present=1 
				AND host_id = ?', array(read_config_option('mikrotik_queues_freq'), $host['id']));
            db_execute_prepared('UPDATE IGNORE plugin_mikrotik_users SET
				bytesIn=0, bytesOut=0, packetsIn=0, packetsOut=0, connectTime=0,
				curBytesIn=0, curBytesOut=0, curPacketsIn=0, curPacketsOut=0,
				prevBytesIn=0, prevBytesOut=0, prevPacketsIn=0, prevPacketsOut=0, present=0
				WHERE host_id = ? 
				AND userType = 1 
				AND last_seen < FROM_UNIXTIME(UNIX_TIMESTAMP() - ?)', array($host['id'], read_config_option('mikrotik_queues_freq')));
            $api->disconnect();
        } else {
            cacti_log('ERROR:RouterOS @ ' . $host['description'] . ' Timed Out');
        }
    }
}
コード例 #2
0
ファイル: cdef.php プロジェクト: MrWnn/cacti
function get_cdef($cdef_id)
{
    $cdef_items = db_fetch_assoc_prepared('SELECT * FROM cdef_items WHERE cdef_id = ? ORDER BY sequence', array($cdef_id));
    $i = 0;
    $cdef_string = '';
    if (sizeof($cdef_items) > 0) {
        foreach ($cdef_items as $cdef_item) {
            if ($i > 0) {
                $cdef_string .= ',';
            }
            if ($cdef_item['type'] == 5) {
                $current_cdef_id = $cdef_item['value'];
                $cdef_string .= get_cdef($current_cdef_id);
            } else {
                $cdef_string .= get_cdef_item_name($cdef_item['id']);
            }
            $i++;
        }
    }
    return $cdef_string;
}
コード例 #3
0
ファイル: api_device.php プロジェクト: MrWnn/cacti
function api_device_save($id, $host_template_id, $description, $hostname, $snmp_community, $snmp_version, $snmp_username, $snmp_password, $snmp_port, $snmp_timeout, $disabled, $availability_method, $ping_method, $ping_port, $ping_timeout, $ping_retries, $notes, $snmp_auth_protocol, $snmp_priv_passphrase, $snmp_priv_protocol, $snmp_context, $max_oids, $device_threads)
{
    global $config;
    include_once $config['base_path'] . '/lib/utility.php';
    include_once $config['base_path'] . '/lib/variables.php';
    include_once $config['base_path'] . '/lib/data_query.php';
    /* fetch some cache variables */
    if (empty($id)) {
        $_host_template_id = 0;
    } else {
        $_host_template_id = db_fetch_cell_prepared('SELECT host_template_id FROM host WHERE id=?', array($id));
    }
    $save['id'] = form_input_validate($id, 'id', '^[0-9]+$', false, 3);
    $save['host_template_id'] = form_input_validate($host_template_id, 'host_template_id', '^[0-9]+$', false, 3);
    $save['description'] = form_input_validate($description, 'description', '', false, 3);
    $save['hostname'] = form_input_validate(trim($hostname), 'hostname', '', false, 3);
    $save['notes'] = form_input_validate($notes, 'notes', '', true, 3);
    $save['snmp_version'] = form_input_validate($snmp_version, 'snmp_version', '', true, 3);
    $save['snmp_community'] = form_input_validate($snmp_community, 'snmp_community', '', true, 3);
    if ($save['snmp_version'] == 3) {
        $save['snmp_username'] = form_input_validate($snmp_username, 'snmp_username', '', true, 3);
        $save['snmp_password'] = form_input_validate($snmp_password, 'snmp_password', '', true, 3);
        $save['snmp_auth_protocol'] = form_input_validate($snmp_auth_protocol, 'snmp_auth_protocol', "^\\[None\\]|MD5|SHA\$", true, 3);
        $save['snmp_priv_passphrase'] = form_input_validate($snmp_priv_passphrase, 'snmp_priv_passphrase', '', true, 3);
        $save['snmp_priv_protocol'] = form_input_validate($snmp_priv_protocol, 'snmp_priv_protocol', "^\\[None\\]|DES|AES128\$", true, 3);
        $save['snmp_context'] = form_input_validate($snmp_context, 'snmp_context', '', true, 3);
    } else {
        $save['snmp_username'] = '';
        $save['snmp_password'] = '';
        $save['snmp_auth_protocol'] = '';
        $save['snmp_priv_passphrase'] = '';
        $save['snmp_priv_protocol'] = '';
        $save['snmp_context'] = '';
    }
    $save['snmp_port'] = form_input_validate($snmp_port, 'snmp_port', '^[0-9]+$', false, 3);
    $save['snmp_timeout'] = form_input_validate($snmp_timeout, 'snmp_timeout', '^[0-9]+$', false, 3);
    /* disabled = 'on'   => regexp '^on$'
     * not disabled = '' => no regexp, but allow nulls */
    $save['disabled'] = form_input_validate($disabled, 'disabled', '^on$', true, 3);
    $save['availability_method'] = form_input_validate($availability_method, 'availability_method', '^[0-9]+$', false, 3);
    $save['ping_method'] = form_input_validate($ping_method, 'ping_method', '^[0-9]+$', false, 3);
    $save['ping_port'] = form_input_validate($ping_port, 'ping_port', '^[0-9]+$', true, 3);
    $save['ping_timeout'] = form_input_validate($ping_timeout, 'ping_timeout', '^[0-9]+$', true, 3);
    $save['ping_retries'] = form_input_validate($ping_retries, 'ping_retries', '^[0-9]+$', true, 3);
    $save['max_oids'] = form_input_validate($max_oids, 'max_oids', '^[0-9]+$', true, 3);
    $save['device_threads'] = form_input_validate($device_threads, 'device_threads', '^[0-9]+$', true, 3);
    $save = api_plugin_hook_function('api_device_save', $save);
    $host_id = 0;
    if (!is_error_message()) {
        $host_id = sql_save($save, 'host');
        if ($host_id) {
            raise_message(1);
            /* push out relavant fields to data sources using this host */
            push_out_host($host_id, 0);
            /* the host substitution cache is now stale; purge it */
            kill_session_var('sess_host_cache_array');
            /* update title cache for graph and data source */
            update_data_source_title_cache_from_host($host_id);
            update_graph_title_cache_from_host($host_id);
        } else {
            raise_message(2);
        }
        /* if the user changes the host template, add each snmp query associated with it */
        if ($host_template_id != $_host_template_id && !empty($host_template_id)) {
            $snmp_queries = db_fetch_assoc_prepared('SELECT snmp_query_id FROM host_template_snmp_query WHERE host_template_id = ?', array($host_template_id));
            if (sizeof($snmp_queries) > 0) {
                foreach ($snmp_queries as $snmp_query) {
                    db_execute_prepared('REPLACE INTO host_snmp_query (host_id, snmp_query_id, reindex_method) VALUES (?, ?, ?)', array($host_id, $snmp_query['snmp_query_id'], read_config_option('reindex_method')));
                    /* recache snmp data */
                    run_data_query($host_id, $snmp_query['snmp_query_id']);
                }
            }
            $graph_templates = db_fetch_assoc_prepared('SELECT graph_template_id FROM host_template_graph WHERE host_template_id = ?', array($host_template_id));
            if (sizeof($graph_templates) > 0) {
                foreach ($graph_templates as $graph_template) {
                    db_execute_prepared('REPLACE INTO host_graph (host_id, graph_template_id) VALUES (?, ?)', array($host_id, $graph_template['graph_template_id']));
                    api_plugin_hook_function('add_graph_template_to_host', array('host_id' => $host_id, 'graph_template_id' => $graph_template['graph_template_id']));
                }
            }
        }
    }
    # now that we have the id of the new host, we may plugin postprocessing code
    $save['id'] = $host_id;
    snmpagent_api_device_new($save);
    api_plugin_hook_function('api_device_new', $save);
    return $host_id;
}
コード例 #4
0
ファイル: host.php プロジェクト: 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');
}
コード例 #5
0
ファイル: utilities.php プロジェクト: MrWnn/cacti
function utilities_view_snmp_cache()
{
    global $poller_actions, $item_rows;
    define('MAX_DISPLAY_PAGES', 21);
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('host_id'));
    input_validate_input_number(get_request_var_request('snmp_query_id'));
    input_validate_input_number(get_request_var_request('page'));
    input_validate_input_number(get_request_var_request('poller_action'));
    /* ==================================================== */
    /* clean up search filter */
    if (isset($_REQUEST['filter'])) {
        $_REQUEST['filter'] = sanitize_search_string(get_request_var('filter'));
    }
    /* if the user pushed the 'clear' button */
    if (isset($_REQUEST['clear_x'])) {
        kill_session_var('sess_snmp_current_page');
        kill_session_var('sess_snmp_host_id');
        kill_session_var('sess_snmp_snmp_query_id');
        kill_session_var('sess_snmp_filter');
        unset($_REQUEST['page']);
        unset($_REQUEST['filter']);
        unset($_REQUEST['host_id']);
        unset($_REQUEST['snmp_query_id']);
    }
    /* remember these search fields in session vars so we don't have to keep passing them around */
    load_current_session_value('page', 'sess_snmp_current_page', '1');
    load_current_session_value('host_id', 'sess_snmp_host_id', '-1');
    load_current_session_value('snmp_query_id', 'sess_snmp_snmp_query_id', '-1');
    load_current_session_value('filter', 'sess_snmp_filter', '');
    load_current_session_value('rows', 'sess_default_rows', read_config_option('num_rows_table'));
    $_REQUEST['page_referrer'] = 'view_snmp_cache';
    load_current_session_value('page_referrer', 'page_referrer', 'view_snmp_cache');
    ?>
	<script type="text/javascript">
	<!--

	function applyFilter() {
		strURL = '?host_id=' + $('#host_id').val();
		strURL = strURL + '&snmp_query_id=' + $('#snmp_query_id').val();
		strURL = strURL + '&filter=' + $('#filter').val();
		strURL = strURL + '&rows=' + $('#rows').val();
		strURL = strURL + '&page=' + $('#page').val();
		strURL = strURL + '&action=view_snmp_cache';
		strURL = strURL + '&header=false';
		$.get(strURL, function(data) {
			$('#main').html(data);
			applySkin();
		});
	}

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

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

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

		$('#form_snmpcache').submit(function(event) {
			event.preventDefault();
			applyFilter();
		});
	});

	-->
	</script>
	<?php 
    html_start_box('<strong>SNMP Cache Items</strong>', '100%', '', '3', 'center', '');
    ?>
	<tr class='even noprint'>
		<td>
		<form id="form_snmpcache" action="utilities.php">
			<table cellpadding="2" cellspacing="0">
				<tr>
					<td width="50">
						Device
					</td>
					<td>
						<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 
    if (get_request_var_request('snmp_query_id') == -1) {
        $hosts = db_fetch_assoc('SELECT DISTINCT
											host.id,
											host.description,
											host.hostname
											FROM (host_snmp_cache, snmp_query,host)
											WHERE host_snmp_cache.host_id = host.id
											AND host_snmp_cache.snmp_query_id = snmp_query.id
											ORDER by host.description');
    } else {
        $hosts = db_fetch_assoc_prepared('SELECT DISTINCT
											host.id,
											host.description,
											host.hostname
											FROM (host_snmp_cache, snmp_query,host)
											WHERE host_snmp_cache.host_id = host.id
											AND host_snmp_cache.snmp_query_id = snmp_query.id
											AND host_snmp_cache.snmp_query_id = ?
											ORDER by host.description', array(get_request_var_request('snmp_query_id')));
    }
    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 '>' . $host['description'] . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
					<td>
						Query Name
					</td>
					<td>
						<select id='snmp_query_id' name="snmp_query_id" onChange="applyFilter()">
							<option value="-1"<?php 
    if (get_request_var_request('host_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
							<?php 
    if (get_request_var_request('host_id') == -1) {
        $snmp_queries = db_fetch_assoc('SELECT DISTINCT
											snmp_query.id,
											snmp_query.name
											FROM (host_snmp_cache, snmp_query,host)
											WHERE host_snmp_cache.host_id = host.id
											AND host_snmp_cache.snmp_query_id = snmp_query.id
											ORDER by snmp_query.name');
    } else {
        $snmp_queries = db_fetch_assoc_prepared("SELECT DISTINCT\n\t\t\t\t\t\t\t\t\t\t\tsnmp_query.id,\n\t\t\t\t\t\t\t\t\t\t\tsnmp_query.name\n\t\t\t\t\t\t\t\t\t\t\tFROM (host_snmp_cache, snmp_query,host)\n\t\t\t\t\t\t\t\t\t\t\tWHERE host_snmp_cache.host_id = host.id\n\t\t\t\t\t\t\t\t\t\t\tAND host_snmp_cache.host_id = ?\n\t\t\t\t\t\t\t\t\t\t\tAND host_snmp_cache.snmp_query_id = snmp_query.id\n\t\t\t\t\t\t\t\t\t\t\tORDER by snmp_query.name", array(get_request_var_request('host_id')));
    }
    if (sizeof($snmp_queries) > 0) {
        foreach ($snmp_queries as $snmp_query) {
            print "<option value='" . $snmp_query['id'] . "'";
            if (get_request_var_request('snmp_query_id') == $snmp_query['id']) {
                print ' selected';
            }
            print '>' . $snmp_query['name'] . "</option>\n";
        }
    }
    ?>
						</select>
					</td>
					<td>
						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>
						<input type="button" id='refresh' name="go" value="Go" title="Set/Refresh Filters">
					</td>
					<td>
						<input type="button" id='clear' name="clear_x" value="Clear" title="Clear Fitlers">
					</td>
				</tr>
			</table>
			<table cellpadding='2' cellspacing='0' border='0'>
				<tr>
					<td width='50'>
						Search
					</td>
					<td>
						<input id='filter' type="text" name="filter" size="25" value="<?php 
    print htmlspecialchars(get_request_var_request('filter'));
    ?>
">
					</td>
				</tr>
			</table>
			<input type='hidden' id='page' name='page' value='<?php 
    print $_REQUEST['page'];
    ?>
'>
			<input type='hidden' name='action' value='view_snmp_cache'>
		</form>
		</td>
	</tr>
	<?php 
    html_end_box();
    $sql_where = '';
    /* filter by host */
    if (get_request_var_request('host_id') == '-1') {
        /* Show all items */
    } elseif (get_request_var_request('host_id') == '0') {
        $sql_where .= ' AND host.id=0';
    } elseif (!empty($_REQUEST['host_id'])) {
        $sql_where .= ' AND host.id=' . get_request_var_request('host_id');
    }
    /* filter by query name */
    if (get_request_var_request('snmp_query_id') == '-1') {
        /* Show all items */
    } elseif (!empty($_REQUEST['snmp_query_id'])) {
        $sql_where .= ' AND host_snmp_cache.snmp_query_id=' . get_request_var_request('snmp_query_id');
    }
    /* filter by search string */
    if (get_request_var_request('filter') != '') {
        $sql_where .= " AND (host.description LIKE '%%" . get_request_var_request('filter') . "%%'\n\t\t\tOR snmp_query.name LIKE '%%" . get_request_var_request('filter') . "%%'\n\t\t\tOR host_snmp_cache.field_name LIKE '%%" . get_request_var_request('filter') . "%%'\n\t\t\tOR host_snmp_cache.field_value LIKE '%%" . get_request_var_request('filter') . "%%'\n\t\t\tOR host_snmp_cache.oid LIKE '%%" . get_request_var_request('filter') . "%%')";
    }
    html_start_box('', '100%', '', '3', 'center', '');
    $total_rows = db_fetch_cell("SELECT\n\t\tCOUNT(*)\n\t\tFROM (host_snmp_cache, snmp_query,host)\n\t\tWHERE host_snmp_cache.host_id = host.id\n\t\tAND host_snmp_cache.snmp_query_id = snmp_query.id\n\t\t{$sql_where}");
    $snmp_cache_sql = "SELECT\n\t\thost_snmp_cache.*,\n\t\thost.description,\n\t\tsnmp_query.name\n\t\tFROM (host_snmp_cache, snmp_query,host)\n\t\tWHERE host_snmp_cache.host_id = host.id\n\t\tAND host_snmp_cache.snmp_query_id = snmp_query.id\n\t\t{$sql_where}\n\t\tLIMIT " . get_request_var_request('rows') * (get_request_var_request('page') - 1) . ',' . get_request_var_request('rows');
    $snmp_cache = db_fetch_assoc($snmp_cache_sql);
    $nav = html_nav_bar('utilities.php?action=view_snmp_cache&host_id=' . get_request_var_request('host_id') . '&filter=' . get_request_var_request('filter'), MAX_DISPLAY_PAGES, get_request_var_request('page'), get_request_var_request('rows'), $total_rows, 3, 'Entries', 'page', 'main');
    print $nav;
    html_header(array('Details'));
    $i = 0;
    if (sizeof($snmp_cache) > 0) {
        foreach ($snmp_cache as $item) {
            if ($i % 2 == 0) {
                $class = 'even';
            } else {
                $class = 'odd';
            }
            print "<tr class='{$class}'>\n";
            ?>
			<td>
				Device: <?php 
            print strlen(get_request_var_request('filter')) ? preg_replace('/(' . preg_quote(get_request_var_request('filter'), '/') . ')/i', "<span class='filteredValue'>\\1</span>", $item['description']) : $item['description'];
            ?>
				, SNMP Query: <?php 
            print strlen(get_request_var_request('filter')) ? preg_replace('/(' . preg_quote(get_request_var_request('filter'), '/') . ')/i', "<span class='filteredValue'>\\1</span>", $item['name']) : $item['name'];
            ?>
			</td>
			</tr>
			<?php 
            print "<tr class='{$class}'>\n";
            ?>
			<td>
				Index: <?php 
            print $item['snmp_index'];
            ?>
				, Field Name: <?php 
            print strlen(get_request_var_request('filter')) ? preg_replace('/(' . preg_quote(get_request_var_request('filter'), '/') . ')/i', "<span class='filteredValue'>\\1</span>", $item['field_name']) : $item['field_name'];
            ?>
				, Field Value: <?php 
            print strlen(get_request_var_request('filter')) ? preg_replace('/(' . preg_quote(get_request_var_request('filter'), '/') . ')/i', "<span class='filteredValue'>\\1</span>", $item['field_value']) : $item['field_value'];
            ?>
			</td>
			</tr>
			<?php 
            print "<tr class='{$class}'>\n";
            ?>
			<td>
				OID: <?php 
            print strlen(get_request_var_request('filter')) ? preg_replace('/(' . preg_quote(get_request_var_request('filter'), '/') . ')/i', "<span class='filteredValue'>\\1</span>", $item['oid']) : $item['oid'];
            ?>
			</td>
			</tr>
			<?php 
            $i++;
        }
        print $nav;
    }
    html_end_box();
}
コード例 #6
0
ファイル: boost.php プロジェクト: MrWnn/cacti
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);
    }
}
コード例 #7
0
ファイル: data_input.php プロジェクト: MrWnn/cacti
function data_edit()
{
    global $fields_data_input_edit;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    /* ==================================================== */
    if (!empty($_REQUEST['id'])) {
        $data_input = db_fetch_row_prepared('SELECT * FROM data_input WHERE id = ?', array(get_request_var_request('id')));
        $header_label = '[edit: ' . htmlspecialchars($data_input['name']) . ']';
    } else {
        $header_label = '[new]';
    }
    html_start_box("<strong>Data Input Methods</strong> {$header_label}", '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array(), 'fields' => inject_form_variables($fields_data_input_edit, isset($data_input) ? $data_input : array())));
    html_end_box();
    if (!empty($_REQUEST['id'])) {
        html_start_box('<strong>Input Fields</strong>', '100%', '', '3', 'center', 'data_input.php?action=field_edit&type=in&data_input_id=' . htmlspecialchars(get_request_var_request('id')));
        print "<tr class='tableHeader'>";
        DrawMatrixHeaderItem('Name', '', 1);
        DrawMatrixHeaderItem('Field Order', '', 1);
        DrawMatrixHeaderItem('Friendly Name', '', 2);
        print '</tr>';
        $fields = db_fetch_assoc_prepared("SELECT id, data_name, name, sequence FROM data_input_fields WHERE data_input_id = ? AND input_output = 'in' ORDER BY sequence, data_name", array(get_request_var_request('id')));
        $i = 0;
        if (sizeof($fields) > 0) {
            foreach ($fields as $field) {
                form_alternate_row('', true);
                ?>
				<td>
					<a class="linkEditMain" href="<?php 
                print htmlspecialchars('data_input.php?action=field_edit&id=' . $field['id'] . '&data_input_id=' . $_REQUEST['id']);
                ?>
"><?php 
                print htmlspecialchars($field['data_name']);
                ?>
</a>
				</td>
				<td>
					<?php 
                print $field['sequence'];
                if ($field['sequence'] == '0') {
                    print ' (Not In Use)';
                }
                ?>
				</td>
				<td>
					<?php 
                print htmlspecialchars($field['name']);
                ?>
				</td>
				<td align="right">
					<a href="<?php 
                print htmlspecialchars('data_input.php?action=field_remove&id=' . $field['id'] . '&data_input_id=' . $_REQUEST['id']);
                ?>
"><img src="images/delete_icon.gif" style="height:10px;width:10px;" border="0" alt="Delete"></a>
				</td>
			</tr>
		<?php 
            }
        } else {
            print '<tr><td><em>No Input Fields</em></td></tr>';
        }
        html_end_box();
        html_start_box('<strong>Output Fields</strong>', '100%', '', '3', 'center', 'data_input.php?action=field_edit&type=out&data_input_id=' . $_REQUEST['id']);
        print "<tr class='tableHeader'>";
        DrawMatrixHeaderItem('Name', '', 1);
        DrawMatrixHeaderItem('Field Order', '', 1);
        DrawMatrixHeaderItem('Friendly Name', '', 1);
        DrawMatrixHeaderItem('Update RRA', '', 2);
        print '</tr>';
        $fields = db_fetch_assoc_prepared("SELECT id, name, data_name, update_rra, sequence FROM data_input_fields WHERE data_input_id = ? and input_output = 'out' ORDER BY sequence, data_name", array(get_request_var_request('id')));
        $i = 0;
        if (sizeof($fields) > 0) {
            foreach ($fields as $field) {
                form_alternate_row('', true);
                ?>
				<td>
					<a class="linkEditMain" href="<?php 
                print htmlspecialchars('data_input.php?action=field_edit&id=' . $field['id'] . '&data_input_id=' . $_REQUEST['id']);
                ?>
"><?php 
                print htmlspecialchars($field['data_name']);
                ?>
</a>
				</td>
				<td>
					<?php 
                print $field['sequence'];
                if ($field['sequence'] == '0') {
                    print ' (Not In Use)';
                }
                ?>
				</td>
				<td>
					<?php 
                print htmlspecialchars($field['name']);
                ?>
				</td>
				<td>
					<?php 
                print html_boolean_friendly($field['update_rra']);
                ?>
				</td>
				<td align="right">
					<a href="<?php 
                print htmlspecialchars('data_input.php?action=field_remove&id=' . $field['id'] . '&data_input_id=' . $_REQUEST['id']);
                ?>
"><img src="images/delete_icon.gif" style="height:10px;width:10px;" border="0" alt="Delete"></a>
				</td>
			</tr>
		<?php 
            }
        } else {
            print '<tr><td><em>No Output Fields</em></td></tr>';
        }
        html_end_box();
    }
    form_save_button('data_input.php', 'return');
}
コード例 #8
0
ファイル: auth.php プロジェクト: MrWnn/cacti
function secpass_login_process()
{
    $users = db_fetch_assoc('SELECT username FROM user_auth WHERE realm = 0');
    $username = sanitize_search_string(get_request_var_post('login_username'));
    # Mark failed login attempts
    if (read_config_option('secpass_lockfailed') > 0) {
        $max = intval(read_config_option('secpass_lockfailed'));
        if ($max > 0) {
            $p = get_request_var_post('login_password');
            foreach ($users as $fa) {
                if ($fa['username'] == $username) {
                    $user = db_fetch_assoc_prepared("SELECT * FROM user_auth WHERE username = ? AND realm = 0 AND enabled = 'on'", array($username));
                    if (isset($user[0]['username'])) {
                        $user = $user[0];
                        $unlock = intval(read_config_option('secpass_unlocktime'));
                        if ($unlock > 1440) {
                            $unlock = 1440;
                        }
                        if ($unlock > 0 && time() - $user['lastfail'] > 60 * $unlock) {
                            db_execute_prepared("UPDATE user_auth SET lastfail = 0, failed_attempts = 0, locked = '' WHERE username = ? AND realm = 0 AND enabled = 'on'", array($username));
                            $user['failed_attempts'] = $user['lastfail'] = 0;
                            $user['locked'] == '';
                        }
                        if ($user['password'] != md5($p)) {
                            $failed = $user['failed_attempts'] + 1;
                            if ($failed >= $max) {
                                db_execute_prepared("UPDATE user_auth SET locked = 'on' WHERE username = ? AND realm = 0 AND enabled = 'on'", array($username));
                                $user['locked'] = 'on';
                            }
                            $user['lastfail'] = time();
                            db_execute_prepared("UPDATE user_auth SET lastfail = ?, failed_attempts = ? WHERE username = ? AND realm = 0 AND enabled = 'on'", array($user['lastfail'], $failed, $username));
                            if ($user['locked'] != '') {
                                auth_display_custom_error_message('This account has been locked.');
                                exit;
                            }
                            return false;
                        }
                        if ($user['locked'] != '') {
                            auth_display_custom_error_message('This account has been locked.');
                            exit;
                        }
                    }
                }
            }
        }
    }
    # Check if old password doesn't meet specifications and must be changed
    if (read_config_option('secpass_forceold') == 'on') {
        $p = get_request_var_post('login_password');
        $error = secpass_check_pass($p);
        if ($error != '') {
            foreach ($users as $fa) {
                if ($fa['username'] == $username) {
                    db_execute_prepared("UPDATE user_auth SET must_change_password = '******' WHERE username = ? AND password = ? AND realm = 0 AND enabled = 'on'", array($username, md5(get_request_var_post('login_password'))));
                    return true;
                }
            }
        }
    }
    # Set the last Login time
    if (read_config_option('secpass_expireaccount') > 0) {
        $p = get_request_var_post('login_password');
        foreach ($users as $fa) {
            if ($fa['username'] == $username) {
                db_execute_prepared("UPDATE user_auth SET lastlogin = ? WHERE username = ? AND password = ? AND realm = 0 AND enabled = 'on'", array(time(), $username, md5(get_request_var_post('login_password'))));
            }
        }
    }
    return true;
}
コード例 #9
0
ファイル: data_queries.php プロジェクト: MrWnn/cacti
function data_query_edit()
{
    global $fields_data_query_edit, $config;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    /* ==================================================== */
    if (!empty($_REQUEST['id'])) {
        $snmp_query = db_fetch_row_prepared('SELECT * FROM snmp_query WHERE id = ?', array($_REQUEST['id']));
        $header_label = '[edit: ' . htmlspecialchars($snmp_query['name']) . ']';
    } else {
        $header_label = '[new]';
    }
    html_start_box("<strong>Data Queries</strong> {$header_label}", '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array(), 'fields' => inject_form_variables($fields_data_query_edit, isset($snmp_query) ? $snmp_query : array())));
    html_end_box();
    if (!empty($snmp_query['id'])) {
        $xml_filename = str_replace('<path_cacti>', $config['base_path'], $snmp_query['xml_path']);
        if (file_exists($xml_filename) && is_file($xml_filename)) {
            $text = "<font color='#0d7c09'><strong>Successfully located XML file</strong></font>";
            $xml_file_exists = true;
        } else {
            $text = "<font class='txtErrorText'><strong>Could not locate XML file.</strong></font>";
            $xml_file_exists = false;
        }
        html_start_box('', '100%', '', '3', 'center', '');
        print "<tr class='tableRow'><td>{$text}</td></tr>";
        html_end_box();
        if ($xml_file_exists == true) {
            html_start_box('<strong>Associated Graph Templates</strong>', '100%', '', '3', 'center', 'data_queries.php?action=item_edit&snmp_query_id=' . $snmp_query['id']);
            print "<tr class='tableHeader'>\n\t\t\t\t\t<th class='textSubHeaderDark'>Name</th>\n\t\t\t\t\t<th class='textSubHeaderDark'>Graph Template Name</th>\n\t\t\t\t\t<th class='textSubHeaderDark' style='text-align:right;'>Mapping ID</th>\n\t\t\t\t\t<th width='40' style='text-align:right;'>Action</td>\n\t\t\t\t</tr>";
            $snmp_query_graphs = db_fetch_assoc_prepared('SELECT
				snmp_query_graph.id,
				graph_templates.name AS graph_template_name,
				snmp_query_graph.name
				FROM snmp_query_graph
				LEFT JOIN graph_templates ON (snmp_query_graph.graph_template_id = graph_templates.id)
				WHERE snmp_query_graph.snmp_query_id = ?
				ORDER BY snmp_query_graph.name', array($snmp_query['id']));
            $i = 0;
            if (sizeof($snmp_query_graphs) > 0) {
                foreach ($snmp_query_graphs as $snmp_query_graph) {
                    form_alternate_row();
                    ?>
						<td>
							<strong><a href="<?php 
                    print htmlspecialchars('data_queries.php?action=item_edit&id=' . $snmp_query_graph['id'] . '&snmp_query_id=' . $snmp_query['id']);
                    ?>
"><?php 
                    print htmlspecialchars($snmp_query_graph['name']);
                    ?>
</a></strong>
						</td>
						<td>
							<?php 
                    print htmlspecialchars($snmp_query_graph['graph_template_name']);
                    ?>
						</td>
						<td style='text-align:right;'>
							<?php 
                    print $snmp_query_graph['id'];
                    ?>
						</td>
						<td align="right">
							<a href="<?php 
                    print htmlspecialchars('data_queries.php?action=item_remove&id=' . $snmp_query_graph['id'] . '&snmp_query_id=' . $snmp_query['id']);
                    ?>
"><img src="images/delete_icon.gif" style="height:10px;width:10px;" border="0" alt="Delete"></a>
						</td>
					</tr>
					<?php 
                }
            } else {
                print "<tr class='tableRow'><td><em>No Graph Templates Defined.</em></td></tr>";
            }
            html_end_box();
        }
    }
    form_save_button('data_queries.php', 'return');
}
コード例 #10
0
function mactrack_interface_actions($device_id, $ifName, $show_rescan = TRUE)
{
    global $config;
    $row = '';
    $rescan = '';
    $device = db_fetch_row_prepared('SELECT host_id, disabled FROM mac_track_devices WHERE device_id = ?', array($device_id));
    if ($show_rescan) {
        if (api_user_realm_auth('mactrack_sites.php')) {
            if ($device['disabled'] == '') {
                $rescan = "<img id='r_" . $device_id . '_' . $ifName . "' src='" . $config['url_path'] . "plugins/mactrack/images/rescan_device.gif' alt='' onMouseOver='style.cursor=\"pointer\"' onClick='scan_device_interface(" . $device_id . ",\"" . $ifName . "\")' title='Rescan Device' align='absmiddle' border='0'>";
            } else {
                $rescan = "<img src='" . $config['url_path'] . "plugins/mactrack/images/view_none.gif' alt='' align='absmiddle' border='0'>";
            }
        } else {
            $rescan = "<img src='" . $config['url_path'] . "plugins/mactrack/images/view_none.gif' alt='' align='absmiddle' border='0'>";
        }
    }
    if ($device['host_id'] != 0) {
        /* get non-interface graphs */
        $graphs = db_fetch_assoc_prepared('SELECT DISTINCT graph_local.id AS local_graph_id
			FROM mac_track_interface_graphs
			RIGHT JOIN graph_local
			ON graph_local.host_id=mac_track_interface_graphs.host_id
			AND graph_local.id=mac_track_interface_graphs.local_graph_id
			WHERE graph_local.host_id = ? 
			AND mac_track_interface_graphs.device_id IS NULL', array($device['host_id']));
        if (sizeof($graphs)) {
            $url = $config['url_path'] . 'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list=';
            $list = '';
            foreach ($graphs as $graph) {
                $list .= (strlen($list) ? ',' : '') . $graph['local_graph_id'];
            }
            $row .= "<a href='" . htmlspecialchars($url . $list . '&page=1') . "'><img src='" . $config['url_path'] . "plugins/mactrack/images/view_graphs.gif' alt='' onMouseOver='style.cursor=\"pointer\"' title='" . __('View Non Interface Graphs') . "' align='absmiddle' border='0'></a>";
        } else {
            $row .= "<img src='" . $config['url_path'] . "plugins/mactrack/images/view_graphs_disabled.gif' alt='' title='" . __('No Non Interface Graphs in Cacti') . "' align='absmiddle' border='0'/>";
        }
        /* get interface graphs */
        $graphs = db_fetch_assoc_prepared('SELECT local_graph_id
			FROM mac_track_interface_graphs
			WHERE host_id = ? AND ifName = ?', array($device['host_id'], $ifName));
        if (sizeof($graphs)) {
            $url = $config['url_path'] . 'plugins/mactrack/mactrack_view_graphs.php?action=preview&report=graphs&style=selective&graph_list=';
            $list = '';
            foreach ($graphs as $graph) {
                $list .= (strlen($list) ? ',' : '') . $graph['local_graph_id'];
            }
            $row .= "<a href='" . htmlspecialchars($url . $list . '&page=1') . "'><img src='" . $config['url_path'] . "plugins/mactrack/images/view_interface_graphs.gif' alt='' onMouseOver='style.cursor=\"pointer\"' title='" . __('View Interface Graphs') . "' align='absmiddle' border='0'></a>";
        } else {
            $row .= "<img src='" . $config['url_path'] . "plugins/mactrack/images/view_none.gif' alt='' align='absmiddle' border='0'>";
        }
    } else {
        $row .= "<img src='" . $config['url_path'] . "plugins/mactrack/images/view_graphs_disabled.gif' alt='' title='" . __('Device Not in Cacti') . "' align='absmiddle' border='0'/>";
    }
    $row .= $rescan;
    return $row;
}
コード例 #11
0
ファイル: polling.php プロジェクト: Cacti/plugin_thold
function thold_update_host_status()
{
    global $config;
    // Return if we aren't set to notify
    $deadnotify = read_config_option('alert_deadnotify') == 'on';
    if (!$deadnotify) {
        return 0;
    }
    include_once $config['base_path'] . '/plugins/thold/thold_functions.php';
    if (api_plugin_is_enabled('maint')) {
        include_once $config['base_path'] . '/plugins/maint/functions.php';
    }
    $alert_email = read_config_option('alert_email');
    $ping_failure_count = read_config_option('ping_failure_count');
    // Lets find hosts that were down, but are now back up
    $failed = db_fetch_assoc('SELECT * FROM plugin_thold_host_failed');
    if (sizeof($failed)) {
        foreach ($failed as $fh) {
            if (!empty($fh['host_id'])) {
                if (api_plugin_is_enabled('maint')) {
                    if (plugin_maint_check_cacti_host($fh['host_id'])) {
                        continue;
                    }
                }
                $host = db_fetch_row('SELECT * FROM host WHERE id = ' . $fh['host_id']);
                if (isset($host['status']) && $host['status'] == HOST_UP) {
                    $snmp_system = '';
                    $snmp_hostname = '';
                    $snmp_location = '';
                    $snmp_contact = '';
                    $snmp_uptime = '';
                    $uptimelong = '';
                    $downtimemsg = '';
                    if ($host['snmp_community'] == '' && $host['snmp_username'] == '' || $host['snmp_version'] == 0) {
                        // SNMP not in use
                        $snmp_system = 'SNMP not in use';
                    } else {
                        $snmp_system = cacti_snmp_get($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.1.1.0', $host['snmp_version'], $host['snmp_username'], $host['snmp_password'], $host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'], $host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'], read_config_option('snmp_retries'), SNMP_WEBUI);
                        if (substr_count($snmp_system, '00:')) {
                            $snmp_system = str_replace('00:', '', $snmp_system);
                            $snmp_system = str_replace(':', ' ', $snmp_system);
                        }
                        if ($snmp_system != '') {
                            $snmp_uptime = cacti_snmp_get($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.1.3.0', $host['snmp_version'], $host['snmp_username'], $host['snmp_password'], $host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'], $host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'], read_config_option('snmp_retries'), SNMP_WEBUI);
                            $snmp_hostname = cacti_snmp_get($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.1.5.0', $host['snmp_version'], $host['snmp_username'], $host['snmp_password'], $host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'], $host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'], read_config_option('snmp_retries'), SNMP_WEBUI);
                            $snmp_location = cacti_snmp_get($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.1.6.0', $host['snmp_version'], $host['snmp_username'], $host['snmp_password'], $host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'], $host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'], read_config_option('snmp_retries'), SNMP_WEBUI);
                            $snmp_contact = cacti_snmp_get($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.1.4.0', $host['snmp_version'], $host['snmp_username'], $host['snmp_password'], $host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'], $host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'], read_config_option('snmp_retries'), SNMP_WEBUI);
                            $days = intval($snmp_uptime / (60 * 60 * 24 * 100));
                            $remainder = $snmp_uptime % (60 * 60 * 24 * 100);
                            $hours = intval($remainder / (60 * 60 * 100));
                            $remainder = $remainder % (60 * 60 * 100);
                            $minutes = intval($remainder / (60 * 100));
                            $uptimelong = $days . 'd ' . $hours . 'h ' . $minutes . 'm';
                        }
                        $downtime = time() - strtotime($host['status_fail_date']);
                        $downtime_days = floor($downtime / 86400);
                        $downtime_hours = floor(($downtime - $downtime_days * 86400) / 3600);
                        $downtime_minutes = floor(($downtime - $downtime_days * 86400 - $downtime_hours * 3600) / 60);
                        $downtime_seconds = $downtime - $downtime_days * 86400 - $downtime_hours * 3600 - $downtime_minutes * 60;
                        if ($downtime_days > 0) {
                            $downtimemsg = $downtime_days . 'd ' . $downtime_hours . 'h ' . $downtime_minutes . 'm ' . $downtime_seconds . 's ';
                        } elseif ($downtime_hours > 0) {
                            $downtimemsg = $downtime_hours . 'h ' . $downtime_minutes . 'm ' . $downtime_seconds . 's';
                        } elseif ($downtime_minutes > 0) {
                            $downtimemsg = $downtime_minutes . 'm ' . $downtime_seconds . 's';
                        } else {
                            $downtimemsg = $downtime_seconds . 's ';
                        }
                    }
                    $subject = read_config_option('thold_up_subject');
                    if ($subject == '') {
                        $subject = 'Devices Notice: <DESCRIPTION> (<HOSTNAME>) returned from DOWN state';
                    }
                    $subject = str_replace('<HOSTNAME>', $host['hostname'], $subject);
                    $subject = str_replace('<DESCRIPTION>', $host['description'], $subject);
                    $subject = str_replace('<DOWN/UP>', 'UP', $subject);
                    $subject = strip_tags($subject);
                    $msg = read_config_option('thold_up_text');
                    if ($msg == '') {
                        $msg = __('<br>System <DESCRIPTION> (<HOSTNAME>) status: <DOWN/UP><br><br>Current ping response: <CUR_TIME> ms<br>Average system response : <AVG_TIME> ms<br>System availability: <AVAILABILITY><br>Total Checks Since Clear: <TOT_POLL><br>Total Failed Checks: <FAIL_POLL><br>Last Date Checked UP: <LAST_FAIL><br>Devices Previously DOWN for: <DOWNTIME><br><br>Snmp Info:<br>Name - <SNMP_HOSTNAME><br>Location - <SNMP_LOCATION><br>Uptime - <UPTIMETEXT> (<UPTIME> ms)<br>System - <SNMP_SYSTEM><br><br>NOTE: <NOTES>');
                    }
                    $msg = str_replace('<SUBJECT>', $subject, $msg);
                    $msg = str_replace('<HOSTNAME>', $host['hostname'], $msg);
                    $msg = str_replace('<DESCRIPTION>', $host['description'], $msg);
                    $msg = str_replace('<UPTIME>', $snmp_uptime, $msg);
                    $msg = str_replace('<UPTIMETEXT>', $uptimelong, $msg);
                    $msg = str_replace('<DOWNTIME>', $downtimemsg, $msg);
                    $msg = str_replace('<MESSAGE>', '', $msg);
                    $msg = str_replace('<DOWN/UP>', 'UP', $msg);
                    $msg = str_replace('<SNMP_HOSTNAME>', $snmp_hostname, $msg);
                    $msg = str_replace('<SNMP_LOCATION>', $snmp_location, $msg);
                    $msg = str_replace('<SNMP_CONTACT>', $snmp_contact, $msg);
                    $msg = str_replace('<SNMP_SYSTEM>', html_split_string($snmp_system), $msg);
                    $msg = str_replace('<LAST_FAIL>', $host['status_fail_date'], $msg);
                    $msg = str_replace('<AVAILABILITY>', round($host['availability'], 2) . ' %', $msg);
                    $msg = str_replace('<TOT_POLL>', $host['total_polls'], $msg);
                    $msg = str_replace('<FAIL_POLL>', $host['failed_polls'], $msg);
                    $msg = str_replace('<CUR_TIME>', round($host['cur_time'], 2), $msg);
                    $msg = str_replace('<AVG_TIME>', round($host['avg_time'], 2), $msg);
                    $msg = str_replace('<NOTES>', $host['notes'], $msg);
                    $msg = str_replace("\n", '<br>', $msg);
                    switch ($host['thold_send_email']) {
                        case '0':
                            // Disabled
                            $alert_email = '';
                            break;
                        case '1':
                            // Global List
                            break;
                        case '2':
                            // Devices List Only
                            $alert_email = get_thold_notification_emails($host['thold_host_email']);
                            break;
                        case '3':
                            // Global and Devices List
                            $alert_email = $alert_email . ',' . get_thold_notification_emails($host['thold_host_email']);
                            break;
                    }
                    if ($alert_email == '' && $host['thold_send_email'] > 0) {
                        cacti_log('Host[' . $host['id'] . '] Hostname[' . $host['hostname'] . '] WARNING: Can not send a Device recovering email for \'' . $host['description'] . '\' since the \'Alert Email\' setting is not set for Device!', true, 'THOLD');
                    } elseif ($host['thold_send_email'] == '0') {
                        cacti_log('Host[' . $host['id'] . '] Hostname[' . $host['hostname'] . '] NOTE: Did not send a Device recovering email for \'' . $host['description'] . '\', disabled per Device setting!', true, 'THOLD');
                    } elseif ($alert_email != '') {
                        thold_mail($alert_email, '', $subject, $msg, '');
                    }
                }
            }
        }
    }
    // Lets find hosts that are down
    $hosts = db_fetch_assoc_prepared('SELECT *
		FROM host
		WHERE disabled=""
		AND status = ?
		AND status_event_count = ?', array(HOST_DOWN, $ping_failure_count));
    $total_hosts = sizeof($hosts);
    if (count($hosts)) {
        foreach ($hosts as $host) {
            if (api_plugin_is_enabled('maint')) {
                if (plugin_maint_check_cacti_host($host['id'])) {
                    continue;
                }
            }
            $downtime = time() - strtotime($host['status_rec_date']);
            $downtime_days = floor($downtime / 86400);
            $downtime_hours = floor(($downtime - $downtime_days * 86400) / 3600);
            $downtime_minutes = floor(($downtime - $downtime_days * 86400 - $downtime_hours * 3600) / 60);
            $downtime_seconds = $downtime - $downtime_days * 86400 - $downtime_hours * 3600 - $downtime_minutes * 60;
            if ($downtime_days > 0) {
                $downtimemsg = $downtime_days . 'd ' . $downtime_hours . 'h ' . $downtime_minutes . 'm ' . $downtime_seconds . 's ';
            } elseif ($downtime_hours > 0) {
                $downtimemsg = $downtime_hours . 'h ' . $downtime_minutes . 'm ' . $downtime_seconds . 's';
            } elseif ($downtime_minutes > 0) {
                $downtimemsg = $downtime_minutes . 'm ' . $downtime_seconds . 's';
            } else {
                $downtimemsg = $downtime_seconds . 's ';
            }
            $subject = read_config_option('thold_down_subject');
            if ($subject == '') {
                $subject = __('Devices Error: <DESCRIPTION> (<HOSTNAME>) is DOWN');
            }
            $subject = str_replace('<HOSTNAME>', $host['hostname'], $subject);
            $subject = str_replace('<DESCRIPTION>', $host['description'], $subject);
            $subject = str_replace('<DOWN/UP>', 'DOWN', $subject);
            $subject = strip_tags($subject);
            $msg = read_config_option('thold_down_text');
            if ($msg == '') {
                $msg = __('System Error : <DESCRIPTION> (<HOSTNAME>) is <DOWN/UP><br>Reason: <MESSAGE><br><br>Average system response : <AVG_TIME> ms<br>System availability: <AVAILABILITY><br>Total Checks Since Clear: <TOT_POLL><br>Total Failed Checks: <FAIL_POLL><br>Last Date Checked DOWN : <LAST_FAIL><br>Devices Previously UP for: <DOWNTIME><br>NOTE: <NOTES>');
            }
            $msg = str_replace('<SUBJECT>', $subject, $msg);
            $msg = str_replace('<HOSTNAME>', $host['hostname'], $msg);
            $msg = str_replace('<DESCRIPTION>', $host['description'], $msg);
            $msg = str_replace('<UPTIME>', '', $msg);
            $msg = str_replace('<DOWNTIME>', $downtimemsg, $msg);
            $msg = str_replace('<MESSAGE>', $host['status_last_error'], $msg);
            $msg = str_replace('<DOWN/UP>', 'DOWN', $msg);
            $msg = str_replace('<SNMP_HOSTNAME>', '', $msg);
            $msg = str_replace('<SNMP_LOCATION>', '', $msg);
            $msg = str_replace('<SNMP_CONTACT>', '', $msg);
            $msg = str_replace('<SNMP_SYSTEM>', '', $msg);
            $msg = str_replace('<LAST_FAIL>', $host['status_fail_date'], $msg);
            $msg = str_replace('<AVAILABILITY>', round($host['availability'], 2) . ' %', $msg);
            $msg = str_replace('<CUR_TIME>', round($host['cur_time'], 2), $msg);
            $msg = str_replace('<TOT_POLL>', $host['total_polls'], $msg);
            $msg = str_replace('<FAIL_POLL>', $host['failed_polls'], $msg);
            $msg = str_replace('<AVG_TIME>', round($host['avg_time'], 2), $msg);
            $msg = str_replace('<NOTES>', $host['notes'], $msg);
            $msg = str_replace("\n", '<br>', $msg);
            switch ($host['thold_send_email']) {
                case '0':
                    // Disabled
                    $alert_email = '';
                    break;
                case '1':
                    // Global List
                    break;
                case '2':
                    // Devices List Only
                    $alert_email = get_thold_notification_emails($host['thold_host_email']);
                    break;
                case '3':
                    // Global and Devices List
                    $alert_email = $alert_email . ',' . get_thold_notification_emails($host['thold_host_email']);
                    break;
            }
            if ($alert_email == '' && $host['thold_send_email'] > 0) {
                cacti_log('Host[' . $host['id'] . '] Hostname[' . $host['hostname'] . '] WARNING: Can not send a Device down email for \'' . $host['description'] . '\' since the \'Alert Email\' setting is not set for Device!', true, 'THOLD');
            } elseif ($host['thold_send_email'] == '0') {
                cacti_log('Host[' . $host['id'] . '] Hostname[' . $host['hostname'] . '] NOTE: Did not send a Device down email for \'' . $host['description'] . '\', disabled per Device setting!', true, 'THOLD');
            } elseif ($alert_email != '') {
                thold_mail($alert_email, '', $subject, $msg, '');
            }
        }
    }
    // Now lets record all failed hosts
    db_execute('TRUNCATE TABLE plugin_thold_host_failed');
    $hosts = db_fetch_assoc('SELECT id
		FROM host
		WHERE disabled = ""
		AND status != ' . HOST_UP);
    $failed = '';
    if (sizeof($hosts)) {
        foreach ($hosts as $host) {
            if (api_plugin_is_enabled('maint')) {
                if (plugin_maint_check_cacti_host($host['id'])) {
                    continue;
                }
            }
            $failed .= (strlen($failed) ? '), (' : '(') . $host['id'];
        }
        $failed .= ')';
        db_execute("INSERT INTO plugin_thold_host_failed (host_id) VALUES {$failed}");
    }
    return $total_hosts;
}
コード例 #12
0
ファイル: api_tree.php プロジェクト: MrWnn/cacti
function api_tree_delete_node_content($tree_id, $branch_id)
{
    $children = db_fetch_assoc_prepared("SELECT * \n\t\tFROM graph_tree_items \n\t\tWHERE graph_tree_id = ? AND parent = ?", array($tree_id, $branch_id));
    if (sizeof($children)) {
        foreach ($children as $child) {
            if ($child['host_id'] == 0 && $child['graph_id'] == 0) {
                api_tree_delete_node_content($tree_id, $child['id']);
            }
            db_execute_prepared("DELETE \n\t\t\tFROM graph_tree_items \n\t\t\tWHERE graph_tree_id = ?\n\t\t\tAND id = ?", array($tree_id, $child['id']));
        }
    }
}
コード例 #13
0
ファイル: auth_login.php プロジェクト: MrWnn/cacti
         if (basename($referer) == 'logout.php') {
             $referer = $config['url_path'] . 'index.php';
         }
     } else {
         if (isset($_SERVER['REQUEST_URI'])) {
             $referer = $_SERVER['REQUEST_URI'];
             if (basename($referer) == 'logout.php') {
                 $referer = $config['url_path'] . 'index.php';
             }
         } else {
             $referer = $config['url_path'] . 'index.php';
         }
     }
     if (substr_count($referer, 'plugins')) {
         header('Location: ' . $referer);
     } elseif (sizeof(db_fetch_assoc_prepared('SELECT realm_id FROM user_auth_realm WHERE realm_id = 8 AND user_id = ?', array($_SESSION['sess_user_id']))) == 0) {
         header('Location: graph_view.php');
     } else {
         header("Location: {$referer}");
     }
     break;
 case '2':
     /* default console page */
     header('Location: ' . $config['url_path'] . 'index.php');
     break;
 case '3':
     /* default graph page */
     header('Location: ' . $config['url_path'] . 'graph_view.php');
     break;
 default:
     api_plugin_hook_function('login_options_navigate', $user['login_opts']);
コード例 #14
0
ファイル: data_sources.php プロジェクト: MrWnn/cacti
function ds_edit()
{
    global $struct_data_source, $struct_data_source_item, $data_source_types;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('host_id'));
    /* ==================================================== */
    api_plugin_hook('data_source_edit_top');
    $use_data_template = true;
    $host_id = 0;
    if (!empty($_REQUEST['id'])) {
        $data_local = db_fetch_row_prepared('SELECT host_id, data_template_id FROM data_local WHERE id = ?', array($_REQUEST['id']));
        $data = db_fetch_row_prepared('SELECT * FROM data_template_data WHERE local_data_id = ?', array($_REQUEST['id']));
        if (isset($data_local['data_template_id']) && $data_local['data_template_id'] >= 0) {
            $data_template = db_fetch_row_prepared('SELECT id, name FROM data_template WHERE id = ?', array($data_local['data_template_id']));
            $data_template_data = db_fetch_row_prepared('SELECT * FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', array($data_local['data_template_id']));
        } else {
            $_SESSION['sess_messages'] = 'Data Source "' . $_REQUEST['id'] . '" does not exist.';
            header('Location: data_sources.php');
            exit;
        }
        $header_label = '[edit: ' . htmlspecialchars(get_data_source_title($_REQUEST['id'])) . ']';
        if (empty($data_local['data_template_id'])) {
            $use_data_template = false;
        }
    } else {
        $header_label = '[new]';
        $use_data_template = false;
    }
    /* handle debug mode */
    if (isset($_REQUEST['debug'])) {
        if ($_REQUEST['debug'] == '0') {
            kill_session_var('ds_debug_mode');
        } elseif ($_REQUEST['debug'] == '1') {
            $_SESSION['ds_debug_mode'] = true;
        }
    }
    top_header();
    if (!empty($_REQUEST['id'])) {
        ?>
		<table width='100%' align='center'>
			<tr>
				<td class='textInfo' colspan='2' valign='top'>
					<?php 
        print htmlspecialchars(get_data_source_title($_REQUEST['id']));
        ?>
				</td>
				<td class='textInfo' align='right' valign='top'>
					<span class='linkMarker'>*<a href='<?php 
        print htmlspecialchars('data_sources.php?action=ds_edit&id=' . (isset($_REQUEST['id']) ? $_REQUEST['id'] : '0'));
        ?>
&debug=<?php 
        print isset($_SESSION['ds_debug_mode']) ? '0' : '1';
        ?>
'>Turn <strong><?php 
        print isset($_SESSION['ds_debug_mode']) ? 'Off' : 'On';
        ?>
</strong> Data Source Debug Mode.</a><br>
					<?php 
        if (!empty($data_template['id'])) {
            ?>
<span class='linkMarker'>*<a href='<?php 
            print htmlspecialchars('data_templates.php?action=template_edit&id=' . (isset($data_template['id']) ? $data_template['id'] : '0'));
            ?>
'>Edit Data Template.</a><br><?php 
        }
        if (!empty($_REQUEST['host_id']) || !empty($data_local['host_id'])) {
            ?>
<span class='linkMarker'>*<a href='<?php 
            print htmlspecialchars('host.php?action=edit&id=' . (isset($_REQUEST['host_id']) ? $_REQUEST['host_id'] : $data_local['host_id']));
            ?>
'>Edit Device.</a><br><?php 
        }
        ?>
				</td>
			</tr>
		</table>
		<br>
		<?php 
    }
    html_start_box("<strong>Data Template Selection</strong> {$header_label}", '100%', '', '3', 'center', '');
    $form_array = array('data_template_id' => array('method' => 'drop_sql', 'friendly_name' => 'Selected Data Template', 'description' => 'The name given to this data template.', 'value' => isset($data_template) ? $data_template['id'] : '0', 'none_value' => 'None', 'sql' => 'SELECT id,name FROM data_template order by name'), 'host_id' => array('method' => 'drop_sql', 'friendly_name' => 'Device', 'description' => 'Choose the host that this graph belongs to.', 'value' => isset($_REQUEST['host_id']) ? $_REQUEST['host_id'] : $data_local['host_id'], 'none_value' => 'None', 'sql' => "SELECT id,CONCAT_WS('',description,' (',hostname,')') as name FROM host order by description,hostname"), '_data_template_id' => array('method' => 'hidden', 'value' => isset($data_template) ? $data_template['id'] : '0'), '_host_id' => array('method' => 'hidden', 'value' => empty($data_local['host_id']) ? isset($_REQUEST['host_id']) ? $_REQUEST['host_id'] : '0' : $data_local['host_id']), '_data_input_id' => array('method' => 'hidden', 'value' => isset($data['data_input_id']) ? $data['data_input_id'] : '0'), 'data_template_data_id' => array('method' => 'hidden', 'value' => isset($data) ? $data['id'] : '0'), 'local_data_template_data_id' => array('method' => 'hidden', 'value' => isset($data) ? $data['local_data_template_data_id'] : '0'), 'local_data_id' => array('method' => 'hidden', 'value' => isset($data) ? $data['local_data_id'] : '0'));
    draw_edit_form(array('config' => array(), 'fields' => $form_array));
    html_end_box();
    /* only display the "inputs" area if we are using a data template for this data source */
    if (!empty($data['data_template_id'])) {
        $template_data_rrds = db_fetch_assoc_prepared('SELECT * FROM data_template_rrd WHERE local_data_id = ? ORDER BY data_source_name', array($_REQUEST['id']));
        html_start_box('<strong>Supplemental Data Template Data</strong>', '100%', '', '3', 'center', '');
        draw_nontemplated_fields_data_source($data['data_template_id'], $data['local_data_id'], $data, '|field|', '<strong>Data Source Fields</strong>', true, true, 0);
        draw_nontemplated_fields_data_source_item($data['data_template_id'], $template_data_rrds, '|field|_|id|', '<strong>Data Source Item Fields</strong>', true, true, true, 0);
        draw_nontemplated_fields_custom_data($data['id'], 'value_|id|', '<strong>Custom Data</strong>', true, true, 0);
        form_hidden_box('save_component_data', '1', '');
        html_end_box();
    }
    if ((isset($_REQUEST['id']) || isset($_REQUEST['new'])) && empty($data['data_template_id'])) {
        html_start_box('<strong>Data Source</strong>', '100%', '', '3', 'center', '');
        $form_array = array();
        while (list($field_name, $field_array) = each($struct_data_source)) {
            $form_array += array($field_name => $struct_data_source[$field_name]);
            if (!($use_data_template == false || !empty($data_template_data['t_' . $field_name]) || $field_array['flags'] == 'NOTEMPLATE')) {
                $form_array[$field_name]['description'] = '';
            }
            $form_array[$field_name]['value'] = isset($data[$field_name]) ? $data[$field_name] : '';
            $form_array[$field_name]['form_id'] = empty($data['id']) ? '0' : $data['id'];
            if (!($use_data_template == false || !empty($data_template_data['t_' . $field_name]) || $field_array['flags'] == 'NOTEMPLATE')) {
                $form_array[$field_name]['method'] = 'template_' . $form_array[$field_name]['method'];
            }
        }
        draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => inject_form_variables($form_array, isset($data) ? $data : array())));
        html_end_box();
        /* fetch ALL rrd's for this data source */
        if (!empty($_REQUEST['id'])) {
            $template_data_rrds = db_fetch_assoc_prepared('SELECT id, data_source_name FROM data_template_rrd WHERE local_data_id = ? ORDER BY data_source_name', array($_REQUEST['id']));
        }
        /* select the first "rrd" of this data source by default */
        if (empty($_REQUEST['view_rrd'])) {
            $_REQUEST['view_rrd'] = isset($template_data_rrds[0]['id']) ? $template_data_rrds[0]['id'] : '0';
        }
        /* get more information about the rrd we chose */
        if (!empty($_REQUEST['view_rrd'])) {
            $local_data_template_rrd_id = db_fetch_cell_prepared('SELECT local_data_template_rrd_id FROM data_template_rrd WHERE id = ?', array($_REQUEST['view_rrd']));
            $rrd = db_fetch_row_prepared('SELECT * FROM data_template_rrd WHERE id = ?', array($_REQUEST['view_rrd']));
            $rrd_template = db_fetch_row_prepared('SELECT * FROM data_template_rrd WHERE id = ?', array($local_data_template_rrd_id));
            $header_label = '[edit: ' . $rrd['data_source_name'] . ']';
        } else {
            $header_label = '';
        }
        $i = 0;
        if (isset($template_data_rrds)) {
            if (sizeof($template_data_rrds) > 1) {
                /* draw the data source tabs on the top of the page */
                print "\t<table class='tabs' width='100%' cellspacing='0' cellpadding='3' align='center'>\n\t\t\t\t\t<tr>\n";
                foreach ($template_data_rrds as $template_data_rrd) {
                    $i++;
                    print "\t<td " . ($template_data_rrd['id'] == $_REQUEST['view_rrd'] ? "class='even'" : "class='odd'") . " width='" . (strlen($template_data_rrd['data_source_name']) * 9 + 50) . "' align='center' class='tab'>\n\t\t\t\t\t\t\t\t<span class='textHeader'><a href='" . htmlspecialchars('data_sources.php?action=ds_edit&id=' . $_REQUEST['id'] . '&view_rrd=' . $template_data_rrd['id']) . "'>{$i}: " . htmlspecialchars($template_data_rrd['data_source_name']) . '</a>' . ($use_data_template == false ? " <a href='" . htmlspecialchars('data_sources.php?action=rrd_remove&id=' . $template_data_rrd['id'] . '&local_data_id=' . $_REQUEST['id']) . "'><img src='images/delete_icon.gif' border='0' alt='Delete'></a>" : '') . "</span>\n\t\t\t\t\t\t\t</td>\n\n\t\t\t\t\t\t\t<td width='1'></td>\n";
                }
                print "\n\t\t\t\t\t<td></td>\n\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n";
            } elseif (sizeof($template_data_rrds) == 1) {
                $_REQUEST['view_rrd'] = $template_data_rrds[0]['id'];
            }
        }
        html_start_box('', '100%', '', '3', 'center', '');
        print "\t<tr>\n\t\t\t\t<td class='textHeaderDark'>\n\t\t\t\t\t<strong>Data Source Item</strong> {$header_label}\n\t\t\t\t</td>\n\t\t\t\t<td class='textHeaderDark' align='right'>\n\t\t\t\t\t" . (!empty($_REQUEST['id']) && empty($data_template['id']) ? "<strong><a class='linkOverDark' href='" . htmlspecialchars('data_sources.php?action=rrd_add&id=' . $_REQUEST['id']) . "'>New</a>&nbsp;</strong>" : '') . "\n\t\t\t\t</td>\n\t\t\t</tr>\n";
        /* data input fields list */
        if (empty($data['data_input_id']) || db_fetch_cell_prepared('SELECT type_id FROM data_input WHERE id = ?', array($data['data_input_id'])) > '1') {
            unset($struct_data_source_item['data_input_field_id']);
        } else {
            $struct_data_source_item['data_input_field_id']['sql'] = "SELECT id,CONCAT(data_name,' - ',name) as name FROM data_input_fields WHERE data_input_id=" . $data['data_input_id'] . " and input_output='out' and update_rra='on' order by data_name,name";
        }
        $form_array = array();
        while (list($field_name, $field_array) = each($struct_data_source_item)) {
            $form_array += array($field_name => $struct_data_source_item[$field_name]);
            if (!($use_data_template == false || $rrd_template['t_' . $field_name] == 'on')) {
                $form_array[$field_name]['description'] = '';
            }
            $form_array[$field_name]['value'] = isset($rrd) ? $rrd[$field_name] : '';
            if (!($use_data_template == false || $rrd_template['t_' . $field_name] == 'on')) {
                $form_array[$field_name]['method'] = 'template_' . $form_array[$field_name]['method'];
            }
        }
        draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => array('data_template_rrd_id' => array('method' => 'hidden', 'value' => isset($rrd) ? $rrd['id'] : '0'), 'local_data_template_rrd_id' => array('method' => 'hidden', 'value' => isset($rrd) ? $rrd['local_data_template_rrd_id'] : '0')) + $form_array));
        html_end_box();
        /* data source data goes here */
        data_edit();
        form_hidden_box('current_rrd', $_REQUEST['view_rrd'], '0');
    }
    /* display the debug mode box if the user wants it */
    if (isset($_SESSION['ds_debug_mode']) && isset($_REQUEST['id'])) {
        ?>
		<table width='100%' align='center'>
			<tr>
				<td>
					<span class='textInfo'>Data Source Debug</span><br>
					<pre><?php 
        print @rrdtool_function_create($_REQUEST['id'], true);
        ?>
</pre>
				</td>
			</tr>
		</table>
		<?php 
    }
    if (isset($_REQUEST['id']) || isset($_REQUEST['new'])) {
        form_hidden_box('save_component_data_source', '1', '');
    } else {
        form_hidden_box('save_component_data_source_new', '1', '');
    }
    form_save_button('data_sources.php');
    api_plugin_hook('data_source_edit_bottom');
    bottom_footer();
}
コード例 #15
0
ファイル: poller_maintenance.php プロジェクト: MrWnn/cacti
function remove_files($file_array)
{
    global $config, $debug, $archived, $purged;
    include_once $config['library_path'] . '/api_graph.php';
    include_once $config['library_path'] . '/api_data_source.php';
    maint_debug('RRDClean is now running on ' . sizeof($file_array) . ' items');
    /* determine the location of the RRA files */
    if (isset($config['rra_path'])) {
        $rra_path = $config['rra_path'];
    } else {
        $rra_path = $config['base_path'] . '/rra';
    }
    /* let's prepare the archive directory */
    $rrd_archive = read_config_option('rrd_archive', TRUE);
    if ($rrd_archive == '') {
        $rrd_archive = $rra_path . '/archive';
    }
    rrdclean_create_path($rrd_archive);
    /* now scan the files */
    foreach ($file_array as $file) {
        $source_file = $rra_path . '/' . $file['name'];
        switch ($file['action']) {
            case '1':
                if (unlink($source_file)) {
                    maint_debug('Deleted: ' . $file['name']);
                } else {
                    cacti_log($file['name'] . " Error: unable to delete from {$rra_path}!", true, 'MAINT');
                }
                $purged++;
                break;
            case '3':
                $target_file = $rrd_archive . '/' . $file['name'];
                $target_dir = dirname($target_file);
                if (!is_dir($target_dir)) {
                    rrdclean_create_path($target_dir);
                }
                if (rename($source_file, $target_file)) {
                    maint_debug('Moved: ' . $file['name'] . ' to: ' . $rrd_archive);
                } else {
                    cacti_log($file['name'] . " Error: unable to move to {$rrd_archive}!", true, 'MAINT');
                }
                $archived++;
                break;
        }
        /* drop from data_source_purge_action table */
        db_execute_prepared('DELETE FROM `data_source_purge_action` WHERE name = ?', array($file['name']));
        maint_debug('Delete from data_source_purge_action: ' . $file['name']);
        //fetch all local_graph_id's according to this data source
        $lgis = db_fetch_assoc_prepared('SELECT DISTINCT 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 dtr.id=gti.task_item_id
			INNER JOIN data_local AS dl
			ON dtr.local_data_id=dl.id
			WHERE (local_data_id=?)', array($file['local_data_id']));
        if (sizeof($lgis)) {
            /* anything found? */
            cacti_log('Processing ' . sizeof($lgis) . ' Graphs for data source id: ' . $file['local_data_id'], true, 'MAINT');
            /* get them all */
            foreach ($lgis as $item) {
                $remove_lgis[] = $item['id'];
                cacti_log('remove local_graph_id=' . $item['id'], true, 'MAINT');
            }
            /* and remove them in a single run */
            if (!empty($remove_lgis)) {
                api_graph_remove_multi($remove_lgis);
            }
        }
        /* remove related data source if any */
        if ($file['local_data_id'] > 0) {
            cacti_log('removing data source: ' . $file['local_data_id'], true, 'MAINT');
            api_data_source_remove($file['local_data_id']);
        }
    }
    cacti_log('RRDClean has finished a purge pass of ' . sizeof($file_array) . ' items', true, 'MAINT');
}
コード例 #16
0
function mactrack_device_filter()
{
    global $item_rows;
    ?>
	<tr class='even'>
		<td>
		<form id='mactrack'>
			<table class='filterTable'>
				<tr>
					<td>
						<?php 
    print __('Search');
    ?>
					</td>
					<td>
						<input type='text' id='filter' size='25' value='<?php 
    print get_request_var('filter');
    ?>
'>
					</td>
					<td>
						<?php 
    print __('Site');
    ?>
					</td>
					<td>
						<select id='site_id' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('site_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('All');
    ?>
</option>
							<option value='-2'<?php 
    if (get_request_var('site_id') == '-2') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('None');
    ?>
</option>
							<?php 
    $sites = db_fetch_assoc('SELECT site_id, site_name FROM mac_track_sites ORDER BY site_name');
    if (sizeof($sites)) {
        foreach ($sites as $site) {
            print '<option value="' . $site['site_id'] . '"';
            if (get_request_var('site_id') == $site['site_id']) {
                print ' selected';
            }
            print '>' . $site['site_name'] . '</option>';
        }
    }
    ?>
						</select>
					</td>
					<td>
						<input type='submit' id='go' value='<?php 
    print __('Go');
    ?>
'>
					</td>
					<td>
						<input type='button' id='clear' value='<?php 
    print __('Clear');
    ?>
'>
					</td>
					<td>
						<input type='button' id='import' value='<?php 
    print __('Import');
    ?>
'>
					</td>
					<td>
						<input type='submit' id='export' value='<?php 
    print __('Export');
    ?>
'>
					</td>
				</tr>
			</table>
			<table class='filterTable'>
				<tr>
					<td>
						<?php 
    print __('Type');
    ?>
					</td>
					<td>
						<select id='type_id' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('type_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Any');
    ?>
</option>
							<option value='1'<?php 
    if (get_request_var('type_id') == '1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Switch/Hub');
    ?>
</option>
							<option value='2'<?php 
    if (get_request_var('type_id') == '2') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Switch/Router');
    ?>
</option>
							<option value='3'<?php 
    if (get_request_var('type_id') == '3') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Router');
    ?>
</option>
						</select>
					</td>
					<td>
						<?php 
    print __('SubType');
    ?>
					</td>
					<td>
						<select id='device_type_id' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('device_type_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Any');
    ?>
</option>
							<option value='-2'<?php 
    if (get_request_var('device_type_id') == '-2') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Not Detected');
    ?>
</option>
							<?php 
    if (get_request_var('type_id') != -1) {
        $device_types = db_fetch_assoc_prepared('SELECT DISTINCT
									mac_track_devices.device_type_id,
									mac_track_device_types.description,
									mac_track_device_types.sysDescr_match
									FROM mac_track_device_types
									INNER JOIN mac_track_devices 
									ON mac_track_device_types.device_type_id = mac_track_devices.device_type_id
									WHERE device_type = ?
									ORDER BY mac_track_device_types.description', array(get_request_var('type_id')));
    } else {
        $device_types = db_fetch_assoc('SELECT DISTINCT
									mac_track_devices.device_type_id,
									mac_track_device_types.description,
									mac_track_device_types.sysDescr_match
									FROM mac_track_device_types
									INNER JOIN mac_track_devices 
									ON mac_track_device_types.device_type_id=mac_track_devices.device_type_id
									ORDER BY mac_track_device_types.description');
    }
    if (sizeof($device_types) > 0) {
        foreach ($device_types as $device_type) {
            if ($device_type['device_type_id'] == 0) {
                $display_text = 'Unknown Device Type';
            } else {
                $display_text = $device_type['description'] . ' (' . $device_type['sysDescr_match'] . ')';
            }
            print '<option value="' . $device_type['device_type_id'] . '"';
            if (get_request_var('device_type_id') == $device_type['device_type_id']) {
                print ' selected';
            }
            print '>' . $display_text . '</option>';
        }
    }
    ?>
						</select>
					</td>
				</tr>
			</table>
			<table class='filterTable'>
				<tr>
					<td>
						<?php 
    print __('Status');
    ?>
					</td>
					<td>
						<select id='status' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('status') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Any');
    ?>
</option>
							<option value='3'<?php 
    if (get_request_var('status') == '3') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Up');
    ?>
</option>
							<option value='-2'<?php 
    if (get_request_var('status') == '-2') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Disabled');
    ?>
</option>
							<option value='1'<?php 
    if (get_request_var('status') == '1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Down');
    ?>
</option>
							<option value='0'<?php 
    if (get_request_var('status') == '0') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Unknown');
    ?>
</option>
							<option value='4'<?php 
    if (get_request_var('status') == '4') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Error');
    ?>
</option>
							<option value='5'<?php 
    if (get_request_var('status') == '5') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('No Cacti Link');
    ?>
</option>
						</select>
					</td>
					<td>
						<?php 
    print __('Devices');
    ?>
					</td>
					<td>
						<select id='rows' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('rows') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Default');
    ?>
</option>
							<?php 
    if (sizeof($item_rows)) {
        foreach ($item_rows as $key => $value) {
            print "<option value='" . $key . "'";
            if (get_request_var('rows') == $key) {
                print ' selected';
            }
            print '>' . $value . '</option>';
        }
    }
    ?>
						</select>
					</td>
				</tr>
			</table>
		</form>
		<script type='text/javascript'>
		function applyFilter() {
			strURL  = urlPath+'plugins/mactrack/mactrack_devices.php?header=false';
			strURL += '&site_id=' + $('#site_id').val();
			strURL += '&status=' + $('#status').val();
			strURL += '&type_id=' + $('#type_id').val();
			strURL += '&device_type_id=' + $('#device_type_id').val();
			strURL += '&filter=' + $('#filter').val();
			strURL += '&rows=' + $('#rows').val();
			loadPageNoHeader(strURL);
		}

		function clearFilter() {
			strURL  = urlPath+'plugins/mactrack/mactrack_devices.php?header=false&clear=true';
			loadPageNoHeader(strURL);
		}

		function exportRows() {
			strURL  = urlPath+'plugins/mactrack/mactrack_devices.php?export=true';
			document.location = strURL;
		}

		function importRows() {
			strURL  = urlPath+'plugins/mactrack/mactrack_devices.php?import=true';
			loadPageNoHeader(strURL);
		}

		$(function() {
			$('#mactrack').submit(function(event) {
				event.preventDefault();
				applyFilter();
			});

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

			$('#export').click(function() {
				exportRows();
			});

			$('#import').click(function() {
				importRows();
			});
		});
		</script>
		</td>
	</tr>
	<?php 
}
コード例 #17
0
ファイル: cmd.php プロジェクト: MrWnn/cacti
            $ping->port = $hosts[$host_id]['ping_port'];
            /* perform the appropriate ping check of the host */
            if ($ping->ping($hosts[$host_id]['availability_method'], $hosts[$host_id]['ping_method'], $hosts[$host_id]['ping_timeout'], $hosts[$host_id]['ping_retries'])) {
                $host_down = false;
                update_host_status(HOST_UP, $host_id, $hosts, $ping, $hosts[$host_id]['availability_method'], $print_data_to_stdout);
                if ($mibs && $hosts[$host_id]['availability_method'] != 0 && $hosts[$host_id]['availability_method'] != 3) {
                    update_system_mibs($host_id);
                }
            } else {
                $host_down = true;
                update_host_status(HOST_DOWN, $host_id, $hosts, $ping, $hosts[$host_id]['availability_method'], $print_data_to_stdout);
            }
            if (!$host_down) {
                /* do the reindex check for this host */
                $reindex = db_fetch_assoc_prepared('SELECT pr.data_query_id, pr.action,
					pr.op, pr.assert_value, pr.arg1
					FROM poller_reindex AS pr
					WHERE pr.host_id=?', array($item['host_id']));
                if (sizeof($reindex) > 0 && !$host_down) {
                    if (read_config_option('log_verbosity') >= POLLER_VERBOSITY_DEBUG) {
                        cacti_log("Device[{$host_id}] RECACHE: Processing " . sizeof($reindex) . " items in the auto reindex cache for '" . $item['hostname'] . "'.", $print_data_to_stdout);
                    }
                    foreach ($reindex as $index_item) {
                        $assert_fail = false;
                        /* do the check */
                        switch ($index_item['action']) {
                            case POLLER_ACTION_SNMP:
                                /* snmp */
                                if (read_config_option('log_verbosity') >= POLLER_VERBOSITY_DEBUG) {
                                    cacti_log("Device[{$host_id}] RECACHE DQ[" . $index_item['data_query_id'] . '] OID: ' . $index_item['arg1'], $print_data_to_stdout);
                                }
                                $output = cacti_snmp_get($item['hostname'], $item['snmp_community'], $index_item['arg1'], $item['snmp_version'], $item['snmp_username'], $item['snmp_password'], $item['snmp_auth_protocol'], $item['snmp_priv_passphrase'], $item['snmp_priv_protocol'], $item['snmp_context'], $item['snmp_port'], $item['snmp_timeout'], read_config_option('snmp_retries'), SNMP_CMDPHP);
コード例 #18
0
function mactrack_mac_filter()
{
    global $item_rows, $rows_selector, $mactrack_search_types;
    ?>
	<tr class='even'>
		<td>
			<form id='mactrack'>
			<table class='filterTable'>
				<tr>
					<td>
						<?php 
    print __('Search');
    ?>
					</td>
					<td>
						<input type='text' id='filter' size='25' value='<?php 
    print get_request_var('filter');
    ?>
'>
					</td>
					<td>
						<?php 
    print __('Site');
    ?>
					</td>
					<td>
						<select id='site_id' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('site_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('N/A');
    ?>
</option>
							<?php 
    $sites = db_fetch_assoc('select site_id,site_name from mac_track_sites order by site_name');
    if (sizeof($sites)) {
        foreach ($sites as $site) {
            print '<option value="' . $site['site_id'] . '"';
            if (get_request_var('site_id') == $site['site_id']) {
                print ' selected';
            }
            print '>' . $site['site_name'] . '</option>';
        }
    }
    ?>
						</select>
					</td>
					<td>
						<?php 
    print __('Device');
    ?>
					</td>
					<td>
						<select id='device_id' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('device_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('All');
    ?>
</option>
							<?php 
    if (get_request_var('site_id') == -1) {
        $filter_devices = db_fetch_assoc('SELECT device_id, device_name, hostname 
									FROM mac_track_devices 
									ORDER BY device_name');
    } else {
        $filter_devices = db_fetch_assoc_prepared('SELECT device_id, device_name, hostname 
									FROM mac_track_devices 
									WHERE site_id = ? 
									ORDER BY device_name', array(get_request_var('site_id')));
    }
    if (sizeof($filter_devices)) {
        foreach ($filter_devices as $filter_device) {
            print '<option value=" ' . $filter_device['device_id'] . '"';
            if (get_request_var('device_id') == $filter_device['device_id']) {
                print ' selected';
            }
            print '>' . $filter_device['device_name'] . '(' . $filter_device['hostname'] . ')' . '</option>';
        }
    }
    ?>
						</select>
					</td>
					<td>
						<?php 
    print __('MAC\'s');
    ?>
					</td>
					<td>
						<select id='rows' onChange='applyFilter()'>
							<?php 
    if (sizeof($rows_selector) > 0) {
        foreach ($rows_selector as $key => $value) {
            print '<option value="' . $key . '"';
            if (get_request_var('rows') == $key) {
                print ' selected';
            }
            print '>' . $value . '</option>\\n';
        }
    }
    ?>
						</select>
					</td>
					<td>
						<input type='submit' id='go' value='<?php 
    print __('Go');
    ?>
'>
					</td>
					<td>
						<input type='button' id='clear' value='<?php 
    print __('Clear');
    ?>
'>
					</td>
					<td>
						<input type='button' id='export' value='<?php 
    print __('Export');
    ?>
'>
					</td>
				</tr>
			</table>
			<table class='filterTable'>
				<tr>
					<td>
						<?php 
    print __('IP');
    ?>
					</td>
					<td>
						<select id='ip_filter_type_id'>
							<?php 
    for ($i = 1; $i <= sizeof($mactrack_search_types); $i++) {
        print "<option value='" . $i . "'";
        if (get_request_var('ip_filter_type_id') == $i) {
            print ' selected';
        }
        print '>' . $mactrack_search_types[$i] . '</option>';
    }
    ?>
						</select>
					</td>
					<td>
						<input type='text' id='ip_filter' size='25' value='<?php 
    print get_request_var('ip_filter');
    ?>
'>
					</td>
					<td>
						<?php 
    print __('VLAN Name');
    ?>
					</td>
					<td>
						<select id='vlan' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('vlan') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('All');
    ?>
</option>
							<?php 
    $sql_where = '';
    if (get_request_var('device_id') != '-1') {
        $sql_where = 'WHERE device_id=' . get_request_var('device_id');
    }
    if (get_request_var('site_id') != '-1') {
        if (strlen($sql_where)) {
            $sql_where .= ' AND site_id=' . get_request_var('site_id');
        } else {
            $sql_where = 'WHERE site_id=' . get_request_var('site_id');
        }
    }
    $vlans = db_fetch_assoc("SELECT DISTINCT vlan_id, vlan_name \n\t\t\t\t\t\t\t\tFROM mac_track_vlans \n\t\t\t\t\t\t\t\t{$sql_where} \n\t\t\t\t\t\t\t\tORDER BY vlan_name ASC");
    if (sizeof($vlans)) {
        foreach ($vlans as $vlan) {
            print '<option value="' . $vlan['vlan_id'] . '"';
            if (get_request_var('vlan') == $vlan['vlan_id']) {
                print ' selected';
            }
            print '>' . $vlan['vlan_name'] . '</option>';
        }
    }
    ?>
						</select>
					</td>
					<td>
						<?php 
    print __('Show');
    ?>
					</td>
					<td>
						<select id='scan_date' onChange='applyFilter()'>
							<option value='1'<?php 
    if (get_request_var('scan_date') == '1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('All');
    ?>
</option>
							<option value='2'<?php 
    if (get_request_var('scan_date') == '2') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Most Recent');
    ?>
</option>
							<option value='3'<?php 
    if (get_request_var('scan_date') == '3') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Aggregated');
    ?>
</option>
							<?php 
    $scan_dates = db_fetch_assoc('SELECT scan_date FROM mac_track_scan_dates ORDER BY scan_date DESC');
    if (sizeof($scan_dates)) {
        foreach ($scan_dates as $scan_date) {
            print '<option value="' . $scan_date['scan_date'] . '"';
            if (get_request_var('scan_date') == $scan_date['scan_date']) {
                print ' selected';
            }
            print '>' . $scan_date['scan_date'] . '</option>';
        }
    }
    ?>
						</select>
					</td>
				</tr>
				<tr>
					<td>
						<?php 
    print __('MAC');
    ?>
					</td>
					<td>
						<select id='mac_filter_type_id'>
							<?php 
    for ($i = 1; $i <= sizeof($mactrack_search_types) - 2; $i++) {
        print "<option value='" . $i . "'";
        if (get_request_var('mac_filter_type_id') == $i) {
            print ' selected';
        }
        print '>' . $mactrack_search_types[$i] . '</option>';
    }
    ?>
						</select>
					</td>
					<td>
						<input type='text' id='mac_filter' size='25' value='<?php 
    print get_request_var('mac_filter');
    ?>
'>
					</td>
					<td>
						<?php 
    print __('Authorized');
    ?>
					</td>
					<td>
						<select id='authorized' onChange='applyFilter()'>
							<option value='-1'<?php 
    if (get_request_var('authorized') == '-1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('All');
    ?>
</option>
							<option value='1'<?php 
    if (get_request_var('authorized') == '1') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('Yes');
    ?>
</option>
							<option value='0'<?php 
    if (get_request_var('authorized') == '0') {
        ?>
 selected<?php 
    }
    ?>
><?php 
    print __('No');
    ?>
</option>
						</select>
					</td>
				</tr>
				<tr>
					<td>
						<?php 
    print __('Portname');
    ?>
					</td>
					<td>
						<select id='port_name_filter_type_id'>
							<?php 
    for ($i = 1; $i <= sizeof($mactrack_search_types); $i++) {
        print "<option value='" . $i . "'";
        if (get_request_var('port_name_filter_type_id') == $i) {
            print ' selected';
        }
        print '>' . $mactrack_search_types[$i] . '</option>';
    }
    ?>
						</select>
					</td>
					<td>
						<input type='text' id='port_name_filter' size='25' value='<?php 
    print get_request_var('port_name_filter');
    ?>
'>
					</td>
					<td colspan='2'>
					</td>
				</tr>
			</table>
			</form>
			<script type='text/javascript'>

			function applyFilter() {
				strURL  = urlPath+'plugins/mactrack/mactrack_view_macs.php?report=macs&header=false';
				strURL += '&site_id=' + $('#site_id').val();
				strURL += '&device_id=' + $('#device_id').val();
				strURL += '&rows=' + $('#rows').val();
				strURL += '&mac_filter_type_id=' + $('#mac_filter_type_id').val();
				strURL += '&mac_filter=' + $('#mac_filter').val();
				strURL += '&filter=' + $('#filter').val();
				strURL += '&ip_filter_type_id=' + $('#ip_filter_type_id').val();
				strURL += '&ip_filter=' + $('#ip_filter').val();
				strURL += '&scan_date=' + $('#scan_date').val();
				strURL += '&authorized=' + $('#authorized').val();
				strURL += '&vlan=' + $('#vlan').val();

				loadPageNoHeader(strURL);
			}

			function clearFilter() {
				strURL  = urlPath+'plugins/mactrack/mactrack_view_macs.php?report=macs&header=false&clear=true';
				loadPageNoHeader(strURL);
			}

			function exportRows() {
				strURL  = urlPath+'plugins/mactrack/mactrack_view_macs.php?report=macs&export=true';
				document.location = strURL;
			}

			$(function() {
				$('#mactrack').submit(function(event) {
					event.preventDefault();
					applyFilter();
				});

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

				$('#export').click(function() {
					exportRows();
				});
			});

			</script>
		</td>
	</tr>
	<?php 
}
コード例 #19
0
ファイル: data_templates.php プロジェクト: MrWnn/cacti
function template_edit()
{
    global $struct_data_source, $struct_data_source_item, $data_source_types, $fields_data_template_template_edit;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('view_rrd'));
    /* ==================================================== */
    if (!empty($_REQUEST['id'])) {
        $template_data = db_fetch_row_prepared('SELECT * FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', array($_REQUEST['id']));
        $template = db_fetch_row_prepared('SELECT * FROM data_template WHERE id = ?', array($_REQUEST['id']));
        $header_label = '[edit: ' . $template['name'] . ']';
    } else {
        $header_label = '[new]';
    }
    html_start_box('<strong>Data Templates</strong> ' . htmlspecialchars($header_label), '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array(), 'fields' => inject_form_variables($fields_data_template_template_edit, isset($template) ? $template : array(), isset($template_data) ? $template_data : array(), $_REQUEST)));
    html_end_box();
    html_start_box('<strong>Data Source</strong>', '100%', '', '3', 'center', '');
    /* make sure 'data source path' doesn't show up for a template... we should NEVER template this field */
    unset($struct_data_source['data_source_path']);
    $form_array = array();
    while (list($field_name, $field_array) = each($struct_data_source)) {
        $form_array += array($field_name => $struct_data_source[$field_name]);
        if ($field_array['flags'] == 'ALWAYSTEMPLATE') {
            $form_array[$field_name]['description'] = '<em>This field is always templated.</em>';
        } else {
            $form_array[$field_name]['description'] = '';
            $form_array[$field_name]['sub_checkbox'] = array('name' => 't_' . $field_name, 'friendly_name' => 'Use Per-Data Source Value (Ignore this Value)', 'value' => isset($template_data['t_' . $field_name]) ? $template_data['t_' . $field_name] : '');
        }
        $form_array[$field_name]['value'] = isset($template_data[$field_name]) ? $template_data[$field_name] : '';
        $form_array[$field_name]['form_id'] = isset($template_data) ? $template_data['data_template_id'] : '0';
    }
    draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => inject_form_variables($form_array, isset($template_data) ? $template_data : array())));
    html_end_box();
    /* fetch ALL rrd's for this data source */
    if (!empty($_REQUEST['id'])) {
        $template_data_rrds = db_fetch_assoc_prepared('SELECT id, data_source_name FROM data_template_rrd WHERE data_template_id = ? AND local_data_id = 0 ORDER BY data_source_name', array($_REQUEST['id']));
    }
    /* select the first "rrd" of this data source by default */
    if (empty($_REQUEST['view_rrd'])) {
        $_REQUEST['view_rrd'] = isset($template_data_rrds[0]['id']) ? $template_data_rrds[0]['id'] : '0';
    }
    /* get more information about the rrd we chose */
    if (!empty($_REQUEST['view_rrd'])) {
        $template_rrd = db_fetch_row_prepared('SELECT * FROM data_template_rrd WHERE id = ?', array($_REQUEST['view_rrd']));
    }
    $i = 0;
    if (isset($template_data_rrds)) {
        if (sizeof($template_data_rrds) > 1) {
            /* draw the data source tabs on the top of the page */
            print "\t<div class='tabs' style='float:left;'><nav><ul>\n";
            foreach ($template_data_rrds as $template_data_rrd) {
                $i++;
                print "\t<li>\n\t\t\t\t<a " . ($template_data_rrd['id'] == $_REQUEST['view_rrd'] ? "class='selected'" : "class=''") . " href='" . htmlspecialchars('data_templates.php?action=template_edit&id=' . $_REQUEST['id'] . '&view_rrd=' . $template_data_rrd['id']) . "'>{$i}: " . htmlspecialchars($template_data_rrd['data_source_name']) . "</a>\n\t\t\t\t<span><a class='deleteMarker' href='" . htmlspecialchars('data_templates.php?action=rrd_remove&id=' . $template_data_rrd['id'] . '&data_template_id=' . $_REQUEST['id']) . "'><img src='images/delete_icon.gif' border='0' alt='Delete'></a></span></li>\n";
            }
            print "\n\t\t</ul></nav>\n\n\t\t</div>\n";
        } elseif (sizeof($template_data_rrds) == 1) {
            $_REQUEST['view_rrd'] = $template_data_rrds[0]['id'];
        }
    }
    html_start_box('<strong>Data Source Item</strong> [' . (isset($template_rrd) ? htmlspecialchars($template_rrd['data_source_name']) : '') . ']', '100%', '', '3', 'center', !empty($_REQUEST['id']) ? htmlspecialchars('data_templates.php?action=rrd_add&id=' . $_REQUEST['id']) : '', '<strong>New</scrong>');
    /* data input fields list */
    if (empty($template_data['data_input_id']) || db_fetch_cell('SELECT type_id FROM data_input WHERE id=' . $template_data['data_input_id']) != '1' && db_fetch_cell('SELECT type_id FROM data_input WHERE id=' . $template_data['data_input_id']) != '5') {
        unset($struct_data_source_item['data_input_field_id']);
    } else {
        $struct_data_source_item['data_input_field_id']['sql'] = "SELECT id,CONCAT(data_name,' - ',name) AS name FROM data_input_fields WHERE data_input_id=" . $template_data['data_input_id'] . " AND input_output='out' AND update_rra='on' ORDER BY data_name,name";
    }
    $form_array = array();
    while (list($field_name, $field_array) = each($struct_data_source_item)) {
        $form_array += array($field_name => $struct_data_source_item[$field_name]);
        $form_array[$field_name]['description'] = '';
        $form_array[$field_name]['value'] = isset($template_rrd) ? $template_rrd[$field_name] : '';
        $form_array[$field_name]['sub_checkbox'] = array('name' => 't_' . $field_name, 'friendly_name' => 'Use Per-Data Source Value (Ignore this Value)', 'value' => isset($template_rrd) ? $template_rrd['t_' . $field_name] : '');
    }
    draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array + array('data_template_rrd_id' => array('method' => 'hidden', 'value' => isset($template_rrd) ? $template_rrd['id'] : '0'))));
    html_end_box();
    $i = 0;
    if (!empty($_REQUEST['id'])) {
        /* get each INPUT field for this data input source */
        $fields = db_fetch_assoc('SELECT * FROM data_input_fields WHERE data_input_id=' . $template_data['data_input_id'] . " AND input_output='in' ORDER BY name");
        html_start_box('<strong>Custom Data</strong> [data input: ' . htmlspecialchars(db_fetch_cell('SELECT name FROM data_input WHERE id=' . $template_data['data_input_id'])) . ']', '100%', '', '3', 'center', '');
        /* loop through each field found */
        if (sizeof($fields) > 0) {
            foreach ($fields as $field) {
                $data_input_data = db_fetch_row('SELECT t_value,value FROM data_input_data WHERE data_template_data_id=' . $template_data['id'] . ' AND data_input_field_id=' . $field['id']);
                if (sizeof($data_input_data) > 0) {
                    $old_value = $data_input_data['value'];
                } else {
                    $old_value = '';
                }
                form_alternate_row();
                ?>
				<td width="50%">
					<strong><?php 
                print $field['name'];
                ?>
</strong><br>
					<?php 
                form_checkbox('t_value_' . $field['data_name'], $data_input_data['t_value'], 'Use Per-Data Source Value (Ignore this Value)', '', '', $_REQUEST['id']);
                ?>
				</td>
				<td>
					<?php 
                form_text_box('value_' . $field['data_name'], $old_value, '', '');
                ?>
					<?php 
                if (preg_match('/^' . VALID_HOST_FIELDS . '$/i', $field['type_code']) && $data_input_data['t_value'] == '') {
                    print "<br><em>Value will be derived from the host if this field is left empty.</em>\n";
                }
                ?>
				</td>
			</tr>
			<?php 
                $i++;
            }
        } else {
            print '<tr><td><em>No Input Fields for the Selected Data Input Source</em></td></tr>';
        }
        html_end_box();
    }
    form_save_button('data_templates.php', 'return');
}
コード例 #20
0
ファイル: database.php プロジェクト: MrWnn/cacti
function db_fetch_assoc($sql, $log = TRUE, $db_conn = FALSE)
{
    return db_fetch_assoc_prepared($sql, array(), $log, $db_conn);
}
コード例 #21
0
function mactrack_snmp_edit()
{
    global $config, $fields_mactrack_snmp_edit;
    include_once $config['base_path'] . '/plugins/mactrack/lib/mactrack_functions.php';
    /* ================= input validation ================= */
    get_filter_request_var('id');
    get_filter_request_var('page');
    /* ==================================================== */
    /* clean up rule name */
    if (isset_request_var('name')) {
        set_request_var('name', sanitize_search_string(get_request_var('name')));
    }
    /* remember these search fields in session vars so we don't have to keep passing them around */
    load_current_session_value('page', 'sess_mactrack_edit_current_page', '1');
    load_current_session_value('rows', 'sess_default_rows', read_config_option('num_rows_table'));
    /* display the mactrack snmp option set */
    $snmp_group = array();
    if (!isempty_request_var('id')) {
        $snmp_group = db_fetch_row_prepared('SELECT * FROM mac_track_snmp where id = ?', array(get_request_var('id')));
        $header_label = __('SNMP Option Set [edit: %s]', $snmp_group['name']);
    } else {
        $header_label = __('SNMP Option Set [new]');
    }
    form_start('mactrack_snmp.php', 'mactrack_snmp_group');
    html_start_box($header_label, '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => inject_form_variables($fields_mactrack_snmp_edit, $snmp_group)));
    html_end_box();
    form_hidden_box('id', isset_request_var('id') ? get_request_var('id') : '0', '');
    form_hidden_box('save_component_mactrack_snmp', '1', '');
    if (!isempty_request_var('id')) {
        $items = db_fetch_assoc_prepared('SELECT * FROM mac_track_snmp_items WHERE snmp_id= ? ORDER BY sequence', array(get_request_var('id')));
        html_start_box(__('Mactrack SNMP Options'), '100%', '', '3', 'center', 'mactrack_snmp.php?action=item_edit&id=' . get_request_var('id'));
        print "<tr class='tableHeader'>";
        DrawMatrixHeaderItem(__('Item'), '', 1);
        DrawMatrixHeaderItem(__('Version'), '', 1);
        DrawMatrixHeaderItem(__('Community'), '', 1);
        DrawMatrixHeaderItem(__('Port'), '', 1);
        DrawMatrixHeaderItem(__('Timeout'), '', 1);
        DrawMatrixHeaderItem(__('Retries'), '', 1);
        DrawMatrixHeaderItem(__('Max OIDs'), '', 1);
        DrawMatrixHeaderItem(__('Username'), '', 1);
        DrawMatrixHeaderItem(__('Auth Proto'), '', 1);
        DrawMatrixHeaderItem(__('Priv Proto'), '', 1);
        DrawMatrixHeaderItem(__('Actions'), '', 1);
        print '</tr>';
        $i = 1;
        if (sizeof($items)) {
            foreach ($items as $item) {
                form_alternate_row();
                $form_data = '<td><a class="linkEditMain" href="' . htmlspecialchars('mactrack_snmp.php?action=item_edit&item_id=' . $item['id'] . '&id=' . $item['snmp_id']) . '">Item#' . $i . '</a></td>';
                $form_data .= '<td>' . $item['snmp_version'] . '</td>';
                $form_data .= '<td>' . ($item['snmp_version'] == 3 ? __('N/A') : $item['snmp_readstring']) . '</td>';
                $form_data .= '<td>' . $item['snmp_port'] . '</td>';
                $form_data .= '<td>' . $item['snmp_timeout'] . '</td>';
                $form_data .= '<td>' . $item['snmp_retries'] . '</td>';
                $form_data .= '<td>' . $item['max_oids'] . '</td>';
                $form_data .= '<td>' . ($item['snmp_version'] == 3 ? $item['snmp_username'] : __('N/A')) . '</td>';
                $form_data .= '<td>' . ($item['snmp_version'] == 3 ? $item['snmp_auth_protocol'] : __('N/A')) . '</td>';
                $form_data .= '<td>' . ($item['snmp_version'] == 3 ? $item['snmp_priv_protocol'] : __('N/A')) . '</td>';
                $form_data .= '<td class="right">' . ($i < sizeof($items) ? '<a class="remover fa fa-caret-down moveArrow" href="' . htmlspecialchars($config['url_path'] . 'plugins/mactrack/mactrack_snmp.php?action=item_movedown&item_id=' . $item["id"] . '&id=' . $item["snmp_id"]) . '"></a>' : '<span class="moveArrowNone"></span>') . ($i > 1 ? '<a class="remover fa fa-caret-up moveArrow" href="' . htmlspecialchars($config['url_path'] . 'plugins/mactrack/mactrack_snmp.php?action=item_moveup&item_id=' . $item["id"] . '&id=' . $item["snmp_id"]) . '"></a>' : '<span class="moveArrowNone"></span>');
                $form_data .= '<a class="delete deleteMarker fa fa-remove" href="' . htmlspecialchars($config['url_path'] . 'plugins/mactrack/mactrack_snmp.php?action=item_remove&item_id=' . $item["id"] . '&id=' . $item["snmp_id"]) . '"></a>' . '</td></tr>';
                print $form_data;
                $i++;
            }
        } else {
            print '<tr><td colspan="5"><em>' . __('No SNMP Items') . '</em></td></tr>';
        }
        html_end_box();
    }
    form_save_button('mactrack_snmp.php');
}
コード例 #22
0
ファイル: thold.php プロジェクト: Cacti/plugin_thold
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 
}
コード例 #23
0
ファイル: plugins.php プロジェクト: MrWnn/cacti
function api_plugin_remove_realms($plugin)
{
    $realms = db_fetch_assoc_prepared('SELECT id FROM plugin_realms WHERE plugin = ?', array($plugin), false);
    foreach ($realms as $realm) {
        $id = $realm['id'] + 100;
        db_execute_prepared('DELETE FROM user_auth_realm WHERE realm_id = ?', array($id));
        db_execute_prepared('DELETE FROM user_auth_group_realm WHERE realm_id = ?', array($id));
    }
    db_execute_prepared('DELETE FROM plugin_realms WHERE plugin = ?', array($plugin));
}
コード例 #24
0
ファイル: api_data_source.php プロジェクト: MrWnn/cacti
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;
                }
            }
        }
    }
}
コード例 #25
0
ファイル: variables.php プロジェクト: MrWnn/cacti
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;
}
コード例 #26
0
ファイル: functions.php プロジェクト: MrWnn/cacti
function get_associated_rras($local_graph_id)
{
    return db_fetch_assoc_prepared('SELECT
		rra.id,
		rra.steps,
		rra.rows,
		rra.name,
		rra.timespan,
		data_template_data.rrd_step
		FROM graph_templates_item
		LEFT JOIN data_template_rrd ON (graph_templates_item.task_item_id = data_template_rrd.id)
		LEFT JOIN data_template_data ON (data_template_rrd.local_data_id = data_template_data.local_data_id)
		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)
                WHERE graph_templates_item.local_graph_id = ?
		AND data_template_rrd.local_data_id != 0
		GROUP BY rra.id
		ORDER BY rra.timespan', array($local_graph_id));
}
コード例 #27
0
ファイル: host_templates.php プロジェクト: MrWnn/cacti
function template_edit()
{
    global $fields_host_template_edit;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    /* ==================================================== */
    if (!empty($_REQUEST['id'])) {
        $host_template = db_fetch_row_prepared('SELECT * FROM host_template WHERE id = ?', array(get_request_var_request('id')));
        $header_label = '[edit: ' . $host_template['name'] . ']';
    } else {
        $header_label = '[new]';
        $_REQUEST['id'] = 0;
    }
    html_start_box('<strong>Device Templates</strong> ' . htmlspecialchars($header_label), '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array('form_name' => 'chk'), 'fields' => inject_form_variables($fields_host_template_edit, isset($host_template) ? $host_template : 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();
    if (!empty($_REQUEST['id'])) {
        html_start_box('<strong>Associated Graph Templates</strong>', '100%', '', '3', 'center', '');
        $selected_graph_templates = db_fetch_assoc_prepared('SELECT
			graph_templates.id,
			graph_templates.name
			FROM (graph_templates,host_template_graph)
			WHERE graph_templates.id = host_template_graph.graph_template_id
			AND host_template_graph.host_template_id = ?
			ORDER BY graph_templates.name', array(get_request_var_request('id')));
        $i = 0;
        if (sizeof($selected_graph_templates) > 0) {
            foreach ($selected_graph_templates as $item) {
                form_alternate_row('', true);
                ?>
					<td style="padding: 4px;">
						<strong><?php 
                print $i;
                ?>
)</strong> <?php 
                print htmlspecialchars($item['name']);
                ?>
					</td>
					<td align="right">
						<a href='<?php 
                print htmlspecialchars('host_templates.php?action=item_remove_gt&id=' . $item['id'] . '&host_template_id=' . $_REQUEST['id']);
                ?>
'><img src='images/delete_icon.gif' style="height:10px;width:10px;" border='0' alt='Delete'></a>
					</td>
				<?php 
                form_end_row();
                $i++;
            }
        } else {
            print '<tr><td><em>No associated graph templates.</em></td></tr>';
        }
        ?>
		<tr class='odd'>
			<td colspan="2">
				<table cellspacing="0" cellpadding="1" width="100%">
					<td nowrap>Add Graph Template:&nbsp;
						<?php 
        form_dropdown('graph_template_id', db_fetch_assoc_prepared('SELECT
							graph_templates.id,
							graph_templates.name
							FROM graph_templates LEFT JOIN host_template_graph
							ON (graph_templates.id = host_template_graph.graph_template_id AND host_template_graph.host_template_id = ?)
							WHERE host_template_graph.host_template_id is null
							ORDER BY graph_templates.name', array(get_request_var_request('id'))), 'name', 'id', '', '', '');
        ?>
					</td>
					<td align="right">
						&nbsp;<input type="submit" value="Add" name="add_gt_x" title="Add Graph Template to Device Template">
					</td>
				</table>
			</td>
		</tr>

		<?php 
        html_end_box();
        html_start_box('<strong>Associated Data Queries</strong>', '100%', '', '3', 'center', '');
        $selected_data_queries = db_fetch_assoc_prepared('SELECT
			snmp_query.id,
			snmp_query.name
			FROM (snmp_query, host_template_snmp_query)
			WHERE snmp_query.id = host_template_snmp_query.snmp_query_id
			AND host_template_snmp_query.host_template_id = ?
			ORDER BY snmp_query.name', array(get_request_var_request('id')));
        $i = 0;
        if (sizeof($selected_data_queries) > 0) {
            foreach ($selected_data_queries as $item) {
                form_alternate_row('', true);
                ?>
					<td style="padding: 4px;">
						<strong><?php 
                print $i;
                ?>
)</strong> <?php 
                print htmlspecialchars($item['name']);
                ?>
					</td>
					<td align='right'>
						<a href='<?php 
                print htmlspecialchars('host_templates.php?action=item_remove_dq&id=' . $item['id'] . '&host_template_id=' . $_REQUEST['id']);
                ?>
'><img src='images/delete_icon.gif' style="height:10px;width:10px;" border='0' alt='Delete'></a>
					</td>
				<?php 
                form_end_row();
                $i++;
            }
        } else {
            print '<tr><td><em>No associated data queries.</em></td></tr>';
        }
        ?>
		<tr class='odd'>
			<td colspan="2">
				<table cellspacing="0" cellpadding="1" width="100%">
					<td nowrap>Add Data Query:&nbsp;
						<?php 
        form_dropdown('snmp_query_id', db_fetch_assoc_prepared('SELECT
							snmp_query.id,
							snmp_query.name
							FROM snmp_query LEFT JOIN host_template_snmp_query
							ON (snmp_query.id = host_template_snmp_query.snmp_query_id AND host_template_snmp_query.host_template_id = ?)
							WHERE host_template_snmp_query.host_template_id is null
							ORDER BY snmp_query.name', array(get_request_var_request('id'))), 'name', 'id', '', '', '');
        ?>
					</td>
					<td align="right">
						&nbsp;<input type="submit" value="Add" name="add_dq_x" title="Add Data Query to Device Template">
					</td>
				</table>
			</td>
		</tr>

		<?php 
        html_end_box();
    }
    form_save_button('host_templates.php', 'return');
}
コード例 #28
0
ファイル: api_automation_tools.php プロジェクト: MrWnn/cacti
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";
        }
    }
}
コード例 #29
0
ファイル: graphs_new.php プロジェクト: MrWnn/cacti
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']);
}
コード例 #30
0
ファイル: graphs.php プロジェクト: MrWnn/cacti
function graph_diff()
{
    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('graph_template_id'));
    /* ==================================================== */
    $template_query = "SELECT\n\t\tgraph_templates_item.id,\n\t\tgraph_templates_item.text_format,\n\t\tgraph_templates_item.value,\n\t\tgraph_templates_item.hard_return,\n\t\tgraph_templates_item.consolidation_function_id,\n\t\tgraph_templates_item.graph_type_id,\n\t\tCONCAT_WS(' - ', data_template_data.name, data_template_rrd.data_source_name) AS task_item_id,\n\t\tcdef.name AS cdef_id,\n\t\tcolors.hex AS color_id\n\t\tFROM graph_templates_item\n\t\tLEFT JOIN data_template_rrd ON (graph_templates_item.task_item_id = data_template_rrd.id)\n\t\tLEFT JOIN data_local ON (data_template_rrd.local_data_id = data_local.id)\n\t\tLEFT JOIN data_template_data ON (data_local.id = data_template_data.local_data_id)\n\t\tLEFT JOIN cdef ON (cdef_id = cdef.id)\n\t\tLEFT JOIN colors ON (color_id = colors.id)";
    /* first, get information about the graph template as that's what we're going to model this
    	graph after */
    $graph_template_items = db_fetch_assoc_prepared("\n\t\t{$template_query}\n\t\tWHERE graph_templates_item.graph_template_id = ?\n\t\tAND graph_templates_item.local_graph_id = 0\n\t\tORDER BY graph_templates_item.sequence", array($_REQUEST['graph_template_id']));
    /* next, get information about the current graph so we can make the appropriate comparisons */
    $graph_items = db_fetch_assoc_prepared("\n\t\t{$template_query}\n\t\tWHERE graph_templates_item.local_graph_id = ?\n\t\tORDER BY graph_templates_item.sequence", array($_REQUEST['id']));
    $graph_template_inputs = db_fetch_assoc_prepared('SELECT
		graph_template_input.column_name,
		graph_template_input_defs.graph_template_item_id
		FROM (graph_template_input, graph_template_input_defs)
		WHERE graph_template_input.id = graph_template_input_defs.graph_template_input_id
		AND graph_template_input.graph_template_id = ?', array($_REQUEST['graph_template_id']));
    /* ok, we want to loop through the array with the GREATEST number of items so we don't have to worry
    	about tacking items on the end */
    if (sizeof($graph_template_items) > sizeof($graph_items)) {
        $items = $graph_template_items;
    } else {
        $items = $graph_items;
    }
    ?>
	<table class="tableConfirmation" width="100%" align="center">
		<tr>
			<td class="textArea">
				The template you have selected requires some changes to be made to the structure of
				your graph. Below is a preview of your graph along with changes that need to be completed
				as shown in the left-hand column.
			</td>
		</tr>
	</table>
	<br>
	<?php 
    html_start_box('<strong>Graph Preview</strong>', '100%', '', '3', 'center', '');
    $graph_item_actions = array('normal' => '', 'add' => '+', 'delete' => '-');
    $group_counter = 0;
    $i = 0;
    $mode = 'normal';
    $_graph_type_name = '';
    if (sizeof($items) > 0) {
        foreach ($items as $item) {
            reset($struct_graph_item);
            /* graph grouping display logic */
            $bold_this_row = false;
            $use_custom_row_color = false;
            $action_css = '';
            unset($graph_preview_item_values);
            if (sizeof($graph_template_items) > sizeof($graph_items) && $i >= sizeof($graph_items)) {
                $mode = 'add';
                $user_message = "When you click save, the items marked with a '<strong>+</strong>' will be added <strong>(Recommended)</strong>.";
            } elseif (sizeof($graph_template_items) < sizeof($graph_items) && $i >= sizeof($graph_template_items)) {
                $mode = 'delete';
                $user_message = "When you click save, the items marked with a '<strong>-</strong>' will be removed <strong>(Recommended)</strong>.";
            }
            /* here is the fun meshing part. first we check the graph template to see if there is an input
            		for each field of this row. if there is, we revert to the value stored in the graph, if not
            		we revert to the value stored in the template. got that? ;) */
            for ($j = 0; $j < count($graph_template_inputs); $j++) {
                if ($graph_template_inputs[$j]['graph_template_item_id'] == (isset($graph_template_items[$i]['id']) ? $graph_template_items[$i]['id'] : '')) {
                    /* if we find out that there is an "input" covering this field/item, use the
                    			value FROM the graph, not the template */
                    $graph_item_field_name = isset($graph_template_inputs[$j]['column_name']) ? $graph_template_inputs[$j]['column_name'] : '';
                    $graph_preview_item_values[$graph_item_field_name] = isset($graph_items[$i][$graph_item_field_name]) ? $graph_items[$i][$graph_item_field_name] : '';
                }
            }
            /* go back through each graph field and find out which ones haven't been covered by the
            		"inputs" above. for each one, use the value FROM the template */
            while (list($field_name, $field_array) = each($struct_graph_item)) {
                if ($mode == 'delete') {
                    $graph_preview_item_values[$field_name] = isset($graph_items[$i][$field_name]) ? $graph_items[$i][$field_name] : '';
                } elseif (!isset($graph_preview_item_values[$field_name])) {
                    $graph_preview_item_values[$field_name] = isset($graph_template_items[$i][$field_name]) ? $graph_template_items[$i][$field_name] : '';
                }
            }
            /* "prepare" array values */
            $consolidation_function_id = $graph_preview_item_values['consolidation_function_id'];
            $graph_type_id = $graph_preview_item_values['graph_type_id'];
            /* color logic */
            if ($graph_item_types[$graph_type_id] != 'GPRINT' && $graph_item_types[$graph_type_id] != $_graph_type_name) {
                $bold_this_row = true;
                $use_custom_row_color = true;
                $hard_return = '';
                if ($group_counter % 2 == 0) {
                    $alternate_color_1 = 'graphItemGr1Alt1';
                    $alternate_color_2 = 'graphItemGr1Alt2';
                    $custom_row_color = 'graphItemGr1Cust';
                } else {
                    $alternate_color_1 = 'graphItemGr2Alt1';
                    $alternate_color_2 = 'graphItemGr2Alt2';
                    $custom_row_color = 'graphItemGr2Cust';
                }
                $group_counter++;
            }
            $_graph_type_name = $graph_item_types[$graph_type_id];
            /* alternating row colors */
            if ($use_custom_row_color == false) {
                if ($i % 2 == 0) {
                    $action_column_color = $alternate_color_1;
                } else {
                    $action_column_color = $alternate_color_2;
                }
            } else {
                $action_column_color = $custom_row_color;
            }
            print "<tr class='#{$action_column_color}'>";
            $i++;
            /* make the left-hand column blue or red depending on if "add"/"remove" mode is set */
            if ($mode == 'add') {
                $action_column_color = 'graphItemAdd';
                $action_css = '';
            } elseif ($mode == 'delete') {
                $action_column_color = 'graphItemDel';
                $action_css = 'text-decoration: line-through;';
            }
            if ($bold_this_row == true) {
                $action_css .= ' font-weight:bold;';
            }
            /* draw the TD that shows the user whether we are going to: KEEP, ADD, or DROP the item */
            print "<td width='1%' class='#{$action_column_color}' style='font-weight: bold; color: white;'>" . $graph_item_actions[$mode] . '</td>';
            print "<td style='{$action_css}'><strong>Item # " . $i . "</strong></td>\n";
            if (empty($graph_preview_item_values['task_item_id'])) {
                $graph_preview_item_values['task_item_id'] = 'No Task';
            }
            switch (true) {
                case preg_match('/(AREA|STACK|GPRINT|LINE[123])/', $_graph_type_name):
                    $matrix_title = '(' . $graph_preview_item_values['task_item_id'] . '): ' . $graph_preview_item_values['text_format'];
                    break;
                case preg_match('/(HRULE|VRULE)/', $_graph_type_name):
                    $matrix_title = 'HRULE: ' . $graph_preview_item_values['value'];
                    break;
                case preg_match('/(COMMENT)/', $_graph_type_name):
                    $matrix_title = 'COMMENT: ' . $graph_preview_item_values['text_format'];
                    break;
            }
            /* use the cdef name (if in use) if all else fails */
            if ($matrix_title == '') {
                if ($graph_preview_item_values['cdef_id'] != '') {
                    $matrix_title .= 'CDEF: ' . $graph_preview_item_values['cdef_id'];
                }
            }
            if ($graph_preview_item_values['hard_return'] == 'on') {
                $hard_return = "<strong><font class='graphItemHR'>&lt;HR&gt;</font></strong>";
            }
            print "<td style='{$action_css}'>" . htmlspecialchars($matrix_title) . $hard_return . "</td>\n";
            print "<td style='{$action_css}'>" . $graph_item_types[$graph_preview_item_values['graph_type_id']] . "</td>\n";
            print "<td style='{$action_css}'>" . $consolidation_functions[$graph_preview_item_values['consolidation_function_id']] . "</td>\n";
            print '<td' . (!empty($graph_preview_item_values['color_id']) ? " bgcolor='#" . $graph_preview_item_values['color_id'] . "'" : '') . " width='1%'>&nbsp;</td>\n";
            print "<td style='{$action_css}'>" . $graph_preview_item_values['color_id'] . "</td>\n";
            print '</tr>';
        }
    } else {
        print "<tr class='tableRow'><td colspan='7'><em>No Items</em></td></tr>\n";
    }
    html_end_box();
    ?>
	<form action="graphs.php" method="post">
	<table class='tableConfirmation' width="100%" align="center">
		<tr>
			<td class="textArea">
				<input type='radio' name='type' value='1' checked>&nbsp;<?php 
    print $user_message;
    ?>
<br>
				<input type='radio' name='type' value='2'>&nbsp;When you click save, the graph items will remain untouched (could cause inconsistencies).
			</td>
		</tr>
	</table>
	<br>
	<input type="hidden" name="action" value="save">
	<input type="hidden" name="save_component_graph_diff" value="1">
	<input type="hidden" name="local_graph_id" value="<?php 
    print $_REQUEST['id'];
    ?>
">
	<input type="hidden" name="graph_template_id" value="<?php 
    print $_REQUEST['graph_template_id'];
    ?>
">
	<?php 
    form_save_button('graphs.php?action=graph_edit&id=' . $_REQUEST['id']);
}