示例#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');
        }
    }
}
function mactrack_view_get_site_records(&$sql_where, $row_limit, $apply_limits = TRUE)
{
    /* create SQL where clause */
    $device_type_info = db_fetch_row_prepared('SELECT * FROM mac_track_device_types WHERE device_type_id = ?', array(get_request_var('device_type_id')));
    $sql_where = '';
    /* form the 'where' clause for our main sql query */
    if (get_request_var('filter') != '') {
        if (get_request_var('detail') == 'false') {
            $sql_where = "WHERE (mac_track_sites.site_name LIKE '%" . get_request_var('filter') . "%')";
        } else {
            $sql_where = "WHERE (mac_track_device_types.vendor LIKE '%" . get_request_var('filter') . "%' OR " . "mac_track_device_types.description LIKE '%" . get_request_var('filter') . "%' OR " . "mac_track_sites.site_name LIKE '%" . get_request_var('filter') . "%')";
        }
    }
    if (sizeof($device_type_info)) {
        $sql_where = ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.device_type_id=' . $device_type_info['device_type_id'] . ')';
    }
    if (get_request_var('site_id') != '-1' && get_request_var('detail')) {
        $sql_where = ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.site_id=' . get_request_var('site_id') . ')';
    }
    if (get_request_var('detail') == 'false') {
        $query_string = "SELECT *\n\t\t\tFROM mac_track_sites\n\t\t\t{$sql_where}\n\t\t\tORDER BY " . get_request_var('sort_column') . ' ' . get_request_var('sort_direction');
        if ($apply_limits) {
            $query_string .= ' LIMIT ' . $row_limit * (get_request_var('page') - 1) . ',' . $row_limit;
        }
    } else {
        $query_string = "SELECT mac_track_sites.site_name, mac_track_sites.site_id,\n\t\t\tCount(mac_track_device_types.device_type_id) AS total_devices,\n\t\t\tmac_track_device_types.device_type_id,\n\t\t\tmac_track_device_types.device_type,\n\t\t\tmac_track_device_types.vendor,\n\t\t\tmac_track_device_types.description,\n\t\t\tSum(mac_track_devices.ips_total) AS sum_ips_total,\n\t\t\tSum(mac_track_devices.ports_total) AS sum_ports_total,\n\t\t\tSum(mac_track_devices.ports_active) AS sum_ports_active,\n\t\t\tSum(mac_track_devices.ports_trunk) AS sum_ports_trunk,\n\t\t\tSum(mac_track_devices.macs_active) AS sum_macs_active\n\t\t\tFROM (mac_track_device_types\n\t\t\tRIGHT JOIN mac_track_devices ON (mac_track_device_types.device_type_id = mac_track_devices.device_type_id))\n\t\t\tRIGHT JOIN mac_track_sites ON (mac_track_devices.site_id = mac_track_sites.site_id)\n\t\t\t{$sql_where}\n\t\t\tGROUP BY mac_track_sites.site_name, mac_track_device_types.vendor, mac_track_device_types.description\n\t\t\tHAVING (((Count(mac_track_device_types.device_type_id))>0))\n\t\t\tORDER BY " . get_request_var('sort_column') . ' ' . get_request_var('sort_direction');
        if ($apply_limits) {
            $query_string .= ' LIMIT ' . $row_limit * (get_request_var('page') - 1) . ',' . $row_limit;
        }
    }
    return db_fetch_assoc($query_string);
}
示例#3
0
function api_poller_cache_item_add($host_id, $host_field_override, $local_data_id, $rrd_step, $poller_action_id, $data_source_item_name, $num_rrd_items, $arg1 = '', $arg2 = '', $arg3 = '')
{
    static $hosts = array();
    if (!isset($hosts[$host_id])) {
        $host = db_fetch_row_prepared('SELECT
		host.id,
		host.hostname,
		host.snmp_community,
		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,
		host.disabled
		FROM host
		WHERE host.id = ?', array($host_id));
        $hosts[$host_id] = $host;
    } else {
        $host = $hosts[$host_id];
    }
    /* the $host_field_override array can be used to override certain host fields in the poller cache */
    if (isset($host)) {
        $host = array_merge($host, $host_field_override);
    }
    if (isset($host['id']) || isset($host_id)) {
        if (isset($host)) {
            if ($host['disabled'] == 'on') {
                return;
            }
        } else {
            if ($poller_action_id == 0) {
                return;
            }
            $host['id'] = 0;
            $host['snmp_community'] = '';
            $host['snmp_timeout'] = '';
            $host['snmp_username'] = '';
            $host['snmp_password'] = '';
            $host['snmp_auth_protocol'] = '';
            $host['snmp_priv_passphrase'] = '';
            $host['snmp_priv_protocol'] = '';
            $host['snmp_context'] = '';
            $host['snmp_version'] = '';
            $host['snmp_port'] = '';
            $host['hostname'] = 'None';
        }
        if ($poller_action_id == 0) {
            if ($host['snmp_version'] < 1 || $host['snmp_version'] > 3 || $host['snmp_community'] == '' && $host['snmp_version'] != 3) {
                return;
            }
        }
        $rrd_next_step = api_poller_get_rrd_next_step($rrd_step, $num_rrd_items);
        return "({$local_data_id}, " . '0, ' . $host['id'] . ", {$poller_action_id}," . db_qstr($host['hostname']) . ",\n\t\t\t" . db_qstr($host['snmp_community']) . ', ' . db_qstr($host['snmp_version']) . ', ' . db_qstr($host['snmp_timeout']) . ",\n\t\t\t" . db_qstr($host['snmp_username']) . ', ' . db_qstr($host['snmp_password']) . ', ' . db_qstr($host['snmp_auth_protocol']) . ",\n\t\t\t" . db_qstr($host['snmp_priv_passphrase']) . ', ' . db_qstr($host['snmp_priv_protocol']) . ', ' . db_qstr($host['snmp_context']) . ",\n\t\t\t" . db_qstr($host['snmp_port']) . ', ' . db_qstr($data_source_item_name) . ', ' . db_qstr(clean_up_path(get_data_source_path($local_data_id, true))) . ",\n\t\t\t" . db_qstr($num_rrd_items) . ', ' . db_qstr($rrd_step) . ', ' . db_qstr($rrd_next_step) . ', ' . db_qstr($arg1) . ', ' . db_qstr($arg2) . ', ' . db_qstr($arg3) . ", '1')";
    }
}
function mactrack_view_get_device_records(&$sql_where, $row_limit, $apply_limits = TRUE)
{
    $device_type_info = db_fetch_row_prepared('SELECT * FROM mac_track_device_types WHERE device_type_id = ?', array(get_request_var('device_type_id')));
    /* if the device type is not the same as the type_id, then reset it */
    if (sizeof($device_type_info) && get_request_var('type_id') != -1) {
        if ($device_type_info['device_type'] != get_request_var('type_id')) {
            $device_type_info = array();
        }
    } else {
        if (get_request_var('device_type_id') == 0) {
            $device_type_info = array('device_type_id' => 0, 'description' => __('Unknown Device Type'));
        }
    }
    /* form the 'where' clause for our main sql query */
    if (get_request_var('filter') != '') {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . "(mac_track_devices.hostname LIKE '%" . get_request_var('filter') . "%' OR " . "mac_track_devices.notes LIKE '%" . get_request_var('filter') . "%' OR " . "mac_track_devices.device_name LIKE '%" . get_request_var('filter') . "%' OR " . "mac_track_sites.site_name LIKE '%" . get_request_var('filter') . "%')";
    }
    if (sizeof($device_type_info)) {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.device_type_id=' . $device_type_info['device_type_id'] . ')';
    }
    if (get_request_var('status') == '-1') {
        /* Show all items */
    } elseif (get_request_var('status') == '-2') {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.disabled="on")';
    } elseif (get_request_var('status') == '5') {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.host_id=0)';
    } else {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.snmp_status=' . get_request_var('status') . ') AND (mac_track_devices.disabled = "")';
    }
    /* scan types matching */
    if (get_request_var('type_id') == '-1') {
        /* Show all items */
    } else {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.scan_type=' . get_request_var('type_id') . ')';
    }
    /* device types matching */
    if (get_request_var('device_type_id') == '-1') {
        /* Show all items */
    } elseif (get_request_var('device_type_id') == '-2') {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_device_types.description="")';
    } else {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.device_type_id=' . get_request_var('device_type_id') . ')';
    }
    if (get_request_var('site_id') == '-1') {
        /* Show all items */
    } elseif (get_request_var('site_id') == '-2') {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_sites.site_id IS NULL)';
    } elseif (!isempty_request_var('site_id')) {
        $sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . '(mac_track_devices.site_id=' . get_request_var('site_id') . ')';
    }
    $sql_query = "SELECT\n\t\tmac_track_devices.*,\n\t\tmac_track_device_types.description AS device_type,\n\t\tmac_track_sites.site_name\n\t\tFROM mac_track_sites\n\t\tRIGHT JOIN mac_track_devices ON (mac_track_devices.site_id=mac_track_sites.site_id)\n\t\tLEFT JOIN mac_track_device_types ON (mac_track_device_types.device_type_id=mac_track_devices.device_type_id)\n\t\t{$sql_where}\n\t\tORDER BY " . get_request_var('sort_column') . ' ' . get_request_var('sort_direction');
    if ($apply_limits) {
        $sql_query .= ' LIMIT ' . $row_limit * (get_request_var('page') - 1) . ',' . $row_limit;
    }
    return db_fetch_assoc($sql_query);
}
示例#5
0
文件: cdef.php 项目: MrWnn/cacti
function get_cdef_item_name($cdef_item_id)
{
    global $cdef_functions, $cdef_operators;
    $cdef_item = db_fetch_row_prepared('SELECT type, value FROM cdef_items WHERE id = ?', array($cdef_item_id));
    $current_cdef_value = $cdef_item['value'];
    switch ($cdef_item['type']) {
        case '1':
            return $cdef_functions[$current_cdef_value];
            break;
        case '2':
            return $cdef_operators[$current_cdef_value];
            break;
        case '4':
            return $current_cdef_value;
            break;
        case '5':
            return db_fetch_cell_prepared('SELECT name FROM cdef WHERE id = ?', array($current_cdef_value));
            break;
        case '6':
            return $current_cdef_value;
            break;
    }
}
示例#6
0
function settings()
{
    global $tabs_graphs, $settings_graphs, $current_user, $graph_views, $current_user;
    /* you cannot have per-user graph settings if cacti's user management is not turned on */
    if (read_config_option('auth_method') == 0) {
        raise_message(6);
        display_output_messages();
        return;
    }
    if ($_REQUEST['action'] == 'edit') {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $timespan_sel_pos = strpos($_SERVER['HTTP_REFERER'], '&predefined_timespan');
            if ($timespan_sel_pos) {
                $_SERVER['HTTP_REFERER'] = substr($_SERVER['HTTP_REFERER'], 0, $timespan_sel_pos);
            }
        }
        $_SESSION['profile_referer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'graph_view.php';
    }
    print "<form method='post' action='auth_profile.php'>\n";
    html_start_box('<strong>User Settings</strong>', '100%', '', '3', 'center', '');
    $current_user = db_fetch_row_prepared('SELECT * FROM user_auth WHERE id = ?', array($_SESSION['sess_user_id']));
    if (!sizeof($current_user)) {
        return;
    }
    /* file: user_admin.php, action: user_edit (host) */
    $fields_user = array('username' => array('method' => 'value', 'friendly_name' => 'User Name', 'description' => 'The login name for this user.', 'value' => '|arg1:username|', 'max_length' => '40', 'size' => '40'), 'full_name' => array('method' => 'textbox', 'friendly_name' => 'Full Name', 'description' => 'A more descriptive name for this user, that can include spaces or special characters.', 'value' => '|arg1:full_name|', 'max_length' => '120', 'size' => '60'), 'email_address' => array('method' => 'textbox', 'friendly_name' => 'E-Mail Address', 'description' => 'An E-Mail Address you be reached at.', 'value' => '|arg1:email_address|', 'max_length' => '60', 'size' => '60'));
    draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => inject_form_variables($fields_user, isset($current_user) ? $current_user : array())));
    html_end_box();
    if (is_view_allowed('graph_settings') == true) {
        if (read_config_option('auth_method') != 0) {
            $settings_graphs['tree']['default_tree_id']['sql'] = get_graph_tree_array(true);
        }
        html_start_box('<strong>Graph Settings</strong>', '100%', '', '3', 'center', '');
        while (list($tab_short_name, $tab_fields) = each($settings_graphs)) {
            $collapsible = true;
            print "<tr class='spacer tableHeader" . ($collapsible ? ' collapsible' : '') . "' id='row_{$tab_short_name}'><td colspan='2' style='cursor:pointer;' class='tableSubHeaderColumn'>" . $tabs_graphs[$tab_short_name] . ($collapsible ? "<div style='float:right;padding-right:4px;'><i class='fa fa-angle-double-up'></i></div>" : "") . "</td></tr>\n";
            $form_array = array();
            while (list($field_name, $field_array) = each($tab_fields)) {
                $form_array += array($field_name => $tab_fields[$field_name]);
                if (isset($field_array['items']) && is_array($field_array['items'])) {
                    while (list($sub_field_name, $sub_field_array) = each($field_array['items'])) {
                        if (graph_config_value_exists($sub_field_name, $_SESSION['sess_user_id'])) {
                            $form_array[$field_name]['items'][$sub_field_name]['form_id'] = 1;
                        }
                        $form_array[$field_name]['items'][$sub_field_name]['value'] = db_fetch_cell_prepared('SELECT value FROM settings_graphs WHERE name = ? AND user_id = ?', array($sub_field_name, $_SESSION['sess_user_id']));
                    }
                } else {
                    if (graph_config_value_exists($field_name, $_SESSION['sess_user_id'])) {
                        $form_array[$field_name]['form_id'] = 1;
                    }
                    $form_array[$field_name]['value'] = db_fetch_cell_prepared('SELECT value FROM settings_graphs WHERE name = ? AND user_id = ?', array($field_name, $_SESSION['sess_user_id']));
                }
            }
            draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array));
        }
        html_end_box();
    }
    ?>
	<script type="text/javascript">
	<!--
	var themeFonts=<?php 
    print read_config_option('font_method');
    ?>
;

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

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

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

	$(function() {
		graphSettings();

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

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

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

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

	-->
	</script>
	<?php 
    form_hidden_box('save_component_graph_config', '1', '');
    form_save_buttons(array(array('id' => 'return', 'value' => 'Return'), array('id' => 'save', 'value' => 'Save')));
}
示例#7
0
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
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');
}
示例#9
0
function item_edit()
{
    global $struct_graph_item, $graph_item_types, $consolidation_functions;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('host_id'));
    input_validate_input_number(get_request_var_request('graph_template_id'));
    input_validate_input_number(get_request_var_request('local_graph_id'));
    input_validate_input_number(get_request_var_request('host_id'));
    input_validate_input_number(get_request_var_request('data_template_id'));
    /* ==================================================== */
    /* remember these search fields in session vars so we don't have to keep passing them around */
    load_current_session_value('local_graph_id', 'sess_local_graph_id', '');
    load_current_session_value('host_id', 'sess_ds_host_id', '-1');
    load_current_session_value('data_template_id', 'sess_data_template_id', '-1');
    $id = !empty($_REQUEST['id']) ? '&id=' . $_REQUEST['id'] : '';
    $host = db_fetch_row_prepared('SELECT hostname FROM host WHERE id = ?', array(get_request_var_request('host_id')));
    html_start_box('<strong>Data Sources</strong> [host: ' . (empty($host['hostname']) ? 'No Device' : $host['hostname']) . ']', '100%', '', '3', 'center', '');
    ?>
	<tr class='even noprint'>
		<form name="form_graph_items" action="graphs_items.php">
		<td>
			<table cellpadding="2" cellspacing="0">
				<tr>
					<td width="50">
						Device
					</td>
					<td>
						<select name="cbo_host_id" onChange="window.location=document.form_graph_items.cbo_host_id.options[document.form_graph_items.cbo_host_id.selectedIndex].value">
							<option value="graphs_items.php?action=item_edit<?php 
    print $id;
    ?>
&local_graph_id=<?php 
    print get_request_var_request('local_graph_id');
    ?>
&host_id=-1&data_template_id=<?php 
    print get_request_var_request('data_template_id');
    ?>
"<?php 
    if (get_request_var_request('host_id') == '-1') {
        ?>
 selected<?php 
    }
    ?>
>Any</option>
							<option value="graphs_items.php?action=item_edit<?php 
    print $id;
    ?>
&local_graph_id=<?php 
    print get_request_var_request('local_graph_id');
    ?>
&host_id=0&data_template_id=<?php 
    print get_request_var_request('data_template_id');
    ?>
"<?php 
    if (get_request_var_request('host_id') == '0') {
        ?>
 selected<?php 
    }
    ?>
>None</option>
							<?php 
    $hosts = db_fetch_assoc("SELECT id, CONCAT_WS('',description,' (',hostname,')') AS name FROM host ORDER BY description, hostname");
    if (sizeof($hosts) > 0) {
        foreach ($hosts as $host) {
            print "<option value='graphs_items.php?action=item_edit" . $id . '&local_graph_id=' . get_request_var_request('local_graph_id') . '&host_id=' . $host['id'] . '&data_template_id=' . get_request_var_request('data_template_id') . "'";
            if (get_request_var_request('host_id') == $host['id']) {
                print ' selected';
            }
            print '>' . $host['name'] . "</option>\n";
        }
    }
    ?>

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

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

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

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

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

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

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

			break;
		}

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

	</script>
	<?php 
}
function mactrack_log_action($message)
{
    $user = db_fetch_row_prepared('SELECT username, full_name FROM user_auth WHERE id = ?', array($_SESSION['sess_user_id']));
    cacti_log('MACTRACK: ' . $message . ", by '" . $user['full_name'] . '(' . $user['username'] . ")'", false, 'SYSTEM');
}
示例#11
0
function add_host_based_graphs()
{
    global $config, $device_hashes, $device_query_hashes, $device_health_hashes;
    debug('Adding Host Based Graphs');
    /* check for host level graphs next data queries */
    $host_cpu_dq = read_config_option('mikrotik_dq_host_cpu');
    $host_users_dq = mikrotik_data_query_by_hash('ce63249e6cc3d52bc69659a3f32194fe');
    $hosts = db_fetch_assoc("SELECT host_id, host.description, host.hostname \n\t\tFROM plugin_mikrotik_system\n\t\tINNER JOIN host\n\t\tON host.id=plugin_mikrotik_system.host_id\n\t\tWHERE host_status IN(0,3) AND host.disabled=''");
    if (sizeof($hosts)) {
        foreach ($hosts as $h) {
            debug('Processing Host: ' . $h['description'] . ' [' . $h['hostname'] . ']');
            foreach ($device_hashes as $hash) {
                $template = mikrotik_template_by_hash($hash);
                if (!empty($template)) {
                    debug('Processing ' . db_fetch_cell_prepared('SELECT name FROM graph_templates WHERE hash = ?', array($hash)));
                    mikrotik_gt_graph($h['host_id'], $template);
                }
            }
            foreach ($device_query_hashes as $hash) {
                $query = mikrotik_data_query_by_hash($hash);
                if (!empty($query)) {
                    debug('Processing ' . db_fetch_cell_prepared('SELECT name FROM snmp_query WHERE hash = ?', array($hash)));
                    if ($hash == '7dd90372956af1dc8ec7b859a678f227') {
                        $exclusion = read_config_option('mikrotik_user_exclusion');
                        add_host_dq_graphs($h['host_id'], $query, 'userName', $exclusion, false);
                    } else {
                        add_host_dq_graphs($h['host_id'], $query);
                    }
                }
            }
            $health = db_fetch_row_prepared('SELECT * FROM plugin_mikrotik_system_health WHERE host_id = ?', array($h['host_id']));
            debug('Processing Health');
            if (sizeof($health)) {
                foreach ($device_health_hashes as $column => $hash) {
                    if (!empty($health[$column]) && $health[$column] != 'NULL') {
                        $template = mikrotik_template_by_hash($hash);
                        if (!empty($template)) {
                            debug('Processing ' . db_fetch_cell_prepared('SELECT name FROM graph_templates WHERE hash = ?', array($hash)));
                            mikrotik_gt_graph($h['host_id'], $template);
                        }
                    }
                }
            }
        }
    } else {
        debug('No Hosts Found');
    }
}
示例#12
0
文件: variables.php 项目: MrWnn/cacti
function substitute_host_data($string, $l_escape_string, $r_escape_string, $host_id)
{
    if (!empty($host_id)) {
        if (!isset($_SESSION['sess_host_cache_array'][$host_id])) {
            $host = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id));
            $_SESSION['sess_host_cache_array'][$host_id] = $host;
        }
        $string = str_replace($l_escape_string . 'host_management_ip' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['hostname'], $string);
        /* for compatability */
        $string = str_replace($l_escape_string . 'host_hostname' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['hostname'], $string);
        $string = str_replace($l_escape_string . 'host_description' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['description'], $string);
        $string = str_replace($l_escape_string . 'host_notes' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['notes'], $string);
        $string = str_replace($l_escape_string . 'host_polling_time' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['polling_time'], $string);
        $string = str_replace($l_escape_string . 'host_avg_time' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['avg_time'], $string);
        $string = str_replace($l_escape_string . 'host_cur_time' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['cur_time'], $string);
        $string = str_replace($l_escape_string . 'host_availability' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['availability'], $string);
        /* snmp connectivity information */
        $string = str_replace($l_escape_string . 'host_snmp_community' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_community'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_version' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_version'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_username' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_username'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_password' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_password'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_auth_protocol' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_auth_protocol'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_priv_passphrase' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_priv_passphrase'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_priv_protocol' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_priv_protocol'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_context' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_context'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_port' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_port'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_timeout' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_timeout'], $string);
        /* snmp system information */
        $string = str_replace($l_escape_string . 'host_snmp_sysDescr' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysDescr'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysObjectID' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysObjectID'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysContact' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysContact'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysLocation' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysLocation'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysName' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysName'], $string);
        $string = str_replace($l_escape_string . 'host_snmp_sysUpTimeInstance' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['snmp_sysUpTimeInstance'], $string);
        $string = str_replace($l_escape_string . 'host_ping_retries' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['ping_retries'], $string);
        $string = str_replace($l_escape_string . 'host_max_oids' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['max_oids'], $string);
        $string = str_replace($l_escape_string . 'host_id' . $r_escape_string, $_SESSION['sess_host_cache_array'][$host_id]['id'], $string);
        $temp = api_plugin_hook_function('substitute_host_data', array('string' => $string, 'l_escape_string' => $l_escape_string, 'r_escape_string' => $r_escape_string, 'host_id' => $host_id));
        $string = $temp['string'];
    }
    return $string;
}
示例#13
0
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');
}
示例#14
0
文件: color.php 项目: MrWnn/cacti
function color_edit()
{
    global $fields_color_edit;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    /* ==================================================== */
    if (!empty($_REQUEST['id'])) {
        $color = db_fetch_row_prepared('SELECT * FROM colors WHERE id = ?', array(get_request_var_request('id')));
        $header_label = '[edit: ' . $color['hex'] . ']';
    } else {
        $header_label = '[new]';
    }
    html_start_box("<strong>Colors</strong> {$header_label}", '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array(), 'fields' => inject_form_variables($fields_color_edit, isset($color) ? $color : array())));
    html_end_box();
    form_save_button('color.php');
}
示例#15
0
文件: functions.php 项目: MrWnn/cacti
function update_system_mibs($host_id)
{
    $system_mibs = array('snmp_sysDescr' => '.1.3.6.1.2.1.1.1.0', 'snmp_sysObjectID' => '.1.3.6.1.2.1.1.2.0', 'snmp_sysUpTimeInstance' => '.1.3.6.1.2.1.1.3.0', 'snmp_sysContact' => '.1.3.6.1.2.1.1.4.0', 'snmp_sysName' => '.1.3.6.1.2.1.1.5.0', 'snmp_sysLocation' => '.1.3.6.1.2.1.1.6.0');
    $h = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id));
    if (sizeof($h)) {
        foreach ($system_mibs as $name => $oid) {
            $value = cacti_snmp_get($h['hostname'], $h['snmp_community'], $oid, $h['snmp_version'], $h['snmp_username'], $h['snmp_password'], $h['snmp_auth_protocol'], $h['snmp_priv_passphrase'], $h['snmp_priv_protocol'], $h['snmp_context'], $h['snmp_port'], $h['snmp_timeout'], read_config_option('snmp_retries'), SNMP_CMDPHP);
            if (!empty($value)) {
                db_execute_prepared("UPDATE host SET {$name} = ? WHERE id = ?", array($value, $host_id));
            }
        }
    }
}
示例#16
0
function api_reapply_suggested_data_source_title($local_data_id)
{
    global $config;
    $data_template_data_id = db_fetch_cell_prepared('SELECT id FROM data_template_data WHERE local_data_id = ?', array($local_data_id));
    if (empty($data_template_data_id)) {
        return;
    }
    /* require query type data sources only (snmp_query_id > 0) */
    $data_local = db_fetch_row_prepared('SELECT id, host_id, data_template_id, snmp_query_id, snmp_index FROM data_local WHERE snmp_query_id > 0 AND id = ?', array($local_data_id));
    /* if this is not a data query graph, simply return */
    if (!isset($data_local['host_id'])) {
        return;
    }
    $snmp_query_graph_id = db_fetch_cell_prepared("SELECT \n\t\tdata_input_data.value FROM data_input_data \n\t\tJOIN data_input_fields ON (data_input_data.data_input_field_id = data_input_fields.id) \n\t\tJOIN data_template_data ON (data_template_data.id = data_input_data.data_template_data_id) \n\t\tWHERE data_input_fields.type_code = 'output_type' \n\t\tAND data_template_data.local_data_id = ?", array($data_local['id']));
    /* no snmp query graph id found */
    if ($snmp_query_graph_id == 0) {
        return;
    }
    $suggested_values = db_fetch_assoc_prepared("SELECT \n\t\ttext, \n\t\tfield_name \n\t\tFROM snmp_query_graph_rrd_sv \n\t\tWHERE snmp_query_graph_id = ?\n\t\tAND data_template_id = ?\n\t\tAND field_name = 'name'\n\t\tORDER BY sequence", array($snmp_query_graph_id, $data_local['data_template_id']));
    $suggested_values_data = array();
    if (sizeof($suggested_values) > 0) {
        foreach ($suggested_values as $suggested_value) {
            if (!isset($suggested_values_data[$suggested_value['field_name']])) {
                $subs_string = substitute_snmp_query_data($suggested_value['text'], $data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index'], read_config_option('max_data_query_field_length'));
                /* if there are no '|query' characters, all of the substitutions were successful */
                if (!substr_count($subs_string, '|query')) {
                    db_execute_prepared('UPDATE data_template_data SET ' . $suggested_value['field_name'] . ' = ? WHERE local_data_id = ?', array($suggested_value['text'], $local_data_id));
                    /* once we find a working value for that very field, stop */
                    $suggested_values_data[$suggested_value['field_name']] = true;
                }
            }
        }
    }
}
示例#17
0
function thold_edit()
{
    global $config;
    if (isset_request_var('id')) {
        $thold_data = db_fetch_row_prepared('SELECT * 
			FROM thold_data 
			WHERE id = ?', array(get_request_var('id')));
    } elseif (isset_request_var('local_data_id') && isset_request_var('local_graph_id') && isset_request_var('host_id') && isset_request_var('data_template_id') && isset_request_var('data_template_rrd_id')) {
        $thold_data['id'] = '0';
        $thold_data['local_data_id'] = get_filter_request_var('local_data_id');
        $thold_data['local_graph_id'] = get_filter_request_var('local_graph_id');
        $thold_data['data_template_id'] = get_filter_request_var('data_template_id');
        $thold_data['host_id'] = get_filter_request_var('host_id');
        $thold_data['data_template_rrd_id'] = get_filter_request_var('data_template_rrd_id');
        $thold_data['thold_template_id'] = get_filter_request_var('thold_template_id');
    } else {
        exit;
    }
    $desc = db_fetch_cell_prepared('SELECT name_cache 
		FROM data_template_data 
		WHERE local_data_id = ? 
		LIMIT 1', array($thold_data['local_data_id']));
    $rrdsql = array_rekey(db_fetch_assoc_prepared("SELECT id \n\t\tFROM data_template_rrd \n\t\tWHERE local_data_id = ? ORDER BY id", array($thold_data['local_data_id'])), 'id', 'id');
    $grapharr = db_fetch_assoc('SELECT DISTINCT local_graph_id 
		FROM graph_templates_item 
		WHERE task_item_id IN (' . implode(', ', $rrdsql) . ') AND graph_template_id>0');
    if (empty($thold_data['local_graph_id'])) {
        $thold_data['local_graph_id'] = db_fetch_cell_prepared('SELECT gl.id
			FROM graph_local AS gl
			INNER JOIN graph_templates_item AS gti
			ON gl.id=gti.local_graph_id
			INNER JOIN data_template_rrd AS dtr
			ON gti.task_item_id=dtr.id
			WHERE dtr.local_data_id = ?
			LIMIT 1', array($thold_data['local_data_id']));
    }
    if (empty($thold_data['data_template_rrd_id'])) {
        $thold_data['data_template_rrd_id'] = db_fetch_cell_prepared('SELECT id
			FROM data_template_rrd AS dtr
			WHERE local_data_id = ? 
			LIMIT 1', array($thold_data['local_data_id']));
    }
    $dt_sql = 'SELECT DISTINCT dtr.local_data_id
		FROM data_template_rrd AS dtr
		LEFT JOIN graph_templates_item AS gti
		ON gti.task_item_id=dtr.id
		LEFT JOIN graph_local AS gl
		ON gl.id=gti.local_graph_id
		WHERE gl.id=' . $thold_data['local_graph_id'];
    $template_data_rrds = db_fetch_assoc("SELECT td.id AS thold_id, dtr.id, dtr.data_source_name, dtr.local_data_id \n\t\tFROM data_template_rrd AS dtr\n\t\tLEFT JOIN thold_data AS td\n\t\tON dtr.id=td.data_template_rrd_id\n\t\tWHERE dtr.local_data_id IN ({$dt_sql}) \n\t\tORDER BY dtr.id");
    form_start('thold.php', 'thold');
    html_start_box(__('Graph Data'), '100%', '', '3', 'center', '');
    ?>
	<tr>
		<td class='textArea'>
			<?php 
    if (isset($banner)) {
        echo $banner . '<br><br>';
    }
    ?>
			<?php 
    print __('Data Source Description:');
    ?>
 <br><?php 
    echo $desc;
    ?>
<br><br>
			<?php 
    print __('Associated Graph (graphs that use this RRD):');
    ?>
 <br>
			<select name='element'>
				<?php 
    foreach ($grapharr as $g) {
        $graph_desc = db_fetch_row_prepared('SELECT local_graph_id, title, title_cache
						FROM graph_templates_graph
						WHERE local_graph_id = ?', array($g['local_graph_id']));
        echo "<option value='" . $graph_desc['local_graph_id'] . "'";
        if ($graph_desc['local_graph_id'] == $thold_data['local_graph_id']) {
            echo ' selected';
        }
        echo '>' . $graph_desc['local_graph_id'] . ' - ' . $graph_desc['title_cache'] . " </option>\n";
    }
    ?>
			</select>
			<br>
			<br>
		</td>
		<td class='textArea'>
			<img id='graphimage' src='<?php 
    echo htmlspecialchars($config['url_path'] . 'graph_image.php?local_graph_id=' . $thold_data['local_graph_id'] . '&rra_id=0&graph_start=-32400&graph_height=140&graph_width=500');
    ?>
'>
		</td>
	</tr>
	<?php 
    html_end_box();
    $template_rrd = db_fetch_row_prepared('SELECT * 
		FROM data_template_rrd 
		WHERE id = ?', array($thold_data['data_template_rrd_id']));
    //-----------------------------
    // Tabs (if more than one item)
    //-----------------------------
    $i = 0;
    $ds = 0;
    if (isset($template_data_rrds)) {
        if (sizeof($template_data_rrds)) {
            /* draw the data source tabs on the top of the page */
            print "<br><div class='tabs'><nav><ul>\n";
            foreach ($template_data_rrds as $template_data_rrd) {
                if ($template_data_rrd['id'] == $thold_data['data_template_rrd_id']) {
                    $ds = $template_data_rrd['data_source_name'];
                }
                if (!empty($template_data_rrd['thold_id'])) {
                    $td = db_fetch_row('SELECT * 
						FROM thold_data 
						WHERE id=' . $template_data_rrd['thold_id']);
                } else {
                    $td = array();
                }
                $cur_setting = '';
                if (!sizeof($td)) {
                    $cur_setting .= "<span style='padding-right:4px;'>" . __('N/A') . "</span>";
                } else {
                    $cur_setting = '<span style="padding-right:4px;">' . __('Last:') . '</span>' . ($td['lastread'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceDown'>" . thold_format_number($td['lastread'], 4) . "</span>");
                    if ($td['thold_type'] != 1) {
                        if ($td['thold_warning_fail_trigger'] != 0) {
                            if ($td['thold_warning_hi'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('WHi:') . '</span>' . ($td['thold_warning_hi'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_warning_hi'], 2) . '</span>');
                            }
                            if ($td['thold_warning_low'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('WLo:') . '</span>' . ($td['thold_warning_low'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_warning_low'], 2) . '</span>');
                            }
                        }
                        if ($td['thold_fail_trigger'] != 0) {
                            if ($td['thold_hi'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('AHi:') . '</span>' . ($td['thold_hi'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_hi'], 2) . '</span>');
                            }
                            if ($td['thold_low'] != '') {
                                $cur_setting .= '<span style="padding:4px">' . __('ALo:') . '</span>' . ($td['thold_low'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_low'], 2) . '</span>');
                            }
                        }
                    } else {
                        $cur_setting .= '<span style="padding:4px">' . __('AHi:') . '</span>' . ($td['thold_hi'] == '' ? "<span>" . __('N/A') . "</span>" : "<span clas='deviceRecovering'>" . thold_format_number($td['thold_hi'], 2) . '</span>');
                        $cur_setting .= '<span style="padding:4px">' . __('ALo:') . '</span>' . ($td['thold_low'] == '' ? "<span>" . __('N/A') . "</span>" : "<span class='deviceRecovering'>" . thold_format_number($td['thold_low'], 2) . '</span>');
                        $cur_setting .= '<span>' . __('BL: (Up %s %/Down %s %)', $td['bl_pct_up'], $td['bl_pct_down']) . '</span>';
                    }
                }
                if ($template_data_rrd['id'] == $thold_data['data_template_rrd_id']) {
                    $selected = 'selected';
                } else {
                    $selected = '';
                }
                if (!empty($template_data_rrd['thold_id'])) {
                    echo "<li class='textEditTitle'><a class='hyperLink {$selected}' href='" . htmlspecialchars('thold.php?action=edit&id=' . $template_data_rrd['thold_id']) . "'>" . $template_data_rrd['data_source_name'] . '<br>' . $cur_setting . '</a></li>';
                } else {
                    echo "<li class='textEditTitle'><a class='hyperLink {$selected}' href='" . htmlspecialchars('thold.php?action=edit&local_data_id=' . $template_data_rrd['local_data_id'] . '&data_template_rrd_id=' . $template_data_rrd['id']) . '&local_graph_id=' . $thold_data['local_graph_id'] . '&host_id=' . $thold_data['host_id'] . '&data_template_id=' . $thold_data['data_template_id'] . '&thold_template_id=0' . "'>" . $template_data_rrd['data_source_name'] . '<br>' . $cur_setting . '</a></li>';
                }
            }
            echo "<li class='textEditTitle'><a class='hyperLink' href='" . htmlspecialchars('thold.php?action=add' . '&local_graph_id=' . $thold_data['local_graph_id'] . '&host_id=' . $thold_data['host_id']) . "'>new thold<br>n/a</a></li>";
            print "</ul></nav></div>\n";
        } elseif (sizeof($template_data_rrds) == 1) {
            set_request_var('data_template_rrd_id', $template_data_rrds[0]['id']);
        }
    }
    //----------------------
    // Data Source Item Form
    //----------------------
    $thold_data_cdef = isset($thold_data['cdef']) ? $thold_data['cdef'] : 0;
    if (isset($thold_data['template'])) {
        $thold_data['template_name'] = db_fetch_cell_prepared('SELECT name 
			FROM thold_template 
			WHERE id = ?', array($thold_data['thold_template_id']));
    }
    $header_text = __('Data Source Item [%s] ' . ' - Current value: [%s]', isset($template_rrd) ? $template_rrd['data_source_name'] : '', get_current_value($thold_data['local_data_id'], $ds, $thold_data_cdef));
    html_start_box($header_text, '100%', '', '3', 'center', '');
    $send_notification_array = array();
    $users = db_fetch_assoc("SELECT plugin_thold_contacts.id, plugin_thold_contacts.data,\n\t\tplugin_thold_contacts.type, user_auth.full_name\n\t\tFROM plugin_thold_contacts, user_auth\n\t\tWHERE user_auth.id=plugin_thold_contacts.user_id\n\t\tAND plugin_thold_contacts.data!=''\n\t\tORDER BY user_auth.full_name ASC, plugin_thold_contacts.type ASC");
    if (!empty($users)) {
        foreach ($users as $user) {
            $send_notification_array[$user['id']] = $user['full_name'] . ' - ' . ucfirst($user['type']);
        }
    }
    if (isset($thold_data['id'])) {
        $sql = 'SELECT contact_id as id FROM plugin_thold_threshold_contact WHERE thold_id=' . $thold_data['id'];
        $step = db_fetch_cell('SELECT rrd_step FROM data_template_data WHERE local_data_id = ' . $thold_data['local_data_id'], FALSE);
    } else {
        $sql = 'SELECT contact_id as id FROM plugin_thold_threshold_contact WHERE thold_id=0';
        $step = db_fetch_cell('SELECT rrd_step FROM data_template_data WHERE local_data_id = ' . $thold_data['local_data_id'], FALSE);
    }
    include $config['base_path'] . '/plugins/thold/includes/arrays.php';
    $data_fields = array();
    $reference_types = get_reference_types($thold_data['local_data_id'], $step, $timearray);
    $temp = db_fetch_assoc('SELECT id, local_data_template_rrd_id, data_source_name, data_input_field_id
		FROM data_template_rrd
		WHERE local_data_id=' . $thold_data['local_data_id']);
    foreach ($temp as $d) {
        if ($d['data_input_field_id'] != 0) {
            $name = db_fetch_cell('SELECT name FROM data_input_fields WHERE id=' . $d['data_input_field_id']);
        } else {
            $name = $d['data_source_name'];
        }
        if ($d['id'] != $thold_data['data_template_rrd_id']) {
            $data_fields[$d['data_source_name']] = $name;
        }
    }
    $replacements = db_fetch_assoc_prepared('SELECT DISTINCT field_name
		FROM data_local AS dl
		INNER JOIN host_snmp_cache AS hsc
		ON dl.snmp_query_id=hsc.snmp_query_id
		AND dl.host_id=hsc.host_id
		WHERE dl.id = ?', array($thold_data['data_template_id']));
    $nr = array();
    if (sizeof($replacements)) {
        foreach ($replacements as $r) {
            $nr[] = "<span class='deviceUp'>|query_" . $r['field_name'] . "|</span>";
        }
    }
    $vhf = explode('|', trim(VALID_HOST_FIELDS, '()'));
    if (sizeof($vhf)) {
        foreach ($vhf as $r) {
            $nr[] = "<span class='deviceUp'>|" . $r . "|</span>";
        }
    }
    $replacements = "<br>" . __('Replacement Fields: %s', implode(", ", $nr));
    $dss = db_fetch_assoc_prepared('SELECT data_source_name FROM data_template_rrd WHERE local_data_id = ?', array($thold_data['local_data_id']));
    if (sizeof($dss)) {
        foreach ($dss as $ds) {
            $dsname[] = "<span class='deviceUp'>|ds:" . $ds["data_source_name"] . "|</span>";
        }
    }
    $datasources = "<br>" . __('Data Sources: %s', implode(", ", $dsname));
    $form_array = array('template_header' => array('friendly_name' => __('Template Settings'), 'method' => 'spacer'), 'template_enabled' => array('friendly_name' => __('Template Propagation Enabled'), 'method' => 'checkbox', 'default' => '', 'description' => __('Whether or not these settings will be propagates from the threshold template.'), 'value' => !empty($thold_data['template_enabled']) ? $thold_data['template_enabled'] : ''), 'template_name' => array('friendly_name' => __('Template Name'), 'method' => 'custom', 'default' => '', 'description' => __('Name of the Threshold Template the threshold was created from.'), 'value' => isset($thold_data['template_name']) ? $thold_data['template_name'] : 'N/A'), 'general_header' => array('friendly_name' => __('General Settings'), 'method' => 'spacer'), 'name' => array('friendly_name' => __('Threshold Name'), 'method' => 'textbox', 'max_length' => 100, 'size' => '70', 'default' => $desc . ' [' . $template_rrd['data_source_name'] . ']', 'description' => __('Provide the Thresholds a meaningful name'), 'value' => isset($thold_data['name']) ? $thold_data['name'] : ''), 'thold_enabled' => array('friendly_name' => __('Threshold Enabled'), 'method' => 'checkbox', 'default' => 'on', 'description' => __('Whether or not this threshold will be checked and alerted upon.'), 'value' => isset($thold_data['thold_enabled']) ? $thold_data['thold_enabled'] : ''), 'exempt' => array('friendly_name' => __('Weekend Exemption'), 'description' => __('If this is checked, this Threshold will not alert on weekends.'), 'method' => 'checkbox', 'default' => '', 'value' => isset($thold_data['exempt']) ? $thold_data['exempt'] : ''), 'restored_alert' => array('friendly_name' => __('Disable Restoration Email'), 'description' => __('If this is checked, Thold will not send an alert when the threshold has returned to normal status.'), 'method' => 'checkbox', 'default' => '', 'value' => isset($thold_data['restored_alert']) ? $thold_data['restored_alert'] : ''), 'thold_type' => array('friendly_name' => __('Threshold Type'), 'method' => 'drop_array', 'on_change' => 'changeTholdType()', 'array' => $thold_types, 'default' => read_config_option('thold_type'), 'description' => __('The type of Threshold that will be monitored.'), 'value' => isset($thold_data['thold_type']) ? $thold_data['thold_type'] : ''), 'repeat_alert' => array('friendly_name' => __('Re-Alert Cycle'), 'method' => 'drop_array', 'array' => $repeatarray, 'default' => read_config_option('alert_repeat'), 'description' => __('Repeat alert after this amount of time has pasted since the last alert.'), 'value' => isset($thold_data['repeat_alert']) ? $thold_data['repeat_alert'] : ''), 'thold_warning_header' => array('friendly_name' => __('Warning - High / Low Settings'), 'method' => 'spacer'), 'thold_warning_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, warning will be triggered'), 'value' => isset($thold_data['thold_warning_hi']) ? $thold_data['thold_warning_hi'] : ''), 'thold_warning_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, warning will be triggered'), 'value' => isset($thold_data['thold_warning_low']) ? $thold_data['thold_warning_low'] : ''), 'thold_warning_fail_trigger' => array('friendly_name' => __('Breach Duration'), 'method' => 'drop_array', 'array' => $alertarray, 'description' => __('The amount of time the data source must be in breach of the threshold for a warning to be raised.'), 'value' => isset($thold_data['thold_warning_fail_trigger']) ? $thold_data['thold_warning_fail_trigger'] : read_config_option('alert_trigger')), 'thold_header' => array('friendly_name' => __('Alert - High / Low Settings'), 'method' => 'spacer'), 'thold_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, alert will be triggered'), 'value' => isset($thold_data['thold_hi']) ? $thold_data['thold_hi'] : ''), 'thold_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, alert will be triggered'), 'value' => isset($thold_data['thold_low']) ? $thold_data['thold_low'] : ''), 'thold_fail_trigger' => array('friendly_name' => __('Breach Duration'), 'method' => 'drop_array', 'array' => $alertarray, 'description' => __('The amount of time the data source must be in breach of the threshold for an alert to be raised.'), 'value' => isset($thold_data['thold_fail_trigger']) ? $thold_data['thold_fail_trigger'] : read_config_option('alert_trigger')), 'time_warning_header' => array('friendly_name' => __('Warning - Time Based Settings'), 'method' => 'spacer'), 'time_warning_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, warning will be triggered'), 'value' => isset($thold_data['time_warning_hi']) ? $thold_data['time_warning_hi'] : ''), 'time_warning_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, warning will be triggered'), 'value' => isset($thold_data['time_warning_low']) ? $thold_data['time_warning_low'] : ''), 'time_warning_fail_trigger' => array('friendly_name' => __('Breach Count'), 'method' => 'textbox', 'max_length' => 5, 'size' => 10, 'description' => __('The number of times the data source must be in breach of the threshold.'), 'value' => isset($thold_data['time_warning_fail_trigger']) ? $thold_data['time_warning_fail_trigger'] : read_config_option('thold_warning_time_fail_trigger')), 'time_warning_fail_length' => array('friendly_name' => __('Breach Window'), 'method' => 'drop_array', 'array' => $timearray, 'description' => __('The amount of time in the past to check for threshold breaches.'), 'value' => isset($thold_data['time_warning_fail_length']) ? $thold_data['time_warning_fail_length'] : (read_config_option('thold_warning_time_fail_length') > 0 ? read_config_option('thold_warning_time_fail_length') : 1)), 'time_header' => array('friendly_name' => __('Alert - Time Based Settings'), 'method' => 'spacer'), 'time_hi' => array('friendly_name' => __('High Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes above this number, alert will be triggered'), 'value' => isset($thold_data['time_hi']) ? $thold_data['time_hi'] : ''), 'time_low' => array('friendly_name' => __('Low Threshold'), 'method' => 'textbox', 'max_length' => 100, 'size' => 10, 'description' => __('If set and data source value goes below this number, alert will be triggered'), 'value' => isset($thold_data['time_low']) ? $thold_data['time_low'] : ''), 'time_fail_trigger' => array('friendly_name' => __('Breach Count'), 'method' => 'textbox', 'max_length' => 5, 'size' => 10, 'default' => read_config_option('thold_time_fail_trigger'), 'description' => __('The number of times the data source must be in breach of the threshold.'), 'value' => isset($thold_data['time_fail_trigger']) ? $thold_data['time_fail_trigger'] : read_config_option('thold_time_fail_trigger')), 'time_fail_length' => array('friendly_name' => __('Breach Window'), 'method' => 'drop_array', 'array' => $timearray, 'description' => __('The amount of time in the past to check for threshold breaches.'), 'value' => isset($thold_data['time_fail_length']) ? $thold_data['time_fail_length'] : (read_config_option('thold_time_fail_length') > 0 ? read_config_option('thold_time_fail_length') : 1)), 'baseline_header' => array('friendly_name' => __('Baseline Settings'), 'method' => 'spacer'), 'bl_ref_time_range' => array('friendly_name' => __('Time range'), 'method' => 'drop_array', 'array' => $reference_types, 'description' => __('Specifies the point in the past (based on rrd resolution) that will be used as a reference'), 'value' => isset($thold_data['bl_ref_time_range']) ? $thold_data['bl_ref_time_range'] : read_config_option('alert_bl_timerange_def')), 'bl_pct_up' => array('friendly_name' => __('Deviation UP'), 'method' => 'textbox', 'max_length' => 3, 'size' => 10, 'description' => __('Specifies allowed deviation in percentage for the upper bound threshold. If not set, upper bound threshold will not be checked at all.'), 'value' => isset($thold_data['bl_pct_up']) ? $thold_data['bl_pct_up'] : ''), 'bl_pct_down' => array('friendly_name' => __('Deviation DOWN'), 'method' => 'textbox', 'max_length' => 3, 'size' => 10, 'description' => __('Specifies allowed deviation in percentage for the lower bound threshold. If not set, lower bound threshold will not be checked at all.'), 'value' => isset($thold_data['bl_pct_down']) ? $thold_data['bl_pct_down'] : ''), 'bl_fail_trigger' => array('friendly_name' => __('Baseline Trigger Count'), 'method' => 'textbox', 'max_length' => 3, 'size' => 10, 'description' => __('Number of consecutive times the data source must be in breach of the baseline threshold for an alert to be raised.<br>Leave empty to use default value (<b>Default: %s cycles</b>)', read_config_option('alert_bl_trigger')), 'value' => isset($thold_data['bl_fail_trigger']) ? $thold_data['bl_fail_trigger'] : read_config_option("alert_bl_trigger")), 'data_manipulation' => array('friendly_name' => __('Data Manipulation'), 'method' => 'spacer'), 'data_type' => array('friendly_name' => __('Data Type'), 'method' => 'drop_array', 'on_change' => 'changeDataType()', 'array' => $data_types, 'default' => read_config_option('data_type'), 'description' => __('Special formatting for the given data.'), 'value' => isset($thold_data['data_type']) ? $thold_data['data_type'] : ''), 'cdef' => array('friendly_name' => __('Threshold CDEF'), 'method' => 'drop_array', 'default' => 'NULL', 'description' => __('Apply this CDEF before returning the data.'), 'value' => isset($thold_data['cdef']) ? $thold_data['cdef'] : 0, 'array' => thold_cdef_select_usable_names()), 'percent_ds' => array('friendly_name' => __('Percent Datasource'), 'method' => 'drop_array', 'default' => 'NULL', 'description' => __('Second Datasource Item to use as total value to calculate percentage from.'), 'value' => isset($thold_data['percent_ds']) ? $thold_data['percent_ds'] : 0, 'array' => $data_fields), 'expression' => array('friendly_name' => __('RPN Expression'), 'method' => 'textarea', 'textarea_rows' => 3, 'textarea_cols' => 80, 'default' => '', 'description' => __('An RPN Expression is an RRDtool Compatible RPN Expression.  Syntax includes all functions below in addition to both Device and Data Query replacement expressions such as <span class="deviceUp">|query_ifSpeed|</span>.  To use a Data Source in the RPN Expression, you must use the syntax: <span class="deviceUp">|ds:dsname|</span>.  For example, <span class="deviceUp">|ds:traffic_in|</span> will get the current value of the traffic_in Data Source for the RRDfile(s) associated with the Graph. Any Data Source for a Graph can be included.<br><br>Math Operators: <span class="deviceUp">+, -, /, *, &#37;, ^</span><br>Functions: <span class="deviceUp">SIN, COS, TAN, ATAN, SQRT, FLOOR, CEIL, DEG2RAD, RAD2DEG, ABS, EXP, LOG, ATAN, ADNAN</span><br>Flow Operators: <span class="deviceUp">UN, ISINF, IF, LT, LE, GT, GE, EQ, NE</span><br>Comparison Functions: <span class="deviceUp">MAX, MIN, INF, NEGINF, NAN, UNKN, COUNT, PREV</span>%s %s', $replacements, $datasources), 'value' => isset($thold_data['expression']) ? $thold_data['expression'] : '', 'max_length' => '255', 'size' => '80'), 'other_header' => array('friendly_name' => __('Other Settings'), 'method' => 'spacer'), 'notify_warning' => array('friendly_name' => __('Warning Notification List'), 'method' => 'drop_sql', 'description' => __('You may specify choose a Notification List to receive Warnings for this Data Source'), 'value' => isset($thold_data['notify_warning']) ? $thold_data['notify_warning'] : '', 'none_value' => __('None'), 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name'), 'notify_alert' => array('friendly_name' => __('Alert Notification List'), 'method' => 'drop_sql', 'description' => __('You may specify choose a Notification List to receive Alerts for this Data Source'), 'value' => isset($thold_data['notify_alert']) ? $thold_data['notify_alert'] : '', 'none_value' => __('None'), 'sql' => 'SELECT id, name FROM plugin_notification_lists ORDER BY name'));
    if (read_config_option("thold_alert_snmp") == 'on') {
        $extra = array('snmp_event_category' => array('friendly_name' => __('SNMP Notification - Event Category'), 'method' => 'textbox', 'description' => __('To allow a NMS to categorize different SNMP notifications more easily please fill in the category SNMP notifications for this template should make use of. E.g.: "disk_usage", "link_utilization", "ping_test", "nokia_firewall_cpu_utilization" ...'), 'value' => isset($thold_data['snmp_event_category']) ? $thold_data['snmp_event_category'] : '', 'default' => '', 'max_length' => '255'), 'snmp_event_severity' => array('friendly_name' => __('SNMP Notification - Alert Event Severity'), 'method' => 'drop_array', 'default' => '3', 'description' => __('Severity to be used for alerts. (low impact -> critical impact)'), 'value' => isset($thold_data['snmp_event_severity']) ? $thold_data['snmp_event_severity'] : 3, 'array' => array(1 => __('Low'), 2 => __('Medium'), 3 => __('High'), 4 => __('Critical'))));
        $form_array += $extra;
        if (read_config_option('thold_alert_snmp_warning') != 'on') {
            $extra = array('snmp_event_warning_severity' => array('friendly_name' => __('SNMP Notification - Warning Event Severity'), 'method' => 'drop_array', 'default' => '2', 'description' => __('Severity to be used for warnings. (Low impact -> Critical impact).<br>Note: The severity of warnings has to be equal or lower than the severity being defined for alerts.'), 'value' => isset($thold_data['snmp_event_warning_severity']) ? $thold_data['snmp_event_warning_severity'] : 2, 'array' => array(1 => __('Low'), 2 => __('Medium'), 3 => __('High'), 4 => __('Critical'))));
        }
        $form_array += $extra;
    }
    if (read_config_option('thold_disable_legacy') != 'on') {
        $extra = array('notify_accounts' => array('friendly_name' => __('Notify accounts'), 'method' => 'drop_multi', 'description' => __('This is a listing of accounts that will be notified when this threshold is breached.<br><br><br><br>'), 'array' => $send_notification_array, 'sql' => $sql), 'notify_extra' => array('friendly_name' => __('Alert Emails'), 'method' => 'textarea', 'textarea_rows' => 3, 'textarea_cols' => 50, 'description' => __('You may specify here extra Emails to receive alerts for this data source (comma separated)'), 'value' => isset($thold_data['notify_extra']) ? $thold_data['notify_extra'] : ''), 'notify_warning_extra' => array('friendly_name' => __('Warning Emails'), 'method' => 'textarea', 'textarea_rows' => 3, 'textarea_cols' => 50, 'description' => __('You may specify here extra Emails to receive warnings for this data source (comma separated)'), 'value' => isset($thold_data['notify_warning_extra']) ? $thold_data['notify_warning_extra'] : ''));
        $form_array += $extra;
    } else {
        $extra = array('notify_accounts' => array('method' => 'hidden', 'value' => 'ignore'), 'notify_extra' => array('method' => 'hidden', 'value' => isset($thold_data['notify_extra']) ? $thold_data['notify_extra'] : ''), 'notify_warning_extra' => array('method' => 'hidden', 'value' => isset($thold_data['notify_warning_extra']) ? $thold_data['notify_warning_extra'] : ''));
        $form_array += $extra;
    }
    draw_edit_form(array('config' => array('no_form_tag' => true), 'fields' => $form_array + array('id' => array('method' => 'hidden', 'value' => !empty($thold_data['id']) ? $thold_data['id'] : '0'), 'data_template_rrd_id' => array('method' => 'hidden', 'value' => isset($template_rrd) ? $template_rrd['id'] : '0'), 'host_id' => array('method' => 'hidden', 'value' => $thold_data['host_id']), 'local_data_id' => array('method' => 'hidden', 'value' => $thold_data['local_data_id']))));
    html_end_box();
    if (isset($_SESSION['data_return'])) {
        $ajax = false;
    } else {
        $ajax = true;
    }
    form_save_button('thold.php' . (!empty($thold_data['id']) ? '?id=' . $thold_data['id'] : ''), 'return', 'id', $ajax);
    ?>

	<script type='text/javascript'>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		templateEnableDisable();

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

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

		changeTholdType ();
		changeDataType ();

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

	</script>
	<?php 
}
示例#18
0
文件: database.php 项目: MrWnn/cacti
function db_fetch_row($sql, $log = TRUE, $db_conn = FALSE)
{
    return db_fetch_row_prepared($sql, array(), $log, $db_conn);
}
示例#19
0
function mactrack_device_edit()
{
    global $config, $fields_mactrack_device_edit;
    /* ================= input validation ================= */
    get_filter_request_var('device_id');
    /* ==================================================== */
    if (!isempty_request_var('device_id')) {
        $device = db_fetch_row_prepared('SELECT * FROM mac_track_devices WHERE device_id = ?', array(get_request_var('device_id')));
        $header_label = __('MacTrack Devices [edit: %s]', $device['device_name']);
    } else {
        $device = array();
        $header_label = __('MacTrack Devices [new]');
    }
    if (!empty($device['device_id'])) {
        ?>
		<table width='100%' align='center'>
			<tr>
				<td class='textInfo' colspan='2'>
					<?php 
        print $device['device_name'];
        ?>
 (<?php 
        print $device['hostname'];
        ?>
)
				</td>
			</tr>
			<tr>
				<td class='textHeader'>
					SNMP Information<br>

					<span style='font-size: 10px; font-weight: normal; font-family: monospace;'>
					<?php 
        /* force php to return numeric oid's */
        cacti_oid_numeric_format();
        $snmp_system = cacti_snmp_get($device['hostname'], $device['snmp_readstring'], '.1.3.6.1.2.1.1.1.0', $device['snmp_version'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], SNMP_WEBUI);
        if ($snmp_system == '') {
            print "<span style='color: #ff0000; font-weight: bold;'>SNMP error</span>\n";
        } else {
            $snmp_uptime = cacti_snmp_get($device['hostname'], $device['snmp_readstring'], '.1.3.6.1.2.1.1.3.0', $device['snmp_version'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], SNMP_WEBUI);
            $snmp_hostname = cacti_snmp_get($device['hostname'], $device['snmp_readstring'], '.1.3.6.1.2.1.1.5.0', $device['snmp_version'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], SNMP_WEBUI);
            $snmp_objid = cacti_snmp_get($device['hostname'], $device['snmp_readstring'], '.1.3.6.1.2.1.1.2.0', $device['snmp_version'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_port'], $device['snmp_timeout'], $device['snmp_retries'], SNMP_WEBUI);
            $snmp_objid = str_replace('enterprises', '.1.3.6.1.4.1', $snmp_objid);
            $snmp_objid = str_replace('OID: ', '', $snmp_objid);
            $snmp_objid = str_replace('.iso', '.1', $snmp_objid);
            print "<strong>System:</strong> {$snmp_system}<br>\n";
            print "<strong>Uptime:</strong> {$snmp_uptime}<br>\n";
            print "<strong>Hostname:</strong> {$snmp_hostname}<br>\n";
            print "<strong>ObjectID:</strong> {$snmp_objid}<br>\n";
        }
        ?>
					</span>
				</td>
			</tr>
		</table>
		<br>
		<?php 
    }
    form_start('mactrack_devices.php');
    html_start_box($header_label, '100%', '', '3', 'center', '');
    /* preserve the devices site id between refreshes via a GET variable */
    if (!isempty_request_var('site_id')) {
        $fields_host_edit['site_id']['value'] = get_request_var('site_id');
    }
    draw_edit_form(array('config' => array('no_form_tab' => true), 'fields' => inject_form_variables($fields_mactrack_device_edit, isset($device) ? $device : array())));
    html_end_box();
    form_save_button('mactrack_devices.php', 'return');
}
示例#20
0
function do_rrd()
{
    global $config, $rra_path;
    /* suppress warnings */
    error_reporting(0);
    /* install the rrdclean error handler */
    set_error_handler('rrdclean_error_handler');
    while (list($var, $val) = each($_POST)) {
        if (ereg('^chk_(.*)$', $var, $matches)) {
            /* recreate the file name */
            $unused_file = db_fetch_row_prepared('SELECT id, name, local_data_id 
				FROM data_source_purge_temp
				WHERE id = ?', array($matches[1]));
            /* add to data_source_purge_action table */
            $sql = "INSERT INTO data_source_purge_action VALUES('', ?, ?, ?) ON DUPLICATE KEY UPDATE local_data_id = VALUES(local_data_id)";
            db_execute_prepared($sql, array($unused_file['name'], $unused_file['local_data_id'], $_POST['drp_action']));
            /* drop from data_source_purge table */
            db_execute_prepared('DELETE FROM data_source_purge_temp WHERE id = ?', array($matches[1]));
        }
    }
    /* restore original error handler */
    restore_error_handler();
}
示例#21
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);
    }
}
示例#22
0
/**
 * perform mactrack_device execute action
 * @arg $action				action to be performed
 * return				-
 *  */
function mactrack_device_action_execute($action)
{
    global $config;
    # it's our turn
    if ($action == 'plugin_mactrack_device') {
        /* mactrack */
        /* find out which (if any) hosts have been checked, so we can tell the user */
        if (isset_request_var('selected_items')) {
            $selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items'));
            if ($selected_items != false) {
                /* work on all selected hosts */
                for ($i = 0; $i < count($selected_items); $i++) {
                    # fetch row from host table
                    $device = db_fetch_row_prepared('SELECT * from host WHERE id = ?', array($selected_items[$i]));
                    # now fetch the related device from mac_track_devices, if any
                    $mt_device = db_fetch_row_prepared('SELECT * from mac_track_devices WHERE host_id = ?', array($device['id']));
                    if (is_array($device)) {
                        # update mac_track_device
                        $device_id = api_mactrack_device_save(isset($mt_device['device_id']) ? $mt_device['device_id'] : '0', $device['id'], get_request_var('site_id'), $device['hostname'], $device['description'], get_request_var('scan_type'), get_request_var('snmp_options'), $device['snmp_community'], $device['snmp_version'], $device['snmp_username'], $device['snmp_password'], $device['snmp_auth_protocol'], $device['snmp_priv_passphrase'], $device['snmp_priv_protocol'], $device['snmp_context'], $device['snmp_engine_id'], $device['snmp_port'], $device['snmp_timeout'], get_request_var('snmp_retries'), $device['max_oids'], get_request_var('ignorePorts'), $device['notes'], get_request_var('user_name'), get_request_var('user_password'), get_request_var('term_type'), get_request_var('private_key_path'), isset_request_var('disabled') ? get_request_var('disabled') : '');
                    }
                }
            }
        }
    }
    return $action;
}
示例#23
0
function thold_add_graphs_action_execute()
{
    global $config;
    include_once $config['base_path'] . '/plugins/thold/thold_functions.php';
    $host_id = get_filter_request_var('host_id');
    $local_graph_id = get_filter_request_var('local_data_id');
    $thold_template_id = get_filter_request_var('thold_template_id');
    $message = '';
    $template = db_fetch_row_prepared('SELECT * FROM thold_template WHERE id = ?', array($thold_template_id));
    $temp = db_fetch_row_prepared('SELECT dtr.*
		 FROM data_template_rrd AS dtr
		 LEFT JOIN graph_templates_item AS gti
		 ON gti.task_item_id=dtr.id
		 LEFT JOIN graph_local AS gl
		 ON gl.id=gti.local_graph_id
		 WHERE gl.id = ?', array($local_graph_id));
    $data_template_id = $temp['data_template_id'];
    $local_data_id = $temp['local_data_id'];
    $data_source = db_fetch_row_prepared('SELECT * FROM data_local WHERE id = ?', array($local_data_id));
    $data_template_id = $data_source['data_template_id'];
    /* allow duplicate thresholds, but only from differing templates */
    $existing = db_fetch_assoc('SELECT id
		FROM thold_data
		WHERE local_data_id=' . $local_data_id . '
		AND data_template_rrd_id=' . $data_template_id . '
		AND thold_template_id=' . $template['id'] . " AND template_enabled='on'");
    if (count($existing) == 0 && count($template)) {
        if ($local_graph_id) {
            $rrdlookup = db_fetch_cell("SELECT id FROM data_template_rrd WHERE local_data_id={$local_data_id} ORDER BY id LIMIT 1");
            $grapharr = db_fetch_row("SELECT graph_template_id FROM graph_templates_item WHERE task_item_id={$rrdlookup} AND local_graph_id = {$local_graph_id}");
            $desc = db_fetch_cell_prepared('SELECT name_cache FROM data_template_data WHERE local_data_id = ? LIMIT 1', array($local_data_id));
            $data_source_name = $template['data_source_name'];
            $insert = array();
            $name = thold_format_name($template, $local_graph_id, $local_data_id, $data_source_name);
            $insert['name'] = $name;
            $insert['host_id'] = $data_source['host_id'];
            $insert['local_data_id'] = $local_data_id;
            $insert['local_graph_id'] = $local_graph_id;
            $insert['data_template_id'] = $data_template_id;
            $insert['graph_template_id'] = $grapharr['graph_template_id'];
            $insert['thold_hi'] = $template['thold_hi'];
            $insert['thold_low'] = $template['thold_low'];
            $insert['thold_fail_trigger'] = $template['thold_fail_trigger'];
            $insert['thold_enabled'] = $template['thold_enabled'];
            $insert['thold_warning_hi'] = $template['thold_warning_hi'];
            $insert['thold_warning_low'] = $template['thold_warning_low'];
            $insert['thold_warning_fail_trigger'] = $template['thold_warning_fail_trigger'];
            $insert['bl_ref_time_range'] = $template['bl_ref_time_range'];
            $insert['bl_pct_down'] = $template['bl_pct_down'];
            $insert['bl_pct_up'] = $template['bl_pct_up'];
            $insert['bl_fail_trigger'] = $template['bl_fail_trigger'];
            $insert['bl_alert'] = $template['bl_alert'];
            $insert['repeat_alert'] = $template['repeat_alert'];
            $insert['notify_extra'] = $template['notify_extra'];
            $insert['cdef'] = $template['cdef'];
            $insert['thold_template_id'] = $template['id'];
            $insert['template_enabled'] = 'on';
            $rrdlist = db_fetch_assoc("SELECT id, data_input_field_id\n\t\t\t\tFROM data_template_rrd\n\t\t\t\tWHERE local_data_id='{$local_data_id}'\n\t\t\t\tAND data_source_name='{$data_source_name}'");
            $int = array('id', 'data_template_id', 'data_source_id', 'thold_fail_trigger', 'bl_ref_time_range', 'bl_pct_down', 'bl_pct_up', 'bl_fail_trigger', 'bl_alert', 'repeat_alert', 'cdef');
            foreach ($rrdlist as $rrdrow) {
                $data_rrd_id = $rrdrow['id'];
                $insert['data_template_rrd_id'] = $data_rrd_id;
                $existing = db_fetch_assoc("SELECT id\n\t\t\t\t\tFROM thold_data\n\t\t\t\t\tWHERE local_data_id='{$local_data_id}'\n\t\t\t\t\tAND data_template_rrd_id='{$data_rrd_id}'\n\t\t\t\t\tAND thold_template_id='" . $template['id'] . "' AND template_enabled='on'");
                if (count($existing) == 0) {
                    $insert['id'] = 0;
                    $id = sql_save($insert, 'thold_data');
                    if ($id) {
                        thold_template_update_threshold($id, $insert['template']);
                        $l = db_fetch_assoc("SELECT name FROM data_template where id={$data_template_id}");
                        $tname = $l[0]['name'];
                        $name = $data_source_name;
                        if ($rrdrow['data_input_field_id'] != 0) {
                            $l = db_fetch_assoc('SELECT name FROM data_input_fields where id=' . $rrdrow['data_input_field_id']);
                            $name = $l[0]['name'];
                        }
                        plugin_thold_log_changes($id, 'created', " {$tname} [{$name}]");
                        $message .= "Created threshold for the Graph '<i>{$tname}</i>' using the Data Source '<i>{$name}</i>'<br>";
                    }
                }
            }
        }
    }
    if (strlen($message)) {
        $_SESSION['thold_message'] = "<font size=-2>{$message}</font>";
    } else {
        $_SESSION['thold_message'] = "<font size=-2>" . __('Threshold(s) Already Exists - No Thresholds Created') . "</font>";
    }
    raise_message('thold_message');
    if (isset($_SESSION['graph_return'])) {
        $return_to = $_SESSION['graph_return'];
        unset($_SESSION['graph_return']);
        kill_session_var('graph_return');
        header('Location: ' . $return_to . (strpos($return_to, '?') !== false ? '&' : '?') . 'header=false');
    } else {
        header('Location:' . $config['url_path'] . 'plugins/thold/thold.php?header=false');
    }
}
示例#24
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');
}
示例#25
0
function domain_edit()
{
    global $ldap_versions, $ldap_encryption, $ldap_modes, $domain_types;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('domain_id'));
    /* ==================================================== */
    if (!empty($_REQUEST['domain_id'])) {
        $domain = db_fetch_row_prepared('SELECT * FROM user_domains WHERE domain_id = ?', array($_REQUEST['domain_id']));
        $header_label = '[edit: ' . $domain['domain_name'] . ']';
    } else {
        $header_label = '[new]';
    }
    /* file: data_input.php, action: edit */
    $fields_domain_edit = array('domain_name' => array('method' => 'textbox', 'friendly_name' => 'Name', 'description' => 'Enter a meaningful name for this domain.  This will be the name that appears
			in the Login Realm during login.', 'value' => '|arg1:domain_name|', 'max_length' => '255'), 'type' => array('method' => 'drop_array', 'friendly_name' => 'Domains Type', 'description' => 'Choose what type of domain this is.', 'value' => '|arg1:type|', 'array' => $domain_types, 'default' => '2'), 'user_id' => array('friendly_name' => 'User Template', 'description' => 'The name of the user that Cacti will use as a template for new user accounts.', 'method' => 'drop_sql', 'value' => '|arg1:user_id|', 'none_value' => 'No User', 'sql' => 'SELECT id AS id, username AS name FROM user_auth WHERE realm=0 ORDER BY username', 'default' => '0'), 'enabled' => array('method' => 'checkbox', 'friendly_name' => 'Enabled', 'description' => 'If this checkbox is checked, users will be able to login using this domain.', 'value' => '|arg1:enabled|', 'default' => ''), 'domain_id' => array('method' => 'hidden_zero', 'value' => '|arg1:domain_id|'), 'save_component_domain' => array('method' => 'hidden', 'value' => '1'));
    $fields_domain_ldap_edit = array('server' => array('friendly_name' => 'Server', 'description' => 'The dns hostname or ip address of the server.', 'method' => 'textbox', 'value' => '|arg1:server|', 'default' => read_config_option('ldap_server'), 'max_length' => '255'), 'port' => array('friendly_name' => 'Port Standard', 'description' => 'TCP/UDP port for Non SSL communications.', 'method' => 'textbox', 'max_length' => '5', 'value' => '|arg1:port|', 'default' => read_config_option('ldap_port'), 'size' => '5'), 'port_ssl' => array('friendly_name' => 'Port SSL', 'description' => 'TCP/UDP port for SSL communications.', 'method' => 'textbox', 'max_length' => '5', 'value' => '|arg1:port_ssl|', 'default' => read_config_option('ldap_port_ssl'), 'size' => '5'), 'proto_version' => array('friendly_name' => 'Protocol Version', 'description' => 'Protocol Version that the server supports.', 'method' => 'drop_array', 'value' => '|arg1:proto_version|', 'array' => $ldap_versions), 'encryption' => array('friendly_name' => 'Encryption', 'description' => 'Encryption that the server supports. TLS is only supported by Protocol Version 3.', 'method' => 'drop_array', 'value' => '|arg1:encryption|', 'array' => $ldap_encryption), 'referrals' => array('friendly_name' => 'Referrals', 'description' => 'Enable or Disable LDAP referrals.  If disabled, it may increase the speed of searches.', 'method' => 'drop_array', 'value' => '|arg1:referrals|', 'array' => array('0' => 'Disabled', '1' => 'Enable')), 'mode' => array('friendly_name' => 'Mode', 'description' => 'Mode which cacti will attempt to authenicate against the LDAP server.<blockquote><i>No Searching</i> - No Distinguished Name (DN) searching occurs, just attempt to bind with the provided Distinguished Name (DN) format.<br><br><i>Anonymous Searching</i> - Attempts to search for username against LDAP directory via anonymous binding to locate the users Distinguished Name (DN).<br><br><i>Specific Searching</i> - Attempts search for username against LDAP directory via Specific Distinguished Name (DN) and Specific Password for binding to locate the users Distinguished Name (DN).', 'method' => 'drop_array', 'value' => '|arg1:mode|', 'array' => $ldap_modes), 'dn' => array('friendly_name' => 'Distinguished Name (DN)', 'description' => 'Distinguished Name syntax, such as for windows: <i>"&lt;username&gt;@win2kdomain.local"</i> or for OpenLDAP: <i>"uid=&lt;username&gt;,ou=people,dc=domain,dc=local"</i>.   "&lt;username&gt" is replaced with the username that was supplied at the login prompt.  This is only used when in "No Searching" mode.', 'method' => 'textbox', 'value' => '|arg1:dn|', 'max_length' => '255'), 'group_require' => array('friendly_name' => 'Require Group Membership', 'description' => 'Require user to be member of group to authenicate. Group settings must be set for this to work, enabling without proper group settings will cause authenication failure.', 'value' => '|arg1:group_require|', 'method' => 'checkbox'), 'group_header' => array('friendly_name' => 'LDAP Group Settings', 'method' => 'spacer'), 'group_dn' => array('friendly_name' => 'Group Distingished Name (DN)', 'description' => 'Distingished Name of the group that user must have membership.', 'method' => 'textbox', 'value' => '|arg1:group_dn|', 'max_length' => '255'), 'group_attrib' => array('friendly_name' => 'Group Member Attribute', 'description' => 'Name of the attribute that contains the usernames of the members.', 'method' => 'textbox', 'value' => '|arg1:group_attrib|', 'max_length' => '255'), 'group_member_type' => array('friendly_name' => 'Group Member Type', 'description' => 'Defines if users use full Distingished Name or just Username in the defined Group Member Attribute.', 'method' => 'drop_array', 'value' => '|arg1:group_member_type|', 'array' => array(1 => 'Distingished Name', 2 => 'Username')), 'search_base_header' => array('friendly_name' => 'LDAP Specific Search Settings', 'method' => 'spacer'), 'search_base' => array('friendly_name' => 'Search Base', 'description' => 'Search base for searching the LDAP directory, such as <i>"dc=win2kdomain,dc=local"</i> or <i>"ou=people,dc=domain,dc=local"</i>.', 'method' => 'textbox', 'value' => '|arg1:search_base|', 'max_length' => '255'), 'search_filter' => array('friendly_name' => 'Search Filter', 'description' => 'Search filter to use to locate the user in the LDAP directory, such as for windows: <i>"(&amp;(objectclass=user)(objectcategory=user)(userPrincipalName=&lt;username&gt;*))"</i> or for OpenLDAP: <i>"(&(objectClass=account)(uid=&lt;username&gt))"</i>.  "&lt;username&gt" is replaced with the username that was supplied at the login prompt. ', 'method' => 'textbox', 'value' => '|arg1:search_filter|', 'max_length' => '255'), 'specific_dn' => array('friendly_name' => 'Search Distingished Name (DN)', 'description' => 'Distinguished Name for Specific Searching binding to the LDAP directory.', 'method' => 'textbox', 'value' => '|arg1:specific_dn|', 'max_length' => '255'), 'specific_password' => array('friendly_name' => 'Search Password', 'description' => 'Password for Specific Searching binding to the LDAP directory.', 'method' => 'textbox_password', 'value' => '|arg1:specific_password|', 'max_length' => '255'), 'save_component_domain_ldap' => array('method' => 'hidden', 'value' => '1'));
    html_start_box('<strong>User Domain</strong> $header_label', '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array(), 'fields' => inject_form_variables($fields_domain_edit, isset($domain) ? $domain : array())));
    html_end_box();
    if (!empty($_REQUEST['domain_id'])) {
        $domain = db_fetch_row_prepared('SELECT * FROM user_domains_ldap WHERE domain_id = ?', array($_REQUEST['domain_id']));
        html_start_box('<strong>Domain Properties</strong>', '100%', '', '3', 'center', '');
        draw_edit_form(array('config' => array(), 'fields' => inject_form_variables($fields_domain_ldap_edit, isset($domain) ? $domain : array())));
        html_end_box();
    }
    ?>
	<script type='text/javascript'>
	function initGroupMember() {
		if ($('#group_require').is(':checked')) {
			$('#row_group_header').show();
			$('#row_group_dn').show();
			$('#row_group_attrib').show();
			$('#row_group_member_type').show();
		}else{
			$('#row_group_header').hide();
			$('#row_group_dn').hide();
			$('#row_group_attrib').hide();
			$('#row_group_member_type').hide();
		}
	}

	function initSearch() {
		switch($('#mode').val()) {
		case "0":
			$('#row_search_base_header').hide();
			$('#row_search_base').hide();
			$('#row_search_filter').hide();
			$('#row_specific_dn').hide();
			$('#row_specific_password').hide();
			break;
		case "1":
			$('#row_search_base_header').show();
			$('#row_search_base').show();
			$('#row_search_filter').show();
			$('#row_specific_dn').hide();
			$('#row_specific_password').hide();
			break;
		case "2":
			$('#row_search_base_header').show();
			$('#row_search_base').show();
			$('#row_search_filter').show();
			$('#row_specific_dn').show();
			$('#row_specific_password').show();
			break;
		}
	}

	$(function(data) {
		initSearch();
		initGroupMember();

		$('#mode').change(function() {
			initSearch();
       		});

		$('#group_require').change(function() {
			initGroupMember();
		});
	});
	</script>
	<?php 
    form_save_button('user_domains.php', 'return', 'domain_id');
}
示例#26
0
文件: tree.php 项目: MrWnn/cacti
function tree_edit()
{
    global $fields_tree_edit;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('id'));
    input_validate_input_number(get_request_var_request('type'));
    /* ==================================================== */
    /* clean up search string */
    if (isset($_REQUEST['filter'])) {
        $_REQUEST['filter'] = sanitize_search_string(get_request_var_request('filter'));
    }
    load_current_session_value('filter', 'sess_tree_edit_filter', '');
    load_current_session_value('type', 'sess_tree_edit_type', '0');
    if (!empty($_REQUEST['id'])) {
        $tree = db_fetch_row_prepared('SELECT * FROM graph_tree WHERE id = ?', array($_REQUEST['id']));
        $header_label = '[edit: ' . htmlspecialchars($tree['name']) . ']';
    } else {
        $header_label = '[new]';
    }
    // Reset the cookie state if tree id has changed
    if (isset($_SESSION['sess_tree_id']) && $_SESSION['sess_tree_id'] != $_REQUEST['id']) {
        $select_first = true;
    } else {
        $select_first = false;
    }
    $_SESSION['sess_tree_id'] = $_REQUEST['id'];
    html_start_box('<strong>Graph Trees</strong> ' . $header_label, '100%', '', '3', 'center', '');
    draw_edit_form(array('config' => array(), 'fields' => inject_form_variables($fields_tree_edit, isset($tree) ? $tree : array())));
    html_end_box();
    $lockdiv = '';
    if (isset($tree['locked']) && $tree['locked'] == 0) {
        $lockdiv = "<div style='padding:3px;'><table><tr><td><input id='lock' type='button' value='Edit Tree'></td><td style='font-weight:bold;'>To Edit this tree, you must first lock it by pressing the Edit Tree button.</td></tr></table></div>\n";
        $editable = false;
    } elseif (isset($tree['locked']) && $tree['locked'] == 1) {
        $lockdiv = "<div style='padding:3px;'><table><tr><td><input id='unlock' type='button' value='Finish Editing Tree'></td><td><input id='addbranch' type='button' value='Add Root Branch' onClick='createNode()'></td><td style='font-weight:bold;'>The tree was locked for Editing on '" . $tree['locked_date'] . "' by '" . get_username($tree['modified_by']) . "'";
        if ($tree['modified_by'] == $_SESSION['sess_user_id']) {
            $editable = true;
            $lockdiv .= '</td></tr></table></div>';
        } else {
            $editable = false;
            $lockdiv .= '. To edit the tree, you must first unlock it and then lock it as yourself</td></tr></table></div>';
        }
    } else {
        $tree['id'] = 0;
        $editable = true;
    }
    if ($editable) {
        form_save_button('tree.php', 'return');
    }
    print $lockdiv;
    print "<table class='treeTable' cellpadding='0' cellspacing='0' width='100%' border='0' valign='top'><tr valign='top'><td class='treeArea'>\n";
    if (!empty($_REQUEST['id'])) {
        html_start_box('<strong>Tree Items</strong>', '100%', '', '3', 'center', '');
        echo "<tr><td style='padding:7px;'><div id='jstree'></div></td></tr>\n";
        html_end_box();
        print "</td><td></td><td class='treeItemsArea'>\n";
        html_start_box('<strong>Available Devices</strong>', '100%', '', '3', 'center', '');
        ?>
		<tr id='treeFilter' class='even noprint'>
			<td>
			<form id='form_tree' action='tree.php'>
				<table cellpadding='2' cellspacing='0'>
					<tr>
						<td width='50'>
							Search
						</td>
						<td>
							<input id='hfilter' type='text' name='hfilter' size='25' value='<?php 
        print htmlspecialchars(get_request_var_request('hfilter'));
        ?>
'>
						</td>
					</tr>
				</table>
			</form>
			</td>
		</tr>
		<?php 
        html_end_box(false);
        $display_text = array('Description');
        html_start_box('', '100%', '', '3', 'center', '');
        html_header($display_text);
        echo "<tr><td style='padding:7px;'><div id='hosts'>\n";
        display_hosts();
        echo "</div></td></tr>\n";
        html_end_box();
        print "</td><td></td><td class='treeItemsArea'>\n";
        html_start_box('<strong>Available Graphs</strong>', '100%', '', '3', 'center', '');
        ?>
		<tr id='treeFilter' class='even noprint'>
			<td>
			<form id='form_tree' action='tree.php'>
				<table cellpadding='2' cellspacing='0'>
					<tr>
						<td>
							Search
						</td>
						<td>
							<input id='grfilter' type='text' name='grfilter' size='25' value='<?php 
        print htmlspecialchars(get_request_var_request('grfilter'));
        ?>
'>
						</td>
					</tr>
				</table>
			</form>
			</td>
		</tr>
		<?php 
        html_end_box(false);
        $display_text = array('Graph Name');
        html_start_box('', '100%', '', '3', 'center', '');
        html_header($display_text);
        echo "<tr><td style='padding:7px;'><div id='graphs'>\n";
        display_graphs();
        echo "</div></td></tr>\n";
        html_end_box();
        print "</td></tr></table>\n";
        ?>
		<script type='text/javascript'>
		<?php 
        if ($select_first) {
            print "var reset=true;\n";
        } else {
            print "var reset=false;\n";
        }
        ?>

		var graphMeTimer;
		var hostMeTimer;
		var hostSortInfo   = {};
		var branchSortInfo = {};

		function createNode() {
			var ref = $('#jstree').jstree(true),
			sel = ref.create_node('#', 'New Node', '0');
			if (sel) {
				ref.edit(sel);
			}
		};

		function getGraphData() {
			$.get('tree.php?action=graphs&filter='+$('#grfilter').val(), function(data) {
				$('#graphs').jstree('destroy');
				$('#graphs').html(data);
				dragable('#graphs');
			});
		}

		function getHostData() {
			$.get('tree.php?action=hosts&filter='+$('#hfilter').val(), function(data) {
				$('#hosts').jstree('destroy');
				$('#hosts').html(data);
				dragable('#hosts');
			});
		}

		function setHostSortIcon(nodeid) {
			if (hostSortInfo[nodeid]) {
				// Already set
			}else{
				$.get('tree.php?action=get_host_sort&nodeid='+nodeid, function(data) {
					hostSortInfo[nodeid] = data;
				});
			}
		}

		function setBranchSortIcon(nodeid) {
			if (branchSortInfo[nodeid]) {
				// Already set
			}else{
				$.get('tree.php?action=get_branch_sort&nodeid='+nodeid, function(data) {
					branchSortInfo[nodeid] = data;
				});
			}
		}

		function getHostSortIcon(type, nodeid) {
			if (hostSortInfo[nodeid] == type) {
				return 'fa fa-check';
			}else{
				return 'false';
			}
		}

		function getBranchSortIcon(type, nodeid) {
			if (branchSortInfo[nodeid] == type) {
				return 'fa fa-check';
			}else{
				return 'false';
			}
		}

		function setBranchSortOrder(type, nodeid) {
			$.get('tree.php?action=set_branch_sort&type='+type+'&nodeid='+nodeid, function(data) {
				branchSortInfo[nodeid] = type;
			});
		}

		function setHostSortOrder(type, nodeid) {
			$.get('tree.php?action=set_host_sort&type='+type+'&nodeid='+nodeid, function(data) {
				hostSortInfo[nodeid] = type;
			});
		}

		$(function() {
			<?php 
        if ($editable == false) {
            ?>
			$('select, input').not('#lock').prop('disabled', true);
			<?php 
        } else {
            ?>
			$('select, input').prop('disabled', false);
			<?php 
        }
        ?>

			$('input[value="Save"]').click(function(event) {
				event.preventDefault();
				$.post('tree.php', { action: 'save', name: $('#name').val(), sort_type: $('#sort_type').val(), enabled: $('#enabled').is(':checked'), id: $('#id').val(), save_component_tree: 1 } ).done(function(data) {
					$('#main').html(data);
					applySkin();
				});
			});

			$('#lock').click(function() {
				$.get('tree.php?action=lock&id=<?php 
        print $tree['id'];
        ?>
&header=false', function(data) {
					$('#main').html(data);
					applySkin();
				});
			});

			$('#unlock').click(function() {
				$.get('tree.php?action=unlock&id=<?php 
        print $tree['id'];
        ?>
&header=false', function(data) {
					$('#main').html(data);
					applySkin();
				});
			});

			var height      = parseInt($(window).height()-$('#jstree').offset().top-10)+'px';
			var hheight     = parseInt($(window).height()-$('#hosts').offset().top-10)+'px';
			var gheight     = parseInt($(window).height()-$('#graphs').offset().top-10)+'px';

			$(window).resize(function() {
				height      = parseInt($(window).height()-$('#jstree').offset().top-10)+'px';
				hheight     = parseInt($(window).height()-$('#hosts').offset().top-10)+'px';
				gheight     = parseInt($(window).height()-$('#graphs').offset().top-10)+'px';
				$('#jstree').css('height', height).css('overflow','auto');;
				$('#hosts').css('height', hheight).css('overflow','auto');;
				$('#graphs').css('height', gheight).css('overflow','auto');;
			});

			$("#jstree")
			.jstree({
				'types' : {
					'device' : {
						icon : 'images/server.png',
						max_children : 0
					},
					'graph' : {
						icon : 'images/server_chart_curve.png',
						max_children : 0
					}
				},
				'contextmenu' : {
					'items': function(node) {
						if (node.id.search('tgraph') > 0) {
							var dataType = 'graph';
						}else if (node.id.search('thost') > 0) {
							var dataType = 'host';
						}else {
							var dataType = 'branch';
						}
						if (dataType == 'graph') {
							return graphContext(node.id);
						}else if (dataType == 'host') {
							return hostContext(node.id);
						}else{
							return branchContext(node.id);
						}
					}
				},
				'core' : {
					'data' : {
						'url' : 'tree.php?action=get_node&tree_id='+$('#id').val(),
						'data' : function(node) {
							return { 'id' : node.id }
						}
					},
					'animation' : 0,
					'check_callback' : true
				},
				'themes' : {
					'name' : 'default',
					'responsive' : true,
					'url' : true,
					'dots' : false
				},
				'state': { 'key': 'tree_<?php 
        print $_REQUEST['id'];
        ?>
' },
				'plugins' : [ 'state', 'wholerow', <?php 
        if ($editable) {
            ?>
'contextmenu', 'dnd', <?php 
        }
        ?>
'types' ]
			})
			.on('ready.jstree', function(e, data) {
				if (reset == true) {
					$('#jstree').jstree('clear_state');
				}
			})<?php 
        if ($editable) {
            ?>
.on('delete_node.jstree', function (e, data) {
				$.get('?action=delete_node', { 'id' : data.node.id, 'tree_id' : $('#id').val() })
					.fail(function () {
						data.instance.refresh();
					});
				})
			.on('hover_node.jstree', function (e, data) {
				if (data.node.id.search('thost') >= 0) {
					setHostSortIcon(data.node.id);
				}else if (data.node.id.search('thost') < 0 && data.node.id.search('tgraph') < 0) {
					setBranchSortIcon(data.node.id);
				}
			})
			.on('create_node.jstree', function (e, data) {
				$.get('?action=create_node', { 'id' : data.node.parent, 'tree_id' : $('#id').val(), 'position' : data.position, 'text' : data.node.text })
					.done(function (d) {
						data.instance.set_id(data.node, d.id);
					})
					.fail(function () {
						data.instance.refresh();
					});
			})
			.on('rename_node.jstree', function (e, data) {
				$.get('?action=rename_node', { 'id' : data.node.id, 'tree_id' : $('#id').val(), 'text' : data.text })
					.fail(function () {
						data.instance.refresh();
					});
			})
			.on('move_node.jstree', function (e, data) {
				$.get('?action=move_node', { 'id' : data.node.id, 'tree_id' : $('#id').val(), 'parent' : data.parent, 'position' : data.position })
					.always(function () {
						data.instance.refresh();
					});
			})
			.on('copy_node.jstree', function (e, data) {
				$.get('?action=copy_node', { 'id' : data.original.id, 'tree_id' : $('#id').val(), 'parent' : data.parent, 'position' : data.position })
					.always(function () {
						data.instance.refresh();
					});
			})<?php 
        } else {
            ?>
.children().bind('contextmenu', function(event) {
				return false;
			})<?php 
        }
        ?>
;

			$('#jstree').css('height', height).css('overflow','auto');;

			dragable('#graphs');
			dragable('#hosts');
		});

		function dragable(element) {
			$(element)
				.jstree({
					'types' : {
						'device' : {
							icon : 'images/server.png',
							valid_children: 'none',
							max_children : 0
						},
						'graph' : {
							icon : 'images/server_chart_curve.png',
							valid_children: 'none',
							max_children : 0
						}
					},
					'core' : {
						'animation' : 0,
						'check_callback' : true
					},
					'dnd' : {
						'always_copy' : true
					},
					'themes' : { 'stripes' : true },
					'plugins' : [ 'wholerow', 'state', <?php 
        if ($editable) {
            ?>
'dnd', <?php 
        }
        ?>
'types' ]
				})
				.on('ready.jstree', function(e, data) {
					if (reset == true) {
						$('#jstree').jstree('clear_state');
					}
				})<?php 
        if ($editable) {
            ?>
				.on('copy_node.jstree', function (e, data) {
					$.get('?action=copy_node', { 'id' : data.original.id, 'parent' : data.parent, 'position' : data.position })
						.always(function () {
							data.instance.refresh();
						});
				})<?php 
        }
        ?>
;
				$(element).find('.jstree-ocl').hide();
				$(element).children().bind('contextmenu', function(event) {
					return false;
				});
		}

		function branchContext(nodeid) {
			return {
				'create' : {
					'separator_before'	: false,
					'separator_after'	: true,
					'icon'				: 'fa fa-folder',
					'_disabled'			: false,
					'label'				: 'Create',
					'action'			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						inst.create_node(obj, {}, 'last', function (new_node) {
							setTimeout(function () { inst.edit(new_node); },0);
						});
					}
				},
				'rename' : {
					'separator_before'	: false,
					'separator_after'	: false,
					'icon'				: 'fa fa-pencil',
					'_disabled'			: false,
					'label'				: 'Rename',
					'action'			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						inst.edit(obj);
					}
				},
				'remove' : {
					'separator_before'	: false,
					'icon'				: 'fa fa-remove',
					'separator_after'	: false,
					'_disabled'			: false,
					'label'				: 'Delete',
					'action'			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						if(inst.is_selected(obj)) {
							inst.delete_node(inst.get_selected());
						}
						else {
							inst.delete_node(obj);
						}
					}
				},
				'bst' : {
					'separator_before'	: true,
					'icon'				: 'fa fa-sort',
					'separator_after'	: false,
					'label'				: 'Branch Sorting',
					'action'			: false,
					'submenu' : {
						'inherit' : {
							'separator_before'	: false,
							'separator_after'	: false,
							'icon'				: getBranchSortIcon('inherit', nodeid),
							'label'				: 'Inherit',
							'action'			: function (data) {
								setBranchSortOrder('inherit', nodeid);
							}
						},
						'manual' : {
							'separator_before'	: false,
							'separator_after'	: false,
							'icon'				: getBranchSortIcon('manual', nodeid),
							'label'				: 'Manual',
							'action'			: function (data) {
								setBranchSortOrder('manual', nodeid);
							}
						},
						'alpha' : {
							'separator_before'	: false,
							'icon'				: getBranchSortIcon('alpha', nodeid),
							'separator_after'	: false,
							'label'				: 'Alphabetic',
							'action'			: function (data) {
								setBranchSortOrder('alpha', nodeid);
							}
						},
						'natural' : {
							'separator_before'	: false,
							'icon'				: getBranchSortIcon('natural', nodeid),
							'separator_after'	: false,
							'label'				: 'Natural',
							'action'			: function (data) {
								setBranchSortOrder('natural', nodeid);
							}
						},
						'numeric' : {
							'separator_before'	: false,
							'icon'				: getBranchSortIcon('numeric', nodeid),
							'separator_after'	: false,
							'label'				: 'Numeric',
							'action'			: function (data) {
								setBranchSortOrder('numeric', nodeid);
							}
						}
					}
				},
				'ccp' : {
					'separator_before'	: true,
					'icon'				: 'fa fa-edit',
					'separator_after'	: false,
					'label'				: 'Edit',
					'action'			: false,
					'submenu' : {
						'cut' : {
							'separator_before'	: false,
							'separator_after'	: false,
							'icon'				: 'fa fa-cut',
							'label'				: 'Cut',
							'action'			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.cut(inst.get_selected());
								}
								else {
									inst.cut(obj);
								}
							}
						},
						'copy' : {
							'separator_before'	: false,
							'icon'				: 'fa fa-copy',
							'separator_after'	: false,
							'label'				: 'Copy',
							'action'			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.copy(inst.get_selected());
								}
								else {
									inst.copy(obj);
								}
							}
						},
						'paste' : {
							'separator_before'	: false,
							'icon'				: 'fa fa-paste',
							'_disabled'			: function (data) {
								return !$.jstree.reference(data.reference).can_paste();
							},
							'separator_after'	: false,
							'label'				: 'Paste',
							'action'			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								inst.paste(obj);
							}
						}
					}
				}
			};
		}

		function graphContext(nodeid) {
			return {
				'remove' : {
					'separator_before'	: false,
					'icon'				: 'fa fa-remove',
					'separator_after'	: false,
					'_disabled'			: false, //(this.check('delete_node', data.reference, this.get_parent(data.reference), '')),
					'label'				: 'Delete',
					'action'			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						if(inst.is_selected(obj)) {
							inst.delete_node(inst.get_selected());
						}
						else {
							inst.delete_node(obj);
						}
					}
				},
				'ccp' : {
					'separator_before'	: true,
					'icon'				: 'fa fa-edit',
					'separator_after'	: false,
					'label'				: 'Edit',
					'action'			: false,
					'submenu' : {
						'cut' : {
							'separator_before'	: false,
							'separator_after'	: false,
							'icon'				: 'fa fa-cut',
							'label'				: 'Cut',
							'action'			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.cut(inst.get_selected());
								}
								else {
									inst.cut(obj);
								}
							}
						},
						'copy' : {
							'separator_before'	: false,
							'icon'				: 'fa fa-copy',
							'separator_after'	: false,
							'label'				: 'Copy',
							'action'			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.copy(inst.get_selected());
								}
								else {
									inst.copy(obj);
								}
							}
						}
					}
				}
			};
		}

		function hostContext(nodeid) {
			return {
				'remove' : {
					'separator_before'	: false,
					'icon'				: 'fa fa-remove',
					'separator_after'	: false,
					'_disabled'			: false,
					'label'				: 'Delete',
					'action'			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						if(inst.is_selected(obj)) {
							inst.delete_node(inst.get_selected());
						}
						else {
							inst.delete_node(obj);
						}
					}
				},
				'hso' : {
					'separator_before'	: true,
					'separator_after'	: false,
					'icon'				: 'fa fa-sort',
					'label'				: 'Sorting Type',
					'action'			: false,
					'submenu' : {
						'hsgt' : {
							'separator_before'	: false,
							'icon'				: getHostSortIcon('hsgt', nodeid),
							'separator_after'	: false,
							'label'				: 'Graph Template',
							'action'			: function (data) {
								setHostSortOrder('hsgt', nodeid);
							}
						},
						'hsdq' : {
							'separator_before'	: false,
							'icon'				: getHostSortIcon('hsdq', nodeid),
							'separator_after'	: false,
							'label'				: 'Data Query Index',
							'action'			: function (data) {
								setHostSortOrder('hsdq', nodeid);
							}
						}
					}
				},
				'ccp' : {
					'separator_before'	: true,
					'icon'				: 'fa fa-edit',
					'separator_after'	: false,
					'label'				: 'Edit',
					'action'			: false,
					'submenu' : {
						'cut' : {
							'separator_before'	: false,
							'separator_after'	: false,
							'icon'				: 'fa fa-cut',
							'label'				: 'Cut',
							'action'			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.cut(inst.get_selected());
								}
								else {
									inst.cut(obj);
								}
							}
						},
						'copy' : {
							'separator_before'	: false,
							'icon'				: 'fa fa-copy',
							'separator_after'	: false,
							'label'				: 'Copy',
							'action'			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.copy(inst.get_selected());
								}
								else {
									inst.copy(obj);
								}
							}
						}
					}
				}
			};
		}

		$('#grfilter').keyup(function(data) {
			graphMeTimer && clearTimeout(graphMeTimer);
			graphMeTimer = setTimeout(getGraphData, 300);
		});

		$('#hfilter').keyup(function(data) {
			hostMeTimer && clearTimeout(hostMeTimer);
			hostMeTimer = setTimeout(getHostData, 300);
		});
		</script>
		<?php 
    }
}
示例#27
0
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
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');
}
示例#29
0
function graphs()
{
    global $item_rows;
    /* ================= input validation ================= */
    input_validate_input_number(get_request_var_request('host_id'));
    input_validate_input_number(get_request_var_request('graph_type'));
    input_validate_input_number(get_request_var_request('rows'));
    /* ==================================================== */
    /* clean up search string */
    if (isset($_REQUEST['filter'])) {
        $_REQUEST['filter'] = sanitize_search_string(get_request_var_request('filter'));
    }
    /* if the user pushed the 'clear' button */
    if (isset($_REQUEST['clear_x'])) {
        kill_session_var('sess_graphs_new_filter');
        kill_session_var('sess_default_rows');
        unset($_REQUEST['filter']);
        unset($_REQUEST['rows']);
        $changed = true;
    } else {
        /* if any of the settings changed, reset the page number */
        $changed = false;
        $changed += check_changed('host_id', 'sess_graphs_new_host_id');
        $changed += check_changed('graph_type', 'sess_graphs_new_graph_type');
        $changed += check_changed('filter', 'sess_graphs_new_filter');
        $changed += check_changed('rows', 'sess_default_rows');
    }
    load_current_session_value('host_id', 'sess_graphs_new_host_id', db_fetch_cell('SELECT id FROM host ORDER BY description, hostname LIMIT 1'));
    load_current_session_value('graph_type', 'sess_graphs_new_graph_type', read_config_option('default_graphs_new_dropdown'));
    load_current_session_value('filter', 'sess_graphs_new_filter', '');
    load_current_session_value('rows', 'sess_default_rows', read_config_option('num_rows_table'));
    if (!empty($_REQUEST['host_id'])) {
        $host = db_fetch_row_prepared('SELECT id, description, hostname, host_template_id FROM host WHERE id = ?', array($_REQUEST['host_id']));
        $header = ' [ ' . htmlspecialchars($host['description']) . ' (' . htmlspecialchars($host['hostname']) . ') ' . (!empty($host['host_template_id']) ? htmlspecialchars(db_fetch_cell_prepared('SELECT name FROM host_template WHERE id = ?', array($host['host_template_id']))) : '') . ' ]';
    } else {
        $host = array();
        $header = 'None Host Type';
    }
    $row_limit = get_request_var_request('rows');
    html_start_box("<strong>New Graphs for</strong> {$header}", '100%', '', '3', 'center', '');
    form_alternate_row();
    print '<td class="even">';
    ?>
	<script type='text/javascript'>
	<!--

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

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

	<?php 
    html_end_box();
    ?>

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