Files
cacti/data_templates.php
TheWitness 41e6d9e033 security: consolidate verified GHSA fixes for develop (batch 4) (#8145)
* security: consolidate verified GHSA fixes for develop (batch 4)

Develop counterparts of the 1.2.x batch-4 fixes in #8144, re-verified against
current develop HEAD.

- GHSA-4rmr-wvjq-qxc2: include/auth.php Basic Auth and guest branches fall
  through to the per-page realm check instead of returning early.
- GHSA-j67j-wpm4-9g3x: the pre-dispatch update_policy branch in user_admin.php
  and user_group_admin.php requires a CSRF-token POST. The denylist -> allowlist
  redesign is tracked for 1.3 in #8143.
- GHSA-2p3x-f5jm-rg6p: the View-Graphs -> poller RCE chain is broken by the
  realm check (4rmr), the update_policy guard (j67j) and shell-free webhits (x5pw).
- GHSA-x5pw-cg7j-mj4r: scripts/webhits.pl runs wc through a shell-free list-form open.
- GHSA-9737-rqh3-h7fh: names interpolated into raise_message() now use __esc()
  across the UI; URL- and HTML-bearing messages are excluded.
- GHSA-9x9h-2577-9w86: the colordropdown input is built as a node and the label
  is no longer round-tripped through parseHTML (the list item already used
  createTextNode on develop).
- GHSA-h96j-8xhc-2p3w: remote_agent.php authorizes on $_SERVER['REMOTE_ADDR'],
  not get_client_addr(), which honours client-settable proxy headers.

Regression guards under tests/Unit/Security/{Auth,Csrf,Xss,ShellInjection}.
php -l, check-changelog.py and the sink/architectural baselines all pass.

* chore: reference PR #8145 on the batch-4 1.3.0-dev CHANGELOG entries

* security: resolve develop merge - keep id-only xmlerror unescaped (matches #8141 h745 test)

* security(GHSA-j67j): use REQUEST_METHOD POST guard instead of raw \ (hardening-pattern-guard)

* security(GHSA-9737): fix review findings - drop double-encoding in __esc, escape missed name sinks, correct plugins format-arg count
2026-10-02 13:10:42 -04:00

1342 lines
45 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
require('./include/auth.php');
require_once(CACTI_PATH_LIBRARY . '/api_data_source.php');
require_once(CACTI_PATH_LIBRARY . '/api_tree.php');
require_once(CACTI_PATH_LIBRARY . '/html_tree.php');
require_once(CACTI_PATH_LIBRARY . '/poller.php');
require_once(CACTI_PATH_LIBRARY . '/template.php');
require_once(CACTI_PATH_LIBRARY . '/utility.php');
require_once(CACTI_PATH_LIBRARY . '/CactiValidator.php');
use Symfony\Component\Validator\Constraints as Assert;
$actions = [
1 => __('Delete'),
2 => __('Duplicate'),
3 => __('Change Profile')
];
// set default action
set_default_action();
switch (grv('action')) {
case 'save':
form_save();
break;
case 'actions':
form_actions();
break;
case 'rrd_add':
template_rrd_add();
break;
case 'rrd_remove':
template_rrd_remove();
break;
case 'template_edit':
top_header();
template_edit();
bottom_footer();
break;
default:
top_header();
data_templates();
bottom_footer();
break;
}
function form_save() : void {
if (isrv('save_component_template')) {
// ================= input validation =================
gfrv('data_input_id');
gfrv('data_template_id');
gfrv('data_template_data_id');
gfrv('data_template_rrd_id');
gfrv('data_source_type_id');
gfrv('data_source_profile_id');
gfrv('rrd_heartbeat');
// ====================================================
// save: data_template
$save1['id'] = grv('data_template_id');
$save1['hash'] = get_hash_data_template(grv('data_template_id'));
$save1['name'] = CactiValidator::validateInput(gnrv('template_name'), 'template_name', [new Assert\NotBlank()], 3);
// save: data_template_data
$save2['id'] = grv('data_template_data_id');
$save2['local_data_template_data_id'] = 0;
$save2['local_data_id'] = 0;
$save2['data_input_id'] = CactiValidator::validateInput(grv('data_input_id'), 'data_input_id', [new Assert\Regex('/^[0-9]+$/')], 3);
$save2['t_name'] = CactiValidator::validateInput((isrv('t_name') ? gnrv('t_name') : ''), 't_name', [], 3);
$save2['name'] = CactiValidator::validateInput(gnrv('name'), 'name', (isrv('t_name') ? [] : [new Assert\NotBlank()]), 3);
$save2['t_active'] = CactiValidator::validateInput((isrv('t_active') ? gnrv('t_active') : ''), 't_active', [], 3);
$save2['active'] = CactiValidator::validateInput((isrv('active') ? gnrv('active') : ''), 'active', [], 3);
$rrd_step = db_fetch_cell_prepared('SELECT step
FROM data_source_profiles
WHERE id = ?',
[grv('data_source_profile_id')]);
$rrd_heartbeat = db_fetch_cell_prepared('SELECT heartbeat
FROM data_source_profiles
WHERE id = ?',
[grv('data_source_profile_id')]);
$save2['rrd_step'] = $rrd_step;
$save2['t_data_source_profile_id'] = CactiValidator::validateInput((isrv('t_data_source_profile_id') ? gnrv('t_data_source_profile_id') : ''), 't_data_source_profile_id', [], 3);
$save2['data_source_profile_id'] = CactiValidator::validateInput(grv('data_source_profile_id'), 'data_source_profile_id', [new Assert\Regex('/^[0-9]+$/')], 3);
// save: data_template_rrd
$save3['id'] = grv('data_template_rrd_id');
$save3['hash'] = get_hash_data_template(grv('data_template_rrd_id'), 'data_template_item');
$save3['local_data_template_rrd_id'] = 0;
$save3['local_data_id'] = 0;
$save3['t_rrd_maximum'] = CactiValidator::validateInput((isrv('t_rrd_maximum') ? gnrv('t_rrd_maximum') : ''), 't_rrd_maximum', [], 3);
$save3['rrd_maximum'] = CactiValidator::validateInput(gnrv('rrd_maximum'), 'rrd_maximum', [new Assert\Regex('/^(-?([0-9]+(\.[0-9]*)?|[0-9]*\.[0-9]+)([eE][+\-]?[0-9]+)?|U|\|query_ifSpeed\|)\z/')], 3);
$save3['t_rrd_minimum'] = CactiValidator::validateInput((isrv('t_rrd_minimum') ? gnrv('t_rrd_minimum') : ''), 't_rrd_minimum', [], 3);
$save3['rrd_minimum'] = CactiValidator::validateInput(gnrv('rrd_minimum'), 'rrd_minimum', [new Assert\Regex('/^(-?([0-9]+(\.[0-9]*)?|[0-9]*\.[0-9]+)([eE][+\-]?[0-9]+)?|U)\z/')], 3);
$save3['rrd_heartbeat'] = $rrd_heartbeat;
$save3['t_data_source_type_id'] = CactiValidator::validateInput((isrv('t_data_source_type_id') ? gnrv('t_data_source_type_id') : ''), 't_data_source_type_id', [], 3);
$save3['data_source_type_id'] = CactiValidator::validateInput(grv('data_source_type_id'), 'data_source_type_id', [new Assert\Regex('/^[0-9]+$/')], 3);
$save3['t_data_source_name'] = CactiValidator::validateInput((isrv('t_data_source_name') ? gnrv('t_data_source_name') : ''), 't_data_source_name', [], 3);
$save3['data_source_name'] = CactiValidator::validateInput(gnrv('data_source_name'), 'data_source_name', [new Assert\Regex('/^[a-zA-Z0-9_]{1,19}$/')], 3);
$save3['t_data_input_field_id'] = CactiValidator::validateInput((isrv('t_data_input_field_id') ? gnrv('t_data_input_field_id') : ''), 't_data_input_field_id', [], 3);
$save3['data_input_field_id'] = CactiValidator::validateInput((isrv('data_input_field_id') ? gnrv('data_input_field_id') : '0'), 'data_input_field_id', [], 3);
if ($save3['rrd_minimum'] != 'U' && $save3['rrd_maximum'] != 'U') {
if ($save3['rrd_minimum'] >= $save3['rrd_maximum']) {
raise_message(43);
$_SESSION[SESS_ERROR_FIELDS]['rrd_maximum'] = 'rrd_maximum';
$data_template_id_param = grv('data_template_id');
$view_rrd_param = '';
if (!ierv('current_rrd')) {
$current_rrd = gnrv('current_rrd') ? gnrv('current_rrd') : grv('data_template_rrd_id');
$view_rrd_param = '&view_rrd=' . $current_rrd;
}
$location = 'data_templates.php?action=template_edit&id=' . $data_template_id_param . $view_rrd_param;
header('Location: ' . $location);
exit;
}
}
// ok, first pull out all 'input' values so we know how much to save
$input_fields = db_fetch_assoc_prepared("SELECT id, input_output, regexp_match,
allow_nulls, type_code, data_name
FROM data_input_fields
WHERE data_input_id = ?
AND input_output = 'in'",
[grv('data_input_id')]);
// pass 1 for validation
if (cacti_sizeof($input_fields)) {
foreach ($input_fields as $input_field) {
$form_value = 'value_' . $input_field['data_name'];
if ((isrv($form_value)) && ($input_field['type_code'] == '')) {
if ((isrv('t_' . $form_value)) &&
(gnrv('t_' . $form_value) == 'on')) {
$not_required = true;
} elseif ($input_field['allow_nulls'] == 'on') {
$not_required = true;
} else {
$not_required = false;
}
$constraints = [];
if (!$not_required) {
$constraints[] = new Assert\NotBlank();
}
if (!empty($input_field['regexp_match'])) {
$constraints[] = new Assert\Regex('/' . $input_field['regexp_match'] . '/');
}
CactiValidator::validateInput(gnrv($form_value), 'value_' . $input_field['data_name'], $constraints, 3);
}
}
}
if (!is_error_message()) {
$save1['last_updated'] = date('Y-m-d H:i:s');
$data_template_id = sql_save($save1, 'data_template');
if ($data_template_id) {
raise_message(1);
} else {
raise_message(2);
}
}
if (!is_error_message()) {
$save2['data_template_id'] = $data_template_id;
$data_template_data_id = sql_save($save2, 'data_template_data');
if ($data_template_data_id) {
raise_message(1);
} else {
raise_message(2);
}
}
// update actual host template information for live hosts
if ((!is_error_message()) && ($save2['id'] > 0)) {
db_execute_prepared('UPDATE data_template_data
SET data_input_id = ?
WHERE data_template_id = ?',
[grv('data_input_id'), $data_template_id]);
db_execute_prepared('UPDATE data_template_rrd
SET rrd_heartbeat = ?
WHERE data_template_id = ?
AND local_data_id = 0',
[$rrd_heartbeat, $data_template_id]);
}
if (!is_error_message()) {
$save3['data_template_id'] = $data_template_id;
$data_template_rrd_id = sql_save($save3, 'data_template_rrd');
if ($data_template_rrd_id) {
raise_message(1);
} else {
raise_message(2);
}
} else {
$data_template_rrd_id = 0;
}
if (!is_error_message()) {
// Lets make sure we don't have any fields not set
$data_template_fields = db_fetch_assoc_prepared('SELECT
dt.id, dt.name, dtd.name, di.hash, di.name, di.type_id,
dtr.id dtr_id, dtr.data_source_name, dif.id dif_id, dif.name, dif.data_name,
dif.input_output, dif.update_rra
FROM data_template dt
INNER JOIN data_template_data dtd
ON dt.id = dtd.data_template_id
INNER JOIN data_input di
ON dtd.data_input_id = di.id
INNER JOIN data_template_rrd dtr
ON dt.id = dtr.data_template_id
LEFT OUTER JOIN data_input_fields dif
ON dtr.data_input_field_id = dif.id
WHERE di.type_id in (1,5) AND dt.id = ? AND dif.id IS NULL',
[$data_template_id]);
if (cacti_sizeof($data_template_fields)) {
foreach ($data_template_fields as $data_template_field) {
raise_message('data_template_rrd_' . $data_template_field['dtr_id'], __esc('Field "%s" is missing an Output Field. Select the Output Field associated with this Data Source, and press Save again.', $data_template_field['data_source_name']), MESSAGE_LEVEL_WARN);
}
}
}
if (!is_error_message()) {
if (!ierv('data_template_id')) {
// push out all data source settings to child data source using this template
push_out_data_source($data_template_data_id);
push_out_data_source_item($data_template_rrd_id);
db_execute_prepared('DELETE
FROM data_input_data
WHERE data_template_data_id = ?',
[$data_template_data_id]);
if (cacti_sizeof($input_fields)) {
foreach ($input_fields as $input_field) {
$form_value = 'value_' . $input_field['data_name'];
if (isrv($form_value)) {
// save the data into the 'host_template_data' table
if (isrv('t_value_' . $input_field['data_name'])) {
$template_this_item = 'on';
} else {
$template_this_item = '';
}
if (!ierv('t_value_' . $input_field['data_name'])) {
/* unusual case where a form value comes back as an array
* this should be cleaned up in the database repair script. */
$value = gnrv($form_value);
if (is_array($value)) {
$value = trim($value[0]);
} else {
$value = trim($value);
}
db_execute_prepared('INSERT INTO data_input_data
(data_input_field_id, data_template_data_id, data_template_id, local_data_id, host_id, t_value, value)
VALUES (?, ?, ?, ?, ?, ?, ?)',
[
$input_field['id'],
$data_template_data_id,
$data_template_id,
0,
0,
$template_this_item,
$value
]
);
}
}
}
}
// push out all "custom data" for this data source template
push_out_data_source_custom_data($data_template_id);
// push out the hosts that use the data template
$hosts = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT host_id
FROM data_local
WHERE data_template_id = ?',
[$data_template_id]),
'host_id', 'host_id'
);
if (cacti_sizeof($hosts)) {
foreach ($hosts as $host_id) {
push_out_host($host_id, 0, $data_template_id);
}
}
/**
* push out field mappings for the data collector
* its important to delete first due to the possibility that
* the field names were changed
*/
db_execute_prepared('DELETE FROM poller_data_template_field_mappings
WHERE data_template_id = ?',
[$data_template_id]);
db_execute_prepared('REPLACE INTO poller_data_template_field_mappings
SELECT dtr.data_template_id, dif.data_name,
GROUP_CONCAT(DISTINCT dtr.data_source_name ORDER BY dtr.data_source_name) AS data_source_names,
NOW() AS last_updated
FROM graph_templates_item AS gti
INNER JOIN data_template_rrd AS dtr
ON gti.task_item_id = dtr.id
INNER JOIN data_input_fields AS dif
ON dtr.data_input_field_id = dif.id
WHERE dtr.local_data_id = 0
AND gti.local_graph_id = 0
AND dtr.data_template_id = ?
GROUP BY dtr.data_template_id, dif.data_name',
[$data_template_id]);
}
}
header('Location: data_templates.php?action=template_edit&id=' . (empty($data_template_id) ? grv('data_template_id') : $data_template_id) . (ierv('current_rrd') ? '' : '&view_rrd=' . (gnrv('current_rrd') ? gnrv('current_rrd') : $data_template_rrd_id)));
}
}
function form_actions() : void {
global $actions;
// ================= 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 (gnrv('drp_action') == '1') { // delete
$data_template_data_ids = db_fetch_cell('SELECT GROUP_CONCAT(id)
FROM data_template_data
WHERE ' . array_to_sql_or($selected_items, 'data_template_id') . '
AND local_data_id=0');
db_execute('DELETE FROM data_template_data WHERE ' . array_to_sql_or($selected_items, 'data_template_id') . ' AND local_data_id=0');
db_execute('DELETE FROM data_template_rrd WHERE ' . array_to_sql_or($selected_items, 'data_template_id') . ' AND local_data_id=0');
db_execute('DELETE FROM snmp_query_graph_rrd WHERE ' . array_to_sql_or($selected_items, 'data_template_id'));
db_execute('DELETE FROM snmp_query_graph_rrd_sv WHERE ' . array_to_sql_or($selected_items, 'data_template_id'));
db_execute('DELETE FROM data_template WHERE ' . array_to_sql_or($selected_items, 'id'));
// "undo" any graph that is currently using this template
db_execute('UPDATE data_template_data
SET local_data_template_data_id = 0, data_template_id = 0
WHERE ' . array_to_sql_or($selected_items, 'data_template_id'));
db_execute('UPDATE data_template_rrd
SET local_data_template_rrd_id = 0, data_template_id = 0
WHERE ' . array_to_sql_or($selected_items, 'data_template_id'));
db_execute('UPDATE data_local
SET data_template_id = 0
WHERE ' . array_to_sql_or($selected_items, 'data_template_id'));
// delete data_input_data information
if ($data_template_data_ids != '') {
db_execute('DELETE FROM data_input_data WHERE data_template_data_id IN(' . $data_template_data_ids . ')');
}
} elseif (gnrv('drp_action') == '2') { // duplicate
for ($i = 0; ($i < cacti_count($selected_items)); $i++) {
api_data_source_duplicate(0, $selected_items[$i], gnrv('title_format'));
}
} elseif (gnrv('drp_action') == '3') { // change data source profile
$step = db_fetch_cell_prepared('SELECT step
FROM data_source_profiles
WHERE id = ?',
[gfrv('data_source_profile_id')]);
$heartbeat = db_fetch_cell_prepared('SELECT heartbeat
FROM data_source_profiles
WHERE id = ?',
[gfrv('data_source_profile_id')]);
if (!empty($step)) {
for ($i = 0; ($i < cacti_count($selected_items)); $i++) {
$push_out = false;
if (isrv('update_data_sources') && gnrv('update_data_sources') == 'on') {
$sql_where = ' AND local_data_id >= 0';
$push_out = true;
} else {
$sql_where = ' AND local_data_id = 0';
}
db_execute_prepared("UPDATE data_template_data
SET data_source_profile_id = ?,
rrd_step = ?
WHERE data_template_id = ?
$sql_where",
[gfrv('data_source_profile_id'), $step, $selected_items[$i]]);
db_execute_prepared("UPDATE data_template_rrd
SET rrd_heartbeat = ?
WHERE data_template_id = ?
$sql_where",
[$heartbeat, $selected_items[$i]]);
if ($push_out) {
$php_binary = read_config_option('path_php_binary');
exec_background($php_binary, CACTI_PATH_CLI . '/rebuild_poller_cache.php --data-template-id=' . $selected_items[$i]);
raise_message('repopulate_' . $i, __esc('The Poller Cache operation has been launched in background for Data Template ID %d.', $selected_items[$i]), MESSAGE_LEVEL_INFO);
}
}
}
}
}
header('Location: data_templates.php');
exit;
} else {
$ilist = '';
$iarray = [];
// loop through each of the graphs 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 .= '<li>' . htmle(db_fetch_cell_prepared('SELECT name FROM data_template WHERE id = ?', [$matches[1]])) . '</li>';
$iarray[] = $matches[1];
}
}
$available_profiles = array_rekey(
db_fetch_assoc('SELECT id, name
FROM data_source_profiles
ORDER BY name'),
'id', 'name'
);
$form_data = [
'general' => [
'page' => 'data_templates.php',
'actions' => $actions,
'optvar' => 'drp_action',
'item_array' => $iarray,
'item_list' => $ilist,
],
'options' => [
1 => [
'smessage' => __('Click \'Continue\' to Delete the following Data Template.'),
'pmessage' => __('Click \'Continue\' to Delete following Data Templates.'),
'scont' => __('Delete Data Template'),
'pcont' => __('Delete Data Templates')
],
2 => [
'smessage' => __('Click \'Continue\' to Duplicate the following Data Template.'),
'pmessage' => __('Click \'Continue\' to Duplicate following Data Templates.'),
'scont' => __('Duplicate Data Template'),
'pcont' => __('Duplicate Data Templates'),
'extra' => [
'title_format' => [
'method' => 'textbox',
'title' => __('Title Format'),
'default' => '<template_title> (1)',
'width' => 25
]
]
],
3 => [
'smessage' => __('Click \'Continue\' to Change Profile the following Data Template.'),
'pmessage' => __('Click \'Continue\' to Change Profile following Data Templates.'),
'scont' => __('Change Profile for Data Template'),
'pcont' => __('Change Profile for Data Templates'),
'footer' => __('NOTE: This change will only affect future Data Sources and does not alter existing Data Sources.'),
'extra' => [
'data_source_profile_id' => [
'method' => 'drop_array',
'title' => __('New Data Source Profile'),
'array' => $available_profiles,
'default' => ''
],
'update_data_sources' => [
'method' => 'checkbox',
'title' => __('Update database for existing Data Sources?'),
'description' => __('WARNING: This change will not change either the step or the heartbeat of existing RRDfiles. After this change, a Rebuild Poller Cache operation will take place in background to update the data collection cycle for the impacted Data Sources. It is strongly suggested that you either delete all the impacted RRDfiles afterwards, or use the splice_rrd.php CLI script to preserve old data and repopulate the new RRDfiles with the legacy data. Otherwise, this change will have no on the data and may in fact lead to a loss of fidelity if you are increasing the time between data collection cycles.'),
'default' => ''
]
],
]
]
];
form_continue_confirmation($form_data);
}
}
function template_rrd_remove() : void {
// ================= input validation =================
gfrv('id');
gfrv('data_template_id');
// ====================================================
$children = db_fetch_assoc_prepared('SELECT id
FROM data_template_rrd
WHERE local_data_template_rrd_id = ?
OR id = ?',
[grv('id'), grv('id')]);
if (cacti_sizeof($children)) {
foreach ($children as $item) {
db_execute_prepared('DELETE FROM data_template_rrd WHERE id = ?', [$item['id']]);
db_execute_prepared('DELETE FROM snmp_query_graph_rrd WHERE data_template_rrd_id = ?', [$item['id']]);
db_execute_prepared('UPDATE graph_templates_item SET task_item_id = 0 WHERE task_item_id = ?', [$item['id']]);
}
}
header('Location: data_templates.php?action=template_edit&id=' . grv('data_template_id'));
}
function template_rrd_add() : void {
// ================= input validation =================
gfrv('id');
gfrv('local_data_id');
// ====================================================
$hash = get_hash_data_template(0, 'data_template_item');
// check for duplicated data source name
$i = 0;
$dsname = 'ds';
while (true) {
$exists = db_fetch_cell_prepared('SELECT data_source_name
FROM data_template_rrd
WHERE data_source_name = ?
AND data_template_id = ?',
[$dsname, grv('id')]);
if (empty($exists)) {
break;
} else {
$i++;
$dsname = 'ds (' . $i . ')';
if ($i > 100) {
break;
}
}
}
db_execute_prepared('INSERT IGNORE INTO data_template_rrd
(hash, data_template_id, rrd_maximum, rrd_minimum, rrd_heartbeat, data_source_type_id, data_source_name)
VALUES (?, ?, "U", 0, 600, 1, ?)', [$hash, grv('id'), $dsname]);
$data_template_rrd_id = db_fetch_insert_id();
// add this data template item to each data source using this data template
$children = db_fetch_assoc_prepared('SELECT local_data_id
FROM data_template_data
WHERE data_template_id = ?
AND local_data_id > 0',
[grv('id')]);
if (cacti_sizeof($children)) {
foreach ($children as $item) {
db_execute_prepared('INSERT IGNORE INTO data_template_rrd
(local_data_template_rrd_id, local_data_id, data_template_id, rrd_maximum, rrd_minimum, rrd_heartbeat, data_source_type_id, data_source_name)
VALUES (?, ?, ?, 0, 0, 600, 1, ?)',
[$data_template_rrd_id, $item['local_data_id'], grv('id'), $dsname]);
}
}
header('Location: data_templates.php?action=template_edit&id=' . grv('id') . "&view_rrd=$data_template_rrd_id");
}
function data_template_is_stream(int $data_input_id) : bool {
$id = db_fetch_cell_prepared('SELECT id
FROM data_input
WHERE hash = "7ed649bfa9cd627d7482b7700e88db53"
AND id = ?',
[$data_input_id]);
return !empty($id) ? true : false;
}
function data_template_is_snmp(int $data_input_id) : bool {
$id = db_fetch_cell_prepared('SELECT id
FROM data_input
WHERE hash = "3eb92bb845b9660a7445cf9740726522"
AND id = ?',
[$data_input_id]);
return !empty($id) ? true : false;
}
function template_edit() : void {
global $struct_data_source, $struct_data_source_item, $data_source_types, $fields_data_template_template_edit, $fields_host_edit, $hash_system_data_inputs;
// ================= input validation =================
gfrv('id');
gfrv('view_rrd');
// ====================================================
$isSNMPGet = false;
$isStream = false;
if (!ierv('id')) {
$template_data = db_fetch_row_prepared('SELECT dtd.*, data_sources
FROM (
SELECT COUNT(*) AS data_sources FROM data_local AS dl
LEFT JOIN data_template_data AS idtd ON dl.id=idtd.local_data_id
WHERE idtd.data_template_id = ?
) AS ds
INNER JOIN (
SELECT * FROM data_template_data
WHERE data_template_id = ? AND local_data_id = 0
) AS dtd',
[grv('id'), grv('id')]);
$template = db_fetch_row_prepared('SELECT *
FROM data_template
WHERE id = ?',
[grv('id')]);
if (cacti_sizeof($template_data)) {
$isSNMPGet = data_template_is_snmp($template_data['data_input_id']);
$isStream = data_template_is_stream($template_data['data_input_id']);
}
$header_label = __esc('Data Templates [edit: %s]', $template['name']);
?>
<table style='width:100%'>
<tr>
<td class='textInfo left' style='vertical-align:top;'>
<?php print htmle($template['name']); ?>
</td>
<td class='textInfo right' style='vertical-align:top;'>
<?php
$data_input_id = 0;
if (!empty($template_data['data_input_id'])) {
$data_input_id = get_nonsystem_data_input($template_data['data_input_id']);
if (!isset($data_input_id) || $data_input_id == null) {
$data_input_id = 0;
}
}
if ($data_input_id > 0) {
?><span class='linkMarker'>*</span><a class='hyperLink' href='<?php print htmlspecialchars('data_input.php?action=edit&id=' . $data_input_id); ?>'><?php print __('Edit Data Input Method.'); ?></a><br><?php
}
?>
</td>
</tr>
</table>
<br>
<?php
} else {
$template = [];
$template_data = [];
$template_data_rrds = [];
$data_template_rrd_id = 0;
$header_label = __('Data Templates [new]');
}
form_start('data_templates.php', 'data_templates');
html_start_box($header_label, '100%', true, 3, 'center', '');
draw_edit_form(
[
'config' => ['no_form_tag' => 'true'],
'fields' => inject_form_variables($fields_data_template_template_edit, $template, $template_data, $_REQUEST)
]
);
html_end_box(true, true);
html_start_box(__('Data Source'), '100%', true, 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 = [];
foreach ($struct_data_source as $field_name => $field_array) {
$form_array += [$field_name => $struct_data_source[$field_name]];
if ($form_array[$field_name]['method'] != 'spacer') {
$form_array[$field_name]['value'] = (isset($template_data[$field_name]) ? $template_data[$field_name] : '');
}
$form_array[$field_name]['form_id'] = $template_data['data_template_id'] ?? 0;
if ($field_array['flags'] == 'ALWAYSTEMPLATE') {
$form_array[$field_name]['description'] .= '<br><em>' . __('This field is always templated.') . '</em>';
} else {
$form_array[$field_name]['sub_checkbox'] = [
'name' => 't_' . $field_name,
'friendly_name' => __esc('Check this checkbox if you wish to allow the user to override the value on the right during Data Source creation.'),
'value' => (isset($template_data['t_' . $field_name]) ? $template_data['t_' . $field_name] : ''),
'default' => ''
];
}
}
$form_array['data_source_profile_id']['sql'] = 'SELECT id, name FROM data_source_profiles ORDER BY name';
draw_edit_form(
[
'config' => ['no_form_tag' => true],
'fields' => inject_form_variables($form_array, $template_data)
]
);
html_end_box(true, true);
// fetch ALL rrd's for this data source
if (!ierv('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',
[grv('id')]);
}
// select the first "rrd" of this data source by default
if (ierv('view_rrd')) {
srv('view_rrd', (isset($template_data_rrds[0]['id']) ? $template_data_rrds[0]['id'] : '0'));
}
// get more information about the rrd we chose
if (!ierv('view_rrd')) {
$template_rrd = db_fetch_row_prepared('SELECT *
FROM data_template_rrd
WHERE id = ?',
[grv('view_rrd')]);
}
$i = 0;
if (isset($template_data_rrds)) {
if (cacti_sizeof($template_data_rrds)) {
// draw the data source tabs on the top of the page
print "<div class='tabs' style='float:left;'><nav><ul role='tablist'>";
foreach ($template_data_rrds as $template_data_rrd) {
print "<li class='subTab'><a " . (($template_data_rrd['id'] == grv('view_rrd')) ? "class='pic selected'" : "class='pic'") . " href='" . htmle('data_templates.php?action=template_edit&id=' . grv('id') . '&view_rrd=' . $template_data_rrd['id']) . "'>" . ($i + 1) . ': ' . htmle($template_data_rrd['data_source_name']) . '</a>' . ($template_data['data_sources'] == 0 ? "<a class='pic deleteMarker ti ti-x cactiPostAction' title='" . __esc('Delete') . "' href='#' data-url='" . html_escape_url('data_templates.php?action=rrd_remove&id=' . $template_data_rrd['id'] . '&data_template_id=' . grv('id')) . "'></a>" : "<a class='deleteMarkerDisabled ti ti-x' href='#' title='" . __esc('Data Templates in use can not be modified') . "'></a>") . '</li>';
$i++;
}
print '</ul></nav></div>';
} elseif (cacti_sizeof($template_data_rrds) === 1) {
srv('view_rrd', $template_data_rrds[0]['id']);
}
}
if (grv('id') > 0) {
$readOnly = db_fetch_cell_prepared('SELECT id
FROM data_local
WHERE data_template_id = ?
LIMIT 1',
[grv('id')]);
} else {
$readOnly = false;
}
if (!$isSNMPGet && !$readOnly) {
$add_button = !ierv('id') ? [[
'data_url' => 'data_templates.php?action=rrd_add&id=' . grv('id'),
'title' => __('New')
]] : '';
html_start_box(__('Data Source Item [%s]', (isset($template_rrd) ? htmle($template_rrd['data_source_name']) : '')), '100%', true, 3, 'center', $add_button, __('New'));
} else {
html_start_box(__('Data Source Item [%s]', (isset($template_rrd) ? htmle($template_rrd['data_source_name']) : '')), '100%', true, 3, 'center', '', '');
}
// data input fields list
if (empty($template_data['data_input_id'])) {
unset($struct_data_source_item['data_input_field_id']);
} else {
$input_type = db_fetch_cell_prepared('SELECT type_id
FROM data_input
WHERE id = ?',
[$template_data['data_input_id']]);
if ($input_type != 1 && $input_type != 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 = [];
foreach ($struct_data_source_item as $field_name => $field_array) {
$form_array[$field_name] = $struct_data_source_item[$field_name];
$form_array[$field_name]['value'] = (isset($template_rrd) ? $template_rrd[$field_name] : '');
$form_array[$field_name]['sub_checkbox'] = [
'name' => 't_' . $field_name,
'friendly_name' => __esc('Check this checkbox if you wish to allow the user to override the value on the right during Data Source creation.'),
'value' => (isset($template_rrd['t_' . $field_name]) ? $template_rrd['t_' . $field_name] : ''),
'default' => ''
];
}
draw_edit_form(
[
'config' => ['no_form_tag' => true],
'fields' => $form_array + [
'data_template_rrd_id' => [
'method' => 'hidden',
'value' => (isset($template_rrd) ? $template_rrd['id'] : '0')
]
]
]
);
html_end_box(true, true);
$i = 0;
if (!ierv('id') && !$isStream) {
// get each INPUT field for this data input source
$fields = db_fetch_assoc_prepared('SELECT *
FROM data_input_fields
WHERE data_input_id = ?
AND input_output="in" ORDER BY name',
[$template_data['data_input_id']]);
$name = db_fetch_cell_prepared('SELECT name
FROM data_input
WHERE id = ?',
[$template_data['data_input_id']]);
html_start_box(__('Custom Data [data input: %s]', htmle($name)), '100%', true, 3, 'center', '');
// loop through each field found
if (cacti_sizeof($fields)) {
$class = 'odd';
foreach ($fields as $field) {
$data_input_data = db_fetch_row_prepared('SELECT t_value, value
FROM data_input_data AS did
WHERE data_template_data_id = ?
AND data_input_field_id = ?',
[$template_data['id'], $field['id']]);
// Data Query Key fields
if (data_input_field_always_checked($field['id'])) {
$message = __esc('This value is disabled due to its value being derived from the Device or special Data Query object that keeps track of Data Query associations.');
if (cacti_sizeof($data_input_data)) {
$old_value = $data_input_data['value'] ?? '';
$old_tvalue = 'on';
$disable = 'disable';
} else {
$old_value = '';
$old_tvalue = 'on';
$disable = 'disable';
}
} elseif ($field['type_code'] == 'host_id') {
$message = __esc('This value is disabled due to it being derived from the Device and read only.');
$old_value = $data_input_data['value'] ?? '';
$old_tvalue = '';
$disable = 'disable';
} else {
$message = __esc('Check this checkbox if you wish to allow the user to override the value on the right during Data Source creation.');
if (cacti_sizeof($data_input_data)) {
$old_value = $data_input_data['value'] ?? '';
$old_tvalue = $data_input_data['t_value'] ?? '';
$disable = '';
} else {
$old_value = '';
$old_tvalue = '';
$disable = '';
}
}
if ($field['data_name'] == 'management_ip') {
$help = $fields_host_edit['hostname']['description'];
} elseif (isset($fields_host_edit[$field['data_name']])) {
$help = $fields_host_edit[$field['data_name']]['description'];
} else {
$help = $field['name'];
}
print "<div class='formRow $class'>";
if ($class == 'odd') {
$class = 'even';
} else {
$class = 'odd';
}
if (preg_match('/^' . VALID_HOST_FIELDS . '$/i', $field['type_code']) && $old_tvalue == '') {
$title = __esc('Value will be derived from the Device if this field is left empty.');
} else {
$title = '';
}
?>
<div class='formColumnLeft'>
<div class='formFieldName customDataCheckbox <?php print $disable; ?>'><?php form_checkbox('t_value_' . $field['data_name'], $old_tvalue, '', '', '', grv('id'), '', $message); ?><?php print htmle($field['name']); ?><div class='formTooltip'><?php print display_tooltip($help); ?></div>
</div>
</div>
<div class='formColumnRight <?php print $disable; ?>'>
<?php form_text_box('value_' . $field['data_name'], $old_value, '', '', 30, 'text', 0, '', $title); ?>
</div>
<?php
print '</div>';
$i++;
}
} else {
print '<div style="width:100%;float:left;"><em>' . __('No Input Fields for the Selected Data Input Source') . '</em></div>';
}
html_end_box(true, true);
}
form_save_button('data_templates.php', 'return');
?>
<script type='text/javascript'>
var readOnly = <?php print $readOnly ? 'true' : 'false'; ?>;
$(function() {
if (readOnly) {
// Data Source
$('#data_input_id').prop('disabled', true).addClass('ui-state-disabled');
$('#t_data_input_id').prop('disabled', true).addClass('ui-state-disabled');
if ($('#data_input_id').selectmenu('instance')) {
$('#data_input_id').selectmenu('disable');
}
// Data source attributes
$('#data_source_name').prop('disabled', true).addClass('ui-state-disabled');
$('#t_data_source_name').prop('disabled', true).addClass('ui-state-disabled');
$('#data_source_type_id').prop('disabled', true).addClass('ui-state-disabled');
$('#t_data_source_type_id').prop('disabled', true).addClass('ui-state-disabled');
// Custom Data
$('#value_index_type').prop('disabled', true).addClass('ui-state-disabled');
$('#t_value_index_type').prop('disabled', true).addClass('ui-state-disabled');
$('#value_index_value').prop('disabled', true).addClass('ui-state-disabled');
$('#t_value_index_value').prop('disabled', true).addClass('ui-state-disabled');
$('#value_output_type').prop('disabled', true).addClass('ui-state-disabled');
$('#t_value_output_type').prop('disabled', true).addClass('ui-state-disabled');
if ($('#data_source_type_id').selectmenu('instance')) {
$('#data_source_type_id').selectmenu('disable');
}
}
// Disable Data Query Input Field Changes
$('.disable').find('input').each(function() {
$(this).prop('disabled', true).addClass('ui-stat-disabled');
});
$('.customDataCheckbox').find('input').on('change', function() {
if ($(this).prop('checked') == false) {
raiseMessage(
'<?= __('Custom Data Warning Message'); ?>',
'<?= __esc('WARNING: Data Loss can Occur'); ?>',
'<?= __esc('After you uncheck this checkbox and then Save the Data Template, any existing Data Sources based on this Data Template will lose their Custom Data. This can result in broken Data Collection and Graphs'); ?>',
MESSAGE_LEVEL_MIXED
);
}
});
});
</script>
<?php
}
function data_templates() : void {
global $actions, $item_rows;
draw_data_template_filter(true);
if (grv('rows') == '-1') {
$rows = read_config_option('num_rows_table');
} else {
$rows = grv('rows');
}
// form the 'where' clause for our main sql query
$rows_where = '';
$sql_where = '';
$sql_params = [];
if (grv('filter') != '') {
$sql_where = ' WHERE dt.name LIKE ?';
$sql_params[] = '%' . grv('filter') . '%';
}
if (grv('profile') != '-1') {
$sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' dtd.data_source_profile_id = ?';
$sql_params[] = grv('profile');
}
if (grv('method') != '-1') {
$sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' dtd.data_input_id = ?';
$sql_params[] = grv('method');
}
if (grv('has_data') == 'true') {
$sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . ' dt.data_sources > 0';
}
$total_rows = db_fetch_cell_prepared("SELECT COUNT(*)
FROM data_template AS dt
INNER JOIN data_template_data AS dtd
ON dt.id = dtd.data_template_id
AND dtd.local_data_id = 0
INNER JOIN data_input AS di
ON dtd.data_input_id = di.id
LEFT JOIN data_source_profiles AS dsp
ON dtd.data_source_profile_id = dsp.id
$sql_where",
$sql_params);
$sql_order = get_order_string();
$sql_limit = ' LIMIT ' . ($rows * (grv('page') - 1)) . ',' . $rows;
$template_list_sql = "SELECT dt.id, dt.name, dt.data_sources, dt.last_updated,
di.name AS data_input_method, dtd.active AS active, dsp.name AS profile_name
FROM data_template AS dt
INNER JOIN data_template_data AS dtd
ON dt.id = dtd.data_template_id
AND dtd.local_data_id = 0
LEFT JOIN data_source_profiles AS dsp
ON dtd.data_source_profile_id = dsp.id
LEFT JOIN data_input AS di
ON dtd.data_input_id = di.id
$sql_where
$sql_order
$sql_limit";
$template_list = db_fetch_assoc_prepared($template_list_sql, $sql_params);
$display_text = [
'dt.name' => [
'display' => __('Data Template Name'),
'align' => 'left',
'sort' => 'ASC',
'tip' => __('The name of this Data Template.')
],
'dt.id' => [
'display' => __('ID'),
'align' => 'right',
'sort' => 'ASC',
'tip' => __('The internal database ID for this Data Template. Useful when performing automation or debugging.')
],
'nosort' => [
'display' => __('Deletable'),
'align' => 'right',
'tip' => __('Data Templates that are in use cannot be Deleted. In use is defined as being referenced by a Data Source.')
],
'data_sources' => [
'display' => __('Data Sources Using'),
'align' => 'right',
'sort' => 'DESC',
'tip' => __('The number of Data Sources using this Data Template.')
],
'dtd.data_input_method' => [
'display' => __('Input Method'),
'align' => 'left',
'sort' => 'ASC',
'tip' => __('The method that is used to place Data into the Data Source RRDfile.')
],
'profile_name' => [
'display' => __('Profile Name'),
'align' => 'left',
'sort' => 'ASC',
'tip' => __('The default Data Source Profile for this Data Template.')
],
'active' => [
'display' => __('Status'),
'align' => 'left',
'sort' => 'ASC',
'tip' => __('Data Sources based on Inactive Data Templates will not be updated when the poller runs.')
],
'last_updated' => [
'display' => __('Last Updated'),
'align' => 'right',
'sort' => 'ASC',
'tip' => __('The last time this Template was updated.')
]
];
$nav = html_nav_bar('data_templates.php?filter=' . grv('filter'), MAX_DISPLAY_PAGES, grv('page'), $rows, $total_rows, cacti_sizeof($display_text) + 1, __('Data Templates'), 'page', 'main');
form_start('data_templates.php', 'chk');
print $nav;
html_start_box('', '100%', false, 3, 'center', '');
html_header_sort_checkbox($display_text, grv('sort_column'), grv('sort_direction'), false);
if (cacti_sizeof($template_list)) {
foreach ($template_list as $template) {
if ($template['data_sources'] > 0) {
$disabled = true;
} else {
$disabled = false;
}
$ds_url = 'data_sources.php?reset=true&template_id=' . $template['id'];
if (grv('profile') != '-1') {
$ds_url .= '&profile=' . grv('profile');
}
form_alternate_row('line' . $template['id'], true, $disabled);
form_selectable_cell(filter_value($template['name'], grv('filter'), 'data_templates.php?action=template_edit&id=' . $template['id']), $template['id']);
form_selectable_cell($template['id'], $template['id'], '', 'right');
form_selectable_cell($disabled ? __('No') : __('Yes'), $template['id'], '', 'right');
form_selectable_cell(filter_value(number_format_i18n($template['data_sources']), '', $ds_url), $template['id'], '', 'right');
form_selectable_cell((empty($template['data_input_method']) ? '<em>' . __('None') . '</em>' : htmle($template['data_input_method'])), $template['id']);
form_selectable_cell((empty($template['profile_name']) ? __('External') : htmle($template['profile_name'])), $template['id']);
form_selectable_cell((($template['active'] == 'on') ? __('Active') : __('Disabled')), $template['id']);
form_selectable_cell($template['last_updated'], $template['id'], '', 'right');
form_checkbox_cell($template['name'], $template['id'], $disabled);
form_end_row();
}
} else {
print "<tr class='tableRow odd'><td colspan='" . (cacti_sizeof($display_text) + 1) . "'><em>" . __('No Data Templates Found') . '</em></td></tr>';
}
html_end_box(false);
if (cacti_sizeof($template_list)) {
print $nav;
}
// draw the dropdown containing a list of available actions for this form
draw_actions_dropdown($actions);
form_end();
}
function create_data_template_filter() : array {
global $item_rows, $page_refresh_interval;
$all = ['-1' => __('All')];
$any = ['-1' => __('Any')];
$none = ['0' => __('None')];
if (isrv('has_data')) {
$value = gnrv('has_data');
} else {
$value = read_config_option('default_has') == 'on' ? 'true' : 'false';
}
$profiles = array_rekey(
db_fetch_assoc('SELECT id, name
FROM data_source_profiles
ORDER BY name'),
'id', 'name'
);
$profiles = $all + $profiles;
$methods = array_rekey(
db_fetch_assoc_prepared('SELECT id, name
FROM data_input
ORDER BY name'),
'id', 'name'
);
$methods = $all + $methods;
return [
'rows' => [
[
'method' => [
'method' => 'drop_array',
'friendly_name' => __('Method'),
'filter' => FILTER_VALIDATE_INT,
'default' => '-1',
'pageset' => true,
'array' => $methods,
'value' => '-1'
],
'profile' => [
'method' => 'drop_array',
'friendly_name' => __('Profile'),
'filter' => FILTER_VALIDATE_INT,
'default' => '-1',
'pageset' => true,
'array' => $profiles,
'value' => '-1'
],
'has_data' => [
'method' => 'filter_checkbox',
'friendly_name' => __('Has Data Sources'),
'filter' => FILTER_VALIDATE_REGEXP,
'filter_options' => ['options' => ['regexp' => '(true|false)']],
'default' => '',
'pageset' => true,
'value' => $value
]
],
[
'filter' => [
'method' => 'textbox',
'friendly_name' => __('Search'),
'filter' => FILTER_DEFAULT,
'placeholder' => __('Enter a search term'),
'size' => '30',
'default' => '',
'pageset' => true,
'max_length' => '120',
'value' => ''
],
'rows' => [
'method' => 'drop_array',
'friendly_name' => __('Data Templates'),
'filter' => FILTER_VALIDATE_INT,
'default' => '-1',
'pageset' => true,
'array' => $item_rows,
'value' => '-1'
]
]
],
'buttons' => [
'go' => [
'method' => 'submit',
'display' => __('Go'),
'title' => __('Apply filter to table'),
],
'clear' => [
'method' => 'button',
'display' => __('Clear'),
'title' => __('Reset filter to default values'),
]
],
'sort' => [
'sort_column' => 'dt.name',
'sort_direction' => 'ASC'
]
];
}
function draw_data_template_filter(bool $render = false) : void {
$filters = create_data_template_filter();
// create the page filter
$pageFilter = new CactiTableFilter(__('Data Templates'), 'data_templates.php', 'form_data', 'sess_dt', 'data_templates.php?action=template_edit');
$pageFilter->rows_label = __('Data Templates');
$pageFilter->set_filter_array($filters);
if ($render) {
$pageFilter->render();
} else {
$pageFilter->sanitize();
}
}