__('Delete'),
2 => __('Enable'),
3 => __('Disable'),
4 => __('Change Device Settings'),
5 => __('Clear Statistics'),
6 => __('Apply Automation Rules'),
7 => __('Sync to Device Template')
];
$reports = db_fetch_cell_prepared('SELECT COUNT(*)
FROM reports
WHERE user_id = ?
ORDER BY name',
[$_SESSION[SESS_USER_ID]]
);
if ($reports > 0) {
$actions += [
8 => __('Place Device on Report')
];
}
$actions = api_plugin_hook_function('device_action_array', $actions);
// set default action
set_default_action();
api_plugin_hook('device_top');
if (in_array(grv('action'), [
'reindex', 'gt_add', 'query_add',
'query_change', 'query_reload', 'query_verbose',
'enable_debug', 'disable_debug', 'repopulate',
], true)) {
csrf_require_post();
}
switch (grv('action')) {
case 'export':
host_export();
break;
case 'save':
form_save();
break;
case 'reindex':
host_reindex();
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'actions':
form_actions();
break;
case 'gt_add':
gfrv('host_id');
host_add_gt();
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'gt_remove':
gfrv('host_id');
host_remove_gt();
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'query_add':
gfrv('host_id');
host_add_query();
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'query_remove':
gfrv('host_id');
host_remove_query();
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'query_change':
gfrv('host_id');
host_change_query();
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'query_reload':
gfrv('host_id');
host_reload_query();
raise_message('query_reloaded', __('Data Query Re-indexed.'), MESSAGE_LEVEL_INFO);
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'query_verbose':
gfrv('host_id');
host_reload_query();
raise_message('query_reloaded', __('Device Data Query Re-indexed. Verbose output displayed.'), MESSAGE_LEVEL_INFO);
header('Location: host.php?action=edit&id=' . grv('host_id') . '&display_dq_details=true');
break;
case 'edit':
top_header();
host_edit();
bottom_footer();
break;
case 'ping_host':
$host_id = gfrv('id');
api_device_ping_device($host_id);
break;
case 'enable_debug':
enable_device_debug(gfrv('host_id'));
raise_message('enable_debug', __('Device Debugging Enabled for Device.'), MESSAGE_LEVEL_INFO);
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'disable_debug':
disable_device_debug(gfrv('host_id'));
raise_message('disable_debug', __('Device Debugging Disabled for Device.'), MESSAGE_LEVEL_INFO);
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'repopulate':
if (gfrv('host_id') > 0) {
push_out_host(grv('host_id'));
raise_message('repopulate_message', __('Poller Cache for Device Refreshed.'), MESSAGE_LEVEL_INFO);
} else {
raise_message('repopulate_error', __('ERROR: Invalid Device ID.'), MESSAGE_LEVEL_ERROR);
}
header('Location: host.php?action=edit&id=' . grv('host_id'));
break;
case 'ajax_locations':
get_site_locations();
break;
default:
top_header();
host();
bottom_footer();
break;
}
function host_reindex() : void {
$start = microtime(true);
$host_id = gfrv('host_id');
shell_exec(cacti_escapeshellcmd((string) read_config_option('path_php_binary')) . ' -q ' . cacti_escapeshellarg(CACTI_PATH_CLI . '/poller_reindex_hosts.php') . ' --qid=all --id=' . $host_id);
$end = microtime(true);
$total_time = $end - $start;
$items = db_fetch_cell_prepared('SELECT COUNT(*)
FROM host_snmp_cache
WHERE host_id = ?',
[$host_id]
);
raise_message('host_reindex', __esc('Device Reindex Completed in %0.2f seconds. There were %d items updated.', $total_time, $items), MESSAGE_LEVEL_INFO);
}
function add_tree_names_to_actions_array() : void {
global $actions;
// add a list of tree names to the actions dropdown
$trees = db_fetch_assoc('SELECT id, name FROM graph_tree ORDER BY name');
if (cacti_sizeof($trees)) {
foreach ($trees as $tree) {
$actions['tr_' . $tree['id']] = __esc('Place on a Tree (%s)', $tree['name']);
}
}
}
function get_site_locations() : void {
$return = [];
$term = gnrv('term');
$host_id = $_SESSION['cur_device_id'];
$sql_params = ["%$term%"];
$sql_where = '';
if (read_config_option('site_location_filter') && $_SESSION['cur_device_id']) {
$site_id = db_fetch_cell_prepared('SELECT site_id
FROM host
WHERE id = ?',
[$host_id]);
$sql_params[] = $site_id;
$sql_where = 'AND site_id = ?';
}
$locations = db_fetch_assoc_prepared("SELECT DISTINCT location
FROM host
WHERE location LIKE ?
AND location != ''
AND location IS NOT NULL
$sql_where
ORDER BY location",
$sql_params);
if (cacti_sizeof($locations)) {
foreach ($locations as $l) {
$return[] = ['label' => $l['location'], 'value' => $l['location'], 'id' => $l['location']];
}
}
if (!cacti_sizeof($return)) {
$return[] = ['label' => __('None'), 'value' => '', 'id' => __('None')];
}
print json_encode($return);
}
function form_save() : void {
if (isrv('save_component_host')) {
if (gnrv('snmp_version') == 3 && (gnrv('snmp_password') != gnrv('snmp_password_confirm'))) {
raise_message(14);
} elseif (gnrv('snmp_version') == 3 && (gnrv('snmp_priv_passphrase') != gnrv('snmp_priv_passphrase_confirm'))) {
raise_message(13);
} else {
gfrv('id');
gfrv('host_template_id');
$host_id = api_device_save(
gnrv('id'),
gnrv('host_template_id'),
gnrv('description'),
trim(gnrv('hostname')),
gnrv('snmp_community'),
gnrv('snmp_version'),
gnrv('snmp_username'),
gnrv('snmp_password'),
gnrv('snmp_port'),
gnrv('snmp_timeout'),
(isrv('disabled') ? gnrv('disabled') : ''),
gnrv('availability_method'),
gnrv('ping_method'),
gnrv('ping_port'),
gnrv('ping_timeout'),
gnrv('ping_retries'),
gnrv('notes'),
gnrv('snmp_auth_protocol'),
gnrv('snmp_priv_passphrase'),
gnrv('snmp_priv_protocol'),
gnrv('snmp_context'),
gnrv('snmp_engine_id'),
gnrv('max_oids'),
gnrv('device_threads'),
gnrv('poller_id'),
gnrv('site_id'),
gnrv('external_id'),
gnrv('location'),
gnrv('bulk_walk_size'),
gnrv('snmp_options'),
gnrv('snmp_retries')
);
if ($host_id > 0) {
api_plugin_hook_function('host_save', ['host_id' => $host_id]);
}
}
header('Location: host.php?action=edit&id=' . (empty($host_id) ? gnrv('id') : $host_id));
}
}
function form_actions() : void {
global $actions, $device_change_fields, $fields_host_edit;
global $alignment, $graph_timespans;
// ================= input validation =================
gfrv('drp_action', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^([a-zA-Z0-9_]+)$/']]);
// ====================================================
// if we are to save this form, instead of display it
if (isrv('selected_items')) {
$selected_items = sanitize_unserialize_selected_items(gnrv('selected_items'));
if ($selected_items != false) {
if (grv('drp_action') == '2') { // Enable Selected Devices
api_device_enable_devices($selected_items);
} elseif (grv('drp_action') == '3') { // Disable Selected Devices
api_device_disable_devices($selected_items);
} elseif (grv('drp_action') == '4') { // change device options
ini_set('max_execution_time', '-1');
api_device_change_options($selected_items, $_POST);
} elseif (grv('drp_action') == '5') { // Clear Statistics for Selected Devices
api_device_clear_statistics($selected_items);
} elseif (grv('drp_action') == '7') { // sync to device template
ini_set('max_execution_time', '-1');
api_device_sync_device_templates($selected_items);
} elseif (grv('drp_action') == '8') { // place device on report
if (!reports_add_devices(gfrv('report_id'), $selected_items, gfrv('timespan'), gfrv('align'))) {
$name = db_fetch_cell_prepared('SELECT name
FROM reports
WHERE id = ?',
[grv('report_id')]
);
raise_message('reports_add_error', __esc('Unable to add some Devices to Report \'%s\'', $name), MESSAGE_LEVEL_WARN);
}
} elseif (grv('drp_action') == '1') { // delete
ini_set('max_execution_time', '-1');
if (!isrv('delete_type')) {
srv('delete_type', 2);
}
api_device_remove_multi($selected_items, gfrv('delete_type'));
} elseif (preg_match('/^tr_([0-9]+)$/', grv('drp_action'), $matches)) { // place on tree
gfrv('tree_id');
gfrv('tree_item_id');
foreach ($selected_items as $selected_item) {
api_tree_item_save(0, gnrv('tree_id'), TREE_ITEM_TYPE_HOST, gnrv('tree_item_id'), '', 0, $selected_item, 0, 1, 1, false);
}
} elseif (grv('drp_action') == 6) { // automation
automation_log(__FUNCTION__ . ' called, action: ' . grv('drp_action'), AUTOMATION_LOG_HIGH);
automation_log(__FUNCTION__ . ', items: ' . gnrv('selected_items'), AUTOMATION_LOG_HIGH);
// work on all selected hosts
foreach ($selected_items as $host_id) {
automation_update_device($host_id);
}
} else {
api_plugin_hook_function('device_action_execute', gnrv('drp_action'));
}
}
// update snmpcache
snmpagent_device_action_bottom([gnrv('drp_action'), $selected_items]);
api_plugin_hook_function('device_action_bottom', [gnrv('drp_action'), $selected_items]);
header('Location: host.php');
exit;
} else {
$ilist = '';
$iarray = [];
$footer = '';
$reports = [];
add_tree_names_to_actions_array();
// loop through each of the host templates selected on the previous page and get more info about them
foreach ($_POST as $var => $val) {
if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) {
// ================= input validation =================
input_validate_input_number($matches[1], 'chk[1]');
// ====================================================
$ilist .= '
' . htmle(db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', [$matches[1]])) . '
';
$iarray[] = $matches[1];
}
}
if (gnrv('drp_action') == '4') { // Change Device options
$form_array = [];
foreach ($fields_host_edit as $field_name => $field_array) {
if (api_device_change_field_match($field_name)) {
$form_array += [$field_name => $fields_host_edit[$field_name]];
$form_array[$field_name]['value'] = '';
if (read_config_option('hide_form_description') == 'on') {
$form_array[$field_name]['description'] = '';
}
$form_array[$field_name]['form_id'] = 0;
$form_array[$field_name]['sub_checkbox'] = [
'name' => 't_' . $field_name,
'friendly_name' => __('Update this Field'),
'class' => 'ui-state-disabled',
'value' => ''
];
}
}
ob_start();
draw_edit_form(
[
'config' => ['no_form_tag' => true],
'fields' => $form_array
]
);
device_change_javascript();
device_javascript();
$footer = ob_get_clean();
} elseif (grv('drp_action') == '8') { // Place on Report
$reports = db_fetch_assoc_prepared('SELECT id, name
FROM reports
WHERE user_id = ?
ORDER BY name',
[$_SESSION[SESS_USER_ID]]
);
if (cacti_sizeof($reports)) {
$reports = array_rekey($reports, 'id', 'name');
}
}
$form_data = [
'general' => [
'page' => 'host.php',
'actions' => $actions,
'optvar' => 'drp_action',
'item_array' => $iarray,
'item_list' => $ilist
],
'options' => [
1 => [
'smessage' => __('Click \'Continue\' to Delete the following Device.'),
'pmessage' => __('Click \'Continue\' to Delete the following Devices.'),
'scont' => __('Delete Device'),
'pcont' => __('Delete Devices'),
'extra' => [
'delete_type' => [
'method' => 'radio',
'title' => __('Delete Method'),
'default' => 2,
'items' => [
'1' => [
'radio_value' => 2,
'radio_caption' => __('Leave all Graph(s) and Data Source(s) untouched. Data Source(s) will be disabled.')
],
'2' => [
'radio_value' => 2,
'radio_caption' => __('Delete all associated Graph(s) and Data Source(s).')
]
]
]
]
],
2 => [
'smessage' => __('Click \'Continue\' to Enable the following Device.'),
'pmessage' => __('Click \'Continue\' to Enable the following Devices.'),
'scont' => __('Enable Device'),
'pcont' => __('Enable Devices')
],
3 => [
'smessage' => __('Click \'Continue\' to Disable the following Device.'),
'pmessage' => __('Click \'Continue\' to Disable the following Devices.'),
'scont' => __('Disable Device'),
'pcont' => __('Disable Devices')
],
4 => [
'smessage' => __('Click \'Continue\' to Change settings for the following Device.'),
'pmessage' => __('Click \'Continue\' to Change settings for the following Devices.'),
'scont' => __('Change Device'),
'pcont' => __('Change Devices'),
'footer' => $footer,
],
5 => [
'smessage' => __('Click \'Continue\' to Clear Statistics the following Device.'),
'pmessage' => __('Click \'Continue\' to Clear Statistics the following Devices.'),
'scont' => __('Clear Statistics for Device'),
'pcont' => __('Clear Statistics for Devices')
],
7 => [
'smessage' => __('Click \'Continue\' to Synchronize Device to its Device Template.'),
'pmessage' => __('Click \'Continue\' to Synchronize Devices to their Device Templates.'),
'scont' => __('Synchronize Device Template'),
'pcont' => __('Synchronize Devices Templates')
],
8 => [
'smessage' => __('Click \'Continue\' to Place the following Device on a Report.'),
'pmessage' => __('Click \'Continue\' to Place the following Devices on a Report.'),
'scont' => __('Place Device on Report'),
'pcont' => __('Place Devices on Report'),
'extra' => [
'report_id' => [
'method' => 'drop_array',
'title' => __('Report Name'),
'array' => $reports,
'default' => array_key_first($reports)
],
'timespan' => [
'method' => 'drop_array',
'title' => __('Timespan'),
'array' => $graph_timespans,
'default' => read_user_setting('default_timespan')
],
'align' => [
'method' => 'drop_array',
'title' => __('Align'),
'array' => $alignment,
'default' => REPORTS_ALIGN_CENTER
]
]
],
]
];
$trees = db_fetch_assoc('SELECT id, name FROM graph_tree ORDER BY name');
if (cacti_sizeof($trees)) {
foreach ($trees as $tree) {
$branches = db_fetch_assoc_prepared('SELECT id, title
FROM graph_tree_items
WHERE graph_tree_id = ?
AND host_id = 0
AND local_graph_id = 0
AND parent = 0
ORDER BY parent, position',
[$tree['id']]);
if (cacti_sizeof($branches)) {
$branches = array_rekey($branches, 'id', 'title');
} else {
$branches[0] = '[root]';
}
$form_data['options']['tr_' . $tree['id']] = [
'smessage' => __esc('Click \'Continue\' to Place the following Device on Tree %s.', $tree['name']),
'pmessage' => __esc('Click \'Continue\' to Place the following Devices on Tree %s.', $tree['name']),
'scont' => __('Place Device on Tree'),
'pcont' => __('Place Devices on Tree'),
'extra' => [
'tree_item_id' => [
'method' => 'drop_array',
'title' => __('Destination Branch'),
'array' => $branches,
'default' => array_key_first($branches),
]
],
'eaction' => 'tree_id',
'eactionid' => $tree['id'],
];
}
}
// Legacy support for old version plugins
if (!isset($form_data['options'][grv('drp_action')])) {
$save['drp_action'] = grv('drp_action');
$save['host_list'] = $ilist;
$save['host_array'] = $iarray;
} else {
$save = [];
}
$form_data = api_plugin_hook_function('device_confirmation_form', $form_data);
form_continue_confirmation($form_data, 'device_action_prepare', $save);
}
}
function host_export() : void {
draw_hosts_filter(false);
$total_rows = 0;
$hosts = get_device_records($total_rows, 9999999);
$stdout = fopen('php://output', 'w');
header('Content-type: application/excel');
header('Content-Disposition: attachment; filename=cacti-devices-' . time() . '.csv');
if (cacti_sizeof($hosts)) {
$columns = array_keys($hosts[0]);
is_resource($stdout) && fputcsv($stdout, $columns);
foreach ($hosts as $h) {
// Flatten embedded newlines as the previous export format did, then
// prefix any leading character that a spreadsheet would treat as a
// formula so device data round-trips as literal text.
foreach (array_keys($h) as $hc) {
$v = str_replace(["\n", "\r"], ' ', (string) $h[$hc]);
if (cacti_csv_needs_formula_guard($v)) {
$v = "'" . $v;
}
$h[$hc] = $v;
}
is_resource($stdout) && fputcsv($stdout, $h);
}
}
is_resource($stdout) && fclose($stdout);
}
function host_add_query() : void {
// ================= input validation =================
gfrv('host_id');
gfrv('snmp_query_id');
gfrv('reindex_method');
// ====================================================
api_device_dq_add(grv('host_id'), grv('snmp_query_id'), grv('reindex_method'));
}
function host_reload_query() : void {
// ================= input validation =================
gfrv('id');
gfrv('host_id');
// ====================================================
run_data_query(grv('host_id'), grv('id'));
}
function host_remove_query() : void {
// ================= input validation =================
gfrv('id');
gfrv('host_id');
// ====================================================
api_device_dq_remove(grv('host_id'), grv('id'));
}
function host_change_query() : void {
// ================= input validation =================
gfrv('data_query_id');
gfrv('host_id');
gfrv('reindex_method');
// ====================================================
api_device_dq_change(grv('host_id'), grv('data_query_id'), grv('reindex_method'));
}
function host_add_gt() : void {
// ================= input validation =================
gfrv('host_id');
gfrv('graph_template_id');
// ====================================================
db_execute_prepared('REPLACE INTO host_graph
(host_id, graph_template_id)
VALUES (?, ?)',
[gnrv('host_id'), gnrv('graph_template_id')]
);
if (grv('host_id') > 0) {
object_cache_get_totals('device_state', grv('host_id'));
}
automation_hook_graph_template(gnrv('host_id'), gnrv('graph_template_id'));
api_plugin_hook_function('add_graph_template_to_host', ['host_id' => gnrv('host_id'), 'graph_template_id' => gnrv('graph_template_id')]);
if (grv('host_id') > 0) {
object_cache_get_totals('device_state', grv('host_id'), true);
object_cache_update_totals('diff');
}
}
function host_remove_gt() : void {
// ================= input validation =================
gfrv('id');
gfrv('host_id');
// ====================================================
api_device_gt_remove(grv('host_id'), grv('id'));
}
function create_host_edit_filter(array $host, string $content = '') : array {
global $item_rows;
$debug = is_device_debug_enabled($host['id']);
$filters = [
'rows' => [
[
'pingdata' => [
'method' => 'content',
'filter' => FILTER_DEFAULT,
'content' => $content,
],
'id' => [
'method' => 'validate',
'filter' => FILTER_VALIDATE_INT,
'default' => '',
],
'host_template_id' => [
'method' => 'validate',
'filter' => FILTER_VALIDATE_INT,
'default' => '0'
]
]
],
];
if ($host['id'] > 0) {
$filters['links'] = [
[
'display' => __('Create New Device'),
'url' => 'host.php?action=edit',
'class' => 'ti ti-plus newDevice'
],
[
'display' => __('Create New Graphs'),
'url' => 'graphs_new.php?reset=true&host_id=' . $host['id'],
'class' => 'ti ti-chart-area newGraph'
],
[
'display' => __('Re-Index Device'),
'url' => 'host.php?action=reindex&host_id=' . $host['id'],
'class' => 'ti ti-refresh reindexDevice'
],
[
'display' => ($debug ? __('Disable Device Debug') : __('Enable Device Debug')),
'url' => 'host.php?action=' . ($debug ? 'disable_debug' : 'enable_debug') . '&host_id=' . $host['id'],
'class' => ($debug ? 'ti ti-bug disableDebug' : 'ti ti-bug enableDebug')
],
[
'display' => __('Repopulate Poller Cache'),
'url' => 'host.php?action=repopulate&host_id=' . $host['id'],
'class' => 'ti ti-hammer repopulateCache'
],
[
'display' => __('View Poller Cache'),
'url' => 'utilities.php?poller_action=-1&action=view_poller_cache&host_id=' . $host['id'] . '&template_id=-1&filter=&rows=-1',
'class' => 'fa-solid fa-list-ul viewCache'
],
[
'display' => __('View Data Source List'),
'url' => 'data_sources.php?reset=true&host_id=' . $host['id'] . '&ds_rows=30&filter=&template_id=-1&method_id=-1&page=1',
'class' => 'ti ti-brand-databricks viewSources'
],
[
'display' => __('View Graphs List'),
'url' => 'graphs.php?reset=true&host_id=' . $host['id'] . '&graph_rows=30&filter=&template_id=-1&page=1',
'class' => 'ti ti-brand-databricks viewGraphs'
],
];
}
// process plugin links
ob_start();
/**
* Prototype - We will convert links into nice glyphs potentially
*
* *
* Auto-create Thresholds
* ';
*/
api_plugin_hook('device_edit_top_links');
$new_links = ob_get_clean();
/**
* Now that we have anchors, let's add them to the
* filter array.
*/
if ($new_links != '') {
$links = new DOMDocument();
$links->loadHTML($new_links);
$anchors = $links->getElementsByTagName('a');
if (cacti_sizeof($anchors)) {
foreach ($anchors as $a) {
$name = $a->textContent;
$href = $a->getAttribute('href');
$filters['links'][] = [
'display' => $name,
'url' => $href,
'class' => 'ti ti-plug'
];
}
}
}
return $filters;
}
function host_edit() : void {
global $fields_host_edit, $reindex_types;
// ================= input validation =================
gfrv('id');
// ====================================================
api_plugin_hook('host_edit_top');
$header_label = __('Device [new]');
$host = [];
if (grv('id') > 0) {
$host = db_fetch_row_prepared('SELECT *
FROM host
WHERE id = ?',
[grv('id')]
);
if (cacti_sizeof($host)) {
$header_label = __esc('Device [edit: %s]', $host['description']);
}
} else {
$host['id'] = 0;
$host['description'] = __('New Device');
}
if (cacti_sizeof($host)) {
$content = "
";
$content .= "
" . __('Contacting Device') . "
";
$content .= '
';
$filters = create_host_edit_filter($host, $content);
$_SESSION['cur_device_id'] = grv('id');
} else {
$content = '';
$filters = create_host_edit_filter($host, $content);
$_SESSION['cur_device_id'] = 0;
}
// create the page filter
$pageFilter = new CactiTableFilter($header_label, 'host.php', 'form_host', 'sess_host_edit', '', '', false);
$pageFilter->set_filter_array($filters);
$pageFilter->render();
form_start('host.php', 'host_form');
html_start_box('', '100%', true, 3, 'center', '');
// preserve the host template id if passed in via a GET variable
if (!ierv('host_template_id')) {
$fields_host_edit['host_template_id']['value'] = gfrv('host_template_id');
}
// drop the legacy MD5/DES SNMPv3 algorithms from the pickers when disabled
$fields_host_edit['snmp_auth_protocol']['array'] = snmp_auth_protocol_options(isset($host['snmp_auth_protocol']) ? $host['snmp_auth_protocol'] : '');
$fields_host_edit['snmp_priv_protocol']['array'] = snmp_priv_protocol_options(isset($host['snmp_priv_protocol']) ? $host['snmp_priv_protocol'] : '');
/* On a new Device the auth/priv defaults come from the global setting, which on
* an upgraded install may still be a legacy MD5/DES value that was just dropped
* from the picker above - leaving the