Files
cacti/templates_import.php
TheWitnessandTheWitness 3ab4c69fb7 PHPStan Level 8 - Phase 1 Conversion (#8135)
* PHPStan Level 8 - Phase 1 Conversion

Reduces the real (no-baseline) PHPStan level 8 error count from ~2,724 to 425
and regenerates phpstan-baseline.neon accordingly (8,941 -> 1,921 lines).

Core type-safety changes
- lib/database.php: narrow db_fetch_row()/db_fetch_row_prepared() to return
  array (was bool|array) and db_fetch_assoc()/db_fetch_assoc_prepared() to
  return array (was mixed); the _prepared workers coerce the connection-failure
  path to an empty array so the declared type is honest. empty()/cacti_sizeof()
  checks are unaffected.
- lib/database.php: narrow $db_conn guards from is_object() to instanceof PDO in
  the transaction/quote/insert-id helpers so the PDO calls resolve.
- lib/mib_cache.php: the fluent MibCache methods mib()/object()/table()/row()
  now return self instead of a bare object so chained calls type-check.

Type-safety casts and guards (mechanical, behaviour-preserving)
- Cast string|false/|null builtin results feeding string parameters
  (json_decode, base64_encode, trim, htmle, preg_replace, explode, etc.).
- Cast int|string / int|false values feeding int id/pid parameters.
- Guard resource|false fopen()/popen() handles before fwrite/fclose/fread, and
  wrap foreach over array|false/list|false results with `?: []`.

Genuine bugs found and fixed
- cli/add_tree.php / lib/api_tree.php: site tree nodes could not be created via
  the CLI - the --site-id option was never parsed, $nodeTypes had no 'site'
  entry (passing null to api_tree_item_save(int $type) -> TypeError), and
  api_tree_item_save() never persisted site_id. All three fixed.
- tree.php: leaves_exist() is typed : int but returned db_fetch_assoc_prepared()
  (an array of rows) for a SELECT COUNT(*); now uses db_fetch_cell_prepared()
  and returns the scalar count.
- lib/mib_cache.php: $entries_per_object was a float (division / ceil) used as
  an array key (PHP 8.1 implicit float-to-int key deprecation); now cast to int.

Config
- .phpstan.neon: add notIdentical.alwaysTrue and booleanAnd.alwaysFalse to the
  existing always-true/false ignore family (same "PHPStan gets confused"
  dynamic-constant cause already covered by identical.alwaysTrue,
  notEqual.alwaysTrue, booleanAnd.leftAlwaysTrue, etc.).
- phpstan-baseline.neon: regenerated; the remaining 425 entries are the
  untouched long tail for Phase 2.

* Remove redundant @phpstan-ignore comments

Follow-up cleanup for the level 8 Phase 1 work. Removes 14 inline
@phpstan-ignore comments that no longer suppress any reported error:

- cli/repair_database.php: `@phpstan-ignore booleanAnd.alwaysFalse` is now
  covered by the global booleanAnd.alwaysFalse ignore added to .phpstan.neon.
- 13 others (host.php, include/global.php, include/session.php,
  lib/api_automation.php x2, lib/functions.php x2, lib/html_utility.php x2,
  lib/installer.php, lib/package.php, lib/reports.php, lib/rrd.php) no longer
  match any reported error after the type-safety fixes (e.g. the
  db_fetch_row_prepared() return-type narrowing removed the offset-assign
  errors the api_automation ignores were suppressing).

Verified with reportUnmatchedIgnoredErrors enabled: 0 unmatched ignores
remain and the full level 8 run still reports 0 errors.

* ci: satisfy validator ratchet and refresh security sink baselines

- lib/api_tree.php: give the new tree-item site_id a real numeric
  constraint ('^[-0-9]+$', matching html_reports.php) instead of an
  empty regex, so the validator constraint ratchet passes without
  bumping its baseline.
- tests/security/baselines: refresh the three sink/hotspot signatures
  whose code text changed from the (string) casts added in this branch
  (lib/poller.php setsid, cli/rrdresize.php json_encode, lib/import.php
  simplexml_load_string).

* ci(js): allow DOMPurify 3.4.16 and update sync_js pin test

The dependabot bump (#8134) moved package.json/package-lock.json to
DOMPurify 3.4.16 on develop but left tests/js/sync_js.test.mjs pinned to
3.4.15, so the PR merge commit fails the 'DOMPurify is pinned' contract.
Bring package.json/package-lock.json to 3.4.16 (matching develop) and
update the pin test to expect 3.4.16.

* test: update sql.php null-handling assertion for the (string) cast

This branch changed scripts/sql.php from trim(\ ?? '') to
trim((string) \) (the phpstan-safe form that coerces both null and
false from shell_exec()). Update SqlScriptsTest's null-return assertion
to match the new cast instead of the removed '?? ''.

* fix: address Copilot review - ownership IDs, fopen guards, mib_cache bound

- chown()/chgrp(): pass integer UID/GID from fileowner()/filegroup()
  (guarding the false lookup) instead of string-casting them, which made
  them resolve account/group names like '1001' and fail. Covers
  lib/api_device.php, lib/boost.php and poller_maintenance.php (x2).
- fopen() failure now short-circuits instead of reporting success:
  lib/package.php returns false, lib/clog_webapi.php and utilities.php
  render an error, and snmpagent_mibcachechild.php skips the cache write
  and sentinel unlink so a concurrent writer's lock is preserved.
- lib/mib_cache.php: keep the float quotient as the loop bound and cast
  only the array offset, so a non-even entries/columns split no longer
  truncates the loop and drops a cached row.

* revert: keep db_fetch_* returning false on error; baseline Level 8 instead

Per review, restoring the intentional fail-safe: db_fetch_row[_prepared]()
return bool|array and db_fetch_assoc[_prepared]() return mixed again, so a
genuine SQL error (not just a missing connection) is signalled as false and
the === false checks in cdef_is_in_use(), boost_process_* and aggregate.php
work as before. Dropped the is_array() ? : [] coercion.

Level 8 stays green by regenerating phpstan-baseline.neon to capture the
re-introduced bool|array/mixed call-site errors (the ~1,850 the narrowing
had eliminated). Tightening those callers to drop them from the baseline is
Phase 2 work.

---------

Co-authored-by: TheWitness <copilot@users.noreply.github.com>
2026-10-02 10:08:56 -04:00

546 lines
15 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 . '/import.php');
require_once(CACTI_PATH_LIBRARY . '/poller.php');
require_once(CACTI_PATH_LIBRARY . '/template.php');
require_once(CACTI_PATH_LIBRARY . '/utility.php');
// set default action
set_default_action();
$action = grv('action');
$is_save = isrv('save_component_import');
$tmp_dir = sys_get_temp_dir();
$tmp_len = strlen($tmp_dir);
$tmp_dir .= ($tmp_len !== 0 && substr($tmp_dir, -$tmp_len) === '/') ? '' : '/';
$is_tmp = is_tmp_writable();
if ($is_tmp && $is_save && $action == 'save') {
form_save();
} else {
top_header();
if ($is_tmp) {
import();
} else {
bad_tmp();
}
bottom_footer();
}
function form_save() : void {
global $preview_only, $messages, $import_messages;
if (isrv('save_component_import')) {
// print '<pre>';print_r($_FILES);print '</pre>';exit;
if (($_FILES['import_file']['tmp_name'] != 'none') && ($_FILES['import_file']['tmp_name'] != '')) {
// file upload
$fp = fopen($_FILES['import_file']['tmp_name'],'r');
$xml_data = fread($fp,filesize($_FILES['import_file']['tmp_name']));
is_resource($fp) && fclose($fp);
} else {
header('Location: templates_import.php');
exit;
}
if (gfrv('import_data_source_profile') == '0') {
$import_as_new = true;
$profile_id = db_fetch_cell('SELECT id FROM data_source_profiles ORDER BY `default` DESC LIMIT 1');
} else {
$import_as_new = false;
$profile_id = grv('import_data_source_profile');
}
if (gnrv('preview_only') == 'true') {
$preview_only = true;
} else {
$preview_only = false;
}
if (isrv('remove_orphans') && gnrv('remove_orphans') == 'on') {
$remove_orphans = true;
} else {
$remove_orphans = false;
}
if (isrv('replace_svalues') && gnrv('replace_svalues') == 'on') {
$replace_svalues = true;
} else {
$replace_svalues = false;
}
$import_hashes = [];
// loop through each of the graphs selected on the previous page and get more info about them
foreach ($_POST as $var => $val) {
if (str_contains($var, 'chk_')) {
$id = base64_decode(str_replace('chk_', '', $var), true);
$id = json_decode((string) $id, true);
if (isset($id['hash'])) {
$import_hashes[] = $id['hash'];
}
}
}
// obtain debug information if it's set
$debug_data = import_xml_data($xml_data, $import_as_new, $profile_id, $remove_orphans, $replace_svalues, $import_hashes);
if (!$preview_only) {
raise_message('import_success', __('The Template Import Succeeded.'), MESSAGE_LEVEL_INFO);
header('Location: templates_import.php');
} elseif ($debug_data !== false && cacti_sizeof($debug_data)) {
// print '<pre>';print_r($debug_data);print '</pre>';exit;
$templates = prepare_template_display($debug_data);
// print '<pre>';print_r($templates);print '</pre>';
display_template_data($templates);
exit;
} else {
cacti_log(sprintf('ERROR: Import or Preview failed for XML file %s!', $_FILES['import_file']['name']), false, 'IMPORT');
$message_text = '';
/**
* The variables $import_messages is populated as a global variable
* set in the function import_xml_data(). It includes all the
* errors encountered during the import pre-processing.
*/
if (cacti_sizeof($import_messages)) {
foreach ($import_messages as $message) {
if (isset($messages[$message])) {
$message_text .= ($message_text != '' ? '<br>' : '') . $messages[$message]['message'];
}
}
}
raise_message_javascript(__('Error in Template', 'package'), __('The Template XML file "%s" validation failed', $_FILES['import_file']['name']), __('See the cacti.log for more information, and review the XML file for proper syntax. The error details are shown below.<br><br><b>Errors:</b><br>%s', $message_text));
}
}
}
function prepare_template_display(array &$import_info) : array {
global $hash_type_names;
$templates = [];
/**
* This function will create an array of item types and their status
* the user will have an option to import select items based upon
* these values.
*
* $templates['template_hash'] = array(
* 'package' => 'some_package_name',
* 'package_file' => 'some_package_filename',
* 'type' => 'some_type',
* 'type_name' => 'some_type_name',
* 'name' => 'some_name',
* 'status' => 'some_status'
* );
*/
if (cacti_sizeof($import_info)) {
foreach ($import_info as $type => $type_array) {
if ($type == 'files') {
$templates['files'] = $type_array;
continue;
}
foreach ($type_array as $index => $vals) {
$hash = $vals['hash'];
if (!isset($templates[$hash])) {
$templates[$hash]['status'] = $vals['type'];
} else {
$templates[$hash]['status'] .= '<br>' . $vals['type'];
}
$templates[$hash]['type'] = $type;
$templates[$hash]['type_name'] = $hash_type_names[$type];
$templates[$hash]['name'] = $vals['title'];
unset($vals['title']);
unset($vals['result']);
unset($vals['hash']);
unset($vals['type']);
if (isset($vals['dep'])) {
$template[$hash]['deps'] = $vals['dep'];
}
if (cacti_sizeof($vals)) {
$templates[$hash]['vals'] = $vals;
}
}
}
}
return $templates;
}
function display_template_data(array &$templates) : void {
if (isset($templates['files'])) {
$files = $templates['files'];
unset($templates['files']);
html_start_box(__('Import Files [ If Files are missing, locate and install before using ]'), '100%', false, 3, 'center', '');
$display_text = [
[
'display' => __('File Name')
],
[
'display' => __('Status')
]
];
html_header($display_text);
$id = 0;
foreach ($files as $path => $status) {
if ($status == 'found') {
$status = "<span class='deviceUp'>" . __('Exists') . '</span>';
} elseif ($status == 'notreadable') {
$status = "<span class='deviceRecovering'>" . __('Not Readable') . '</span>';
} else {
$status = "<span class='deviceDown'>" . __('Not Found') . '</span>';
}
form_alternate_row('line_' . $id);
form_selectable_ecell($path, $id);
form_selectable_cell($status, $id);
form_end_row();
}
html_end_box();
}
if (cacti_sizeof($templates)) {
html_start_box(__('Import Templates [ None selected imports all, Check to import selectively ]'), '100%', false, 3, 'center', '');
$display_text = [
[
'display' => __('Template Type')
],
[
'display' => __('Template Name')
],
[
'display' => __('Status')
],
[
'display' => __('Dependencies')
],
[
'display' => __('Changes/Diffferences')
]
];
html_header_checkbox($display_text, false, '', true, 'import');
$templates = array_reverse($templates);
foreach ($templates as $hash => $detail) {
$id = base64_encode(
json_encode(
[
'hash' => $hash,
'type' => $detail['type_name'],
'name' => $detail['name'],
'status' => $detail['status']
]
)
);
if ($detail['status'] == 'updated') {
$status = "<span class='updateObject'>" . __('Updated') . '</span>';
} elseif ($detail['status'] == 'new') {
$status = "<span class='newObject'>" . __('New') . '</span>';
} elseif ($detail['status'] == 'damaged') {
$status = "<span class='deviceDown'>" . __('Damaged') . '</span>';
} else {
$status = "<span class='deviceUp'>" . __('Unchanged') . '</span>';
}
form_alternate_row('line_import_' . $detail['status'] . '_' . $id);
form_selectable_ecell($detail['type_name'], $id);
form_selectable_ecell($detail['name'], $id);
form_selectable_cell($status, $id);
if (isset($detail['deps'])) {
$dep_details = [];
$unmet_count = 0;
$met_count = 0;
foreach ($detail['deps'] as $hash => $dep) {
if ($dep == 'met') {
$dep_details[$dep] = $dep;
$met_count++;
} else {
$dep_details[$dep] = $dep;
$unmet_count++;
}
}
if (isset($dep_details['met'])) {
$dep_details['met'] = __('Met: %d', $met_count);
}
if (isset($dep_details['unmet'])) {
$dep_details['unmet'] = __('Unmet: %d', $unmet_count);
}
form_selectable_cell(implode(', ', $dep_details), $id, '', 'white-space:pre-wrap');
} else {
form_selectable_cell(__('None'), $id);
}
if ($detail['status'] == 'damaged') {
form_selectable_cell(__('Some CDEF Items will not import due to an export error! Contact Template provider for an updated export.'), $id);
} elseif (isset($detail['vals'])) {
$diff_details = '';
$diff_array = [];
$orphan_array = [];
foreach ($detail['vals'] as $type => $diffs) {
if ($type == 'differences') {
foreach ($diffs as $item) {
$diff_array[$item] = $item;
}
} elseif ($type == 'orphans') {
foreach ($diffs as $item) {
$orphan_array[$item] = $item;
}
}
}
if (cacti_sizeof($diff_array)) {
$diff_details .= __('Differences', 'package') . '<br>' . implode('<br>', $diff_array);
}
if (cacti_sizeof($orphan_array)) {
$diff_details .= ($diff_details != '' ? '<br>' : '') . __('Orphans', 'package') . '<br>' . implode('<br>', $orphan_array);
}
form_selectable_cell($diff_details, $id, '', 'white-space:pre-wrap');
} else {
form_selectable_cell(__('None'), $id);
}
form_checkbox_cell($detail['name'], $id);
form_end_row();
}
html_end_box();
}
}
function bad_tmp() : void {
html_start_box(__('Import Template'), '60%', false, 3, 'center', '');
form_alternate_row();
print "<td class='textarea'><p><strong>" . __('ERROR') . ':</strong> ' . __('Failed to access temporary folder, import functionality is disabled') . "</p></td></tr>\n";
html_end_box();
}
function import() : void {
global $hash_type_names, $fields_template_import;
$default_profile = db_fetch_cell('SELECT id FROM data_source_profiles WHERE `default`="on"');
if (empty($default_profile)) {
$default_profile = db_fetch_cell('SELECT id FROM data_source_profiles ORDER BY id LIMIT 1');
}
form_start('templates_import.php', 'import', true);
// ================= input validation and session storage =================
$filters = [
'preview_only' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['options' => ['regexp' => '(true|false)']],
'default' => 'on'
],
'replace_svalues' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['options' => ['regexp' => '(true|false)']],
'default' => read_config_option('replace_svalues')
],
'remove_orphans' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['options' => ['regexp' => '(true|false)']],
'default' => read_config_option('remove_orphans')
],
'data_source_profile' => [
'filter' => FILTER_VALIDATE_INT,
'default' => $default_profile
],
'image_format' => [
'filter' => FILTER_VALIDATE_INT,
'default' => read_config_option('default_image_format')
],
'graph_width' => [
'filter' => FILTER_VALIDATE_INT,
'default' => read_config_option('default_graph_width')
],
'graph_height' => [
'filter' => FILTER_VALIDATE_INT,
'default' => read_config_option('default_graph_height')
],
];
validate_store_request_vars($filters, 'sess_pimport');
// ================= input validation =================
$fields_template_import['import_data_source_profile']['default'] = $default_profile;
if (isrv('replace_svalues') && gnrv('replace_svalues') == 'true') {
$fields_template_import['replace_svalues']['value'] = 'on';
} else {
$fields_template_import['replace_svalues']['value'] = '';
}
if (isrv('remove_orphans') && gnrv('remove_orphans') == 'true') {
$fields_template_import['remove_orphans']['value'] = 'on';
} else {
$fields_template_import['remove_orphans']['value'] = '';
}
if (isrv('image_format')) {
$fields_template_import['image_format']['value'] = gfrv('image_format');
} else {
$fields_template_import['image_format']['value'] = read_config_option('default_image_format');
}
if (isrv('graph_width')) {
$fields_template_import['graph_width']['value'] = gfrv('graph_width');
} else {
$fields_template_import['graph_width']['value'] = read_config_option('default_graph_width');
}
if (isrv('graph_height')) {
$fields_template_import['graph_height']['value'] = gfrv('graph_height');
} else {
$fields_template_import['graph_height']['value'] = read_config_option('default_graph_height');
}
html_start_box(__('Import Template'), '100%', true, 3, 'center', '');
draw_edit_form(
[
'config' => ['no_form_tag' => true],
'fields' => $fields_template_import
]
);
html_end_box(true, true);
print '<div id="contents"></div>';
form_hidden_box('save_component_import','1','');
form_save_button('', 'import', 'import', false);
?>
<script type='text/javascript'>
$(function() {
$('#import_file').change(function() {
var form = $('#import')[0];
var data = new FormData(form);
Pace.start();
$.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: (urlPath != '/' ? urlPath + '/':'') + 'templates_import.php?preview_only=true',
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
if ($('#contents').length == 0) {
$('#main').append('<div id="contents"></div>');
} else {
$('#contents').empty();
}
$('#contents').html(data);
if ($('#templates_import_save2_child').length) {
applySelectorVisibilityAndActions();
$('#templates_import_save2_child').find('tr[id^="line_import_new_"]').each(function(event) {
selectUpdateRow(event, $(this));
});
}
Pace.stop();
},
error: function (e) {
if ($('#contents').length == 0) {
$('#main').append('<div id="contents"></div>');
} else {
$('#contents').empty();
}
$('#contents').html(data);
Pace.stop();
}
});
});
});
</script>
<?php
}
function is_tmp_writable(string $tmp_dir = '') : bool {
if ($tmp_dir === '') {
$tmp_dir = sys_get_temp_dir();
}
$tmp_len = strlen($tmp_dir);
$tmp_dir .= ($tmp_len !== 0 && substr($tmp_dir, -$tmp_len) === '/') ? '' : '/';
$is_tmp = is_resource_writable($tmp_dir);
return $is_tmp;
}