repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/command/minHelpCommandFunctions.php | centreon/www/include/configuration/configObject/command/minHelpCommandFunctions.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
/**
* @param string $command
* @return bool
*/
function isCommandInAllowedResources(CentreonDB $pearDB, string $command): bool
{
$allowedResources = getAllResources($pearDB);
foreach ($allowedResources as $path) {
if (str_starts_with($command, $path)) {
return true;
}
}
return false;
}
/**
* @param CentreonDB $pearDB
* @param int $commandId
* @return string|null
*/
function getCommandById(CentreonDB $pearDB, int $commandId): ?string
{
$sth = $pearDB->prepare('SELECT command_line FROM `command` WHERE `command_id` = :command_id');
$sth->bindParam(':command_id', $commandId, PDO::PARAM_INT);
$sth->execute();
$command = $sth->fetchColumn();
return $command !== false ? $command : null;
}
/**
* @param CentreonDB $pearDB
* @param string $resourceName
* @return string|null
*/
function getResourcePathByName(CentreonDB $pearDB, string $resourceName): ?string
{
$prepare = $pearDB->prepare(
'SELECT `resource_line` FROM `cfg_resource` WHERE `resource_name` = :resource LIMIT 1'
);
$prepare->bindValue(':resource', $resourceName, PDO::PARAM_STR);
$prepare->execute();
$resourcePath = $prepare->fetchColumn();
return $resourcePath !== false ? $resourcePath : null;
}
/**
* @param CentreonDB $pearDB
* @return string[]
*/
function getAllResources(CentreonDB $pearDB): array
{
$dbResult = $pearDB->query('SELECT `resource_line` FROM `cfg_resource`');
return $dbResult->fetchAll(PDO::FETCH_COLUMN);
}
/**
* @param string $commandLine
* @return array{commandPath:string,plugin:string|null,mode:string|null}
*/
function getCommandElements(string $commandLine): array
{
$commandElements = explode(' ', $commandLine);
$matchPluginOption = array_values(preg_grep('/^\-\-plugin\=(\w+)/i', $commandElements) ?? []);
$plugin = $matchPluginOption[0] ?? null;
$matchModeOption = array_values(preg_grep('/^\-\-mode\=(\w+)/i', $commandElements) ?? []);
$mode = $matchModeOption[0] ?? null;
return ['commandPath' => $commandElements[0], 'plugin' => $plugin, 'mode' => $mode];
}
/**
* @param CentreonDB $pearDB
* @param string $commandPath
* @return string
*/
function replaceMacroInCommandPath(CentreonDB $pearDB, string $commandPath): string
{
$explodedCommandPath = explode('/', $commandPath);
$resourceName = $explodedCommandPath[0];
// Match if the first part of the path is a MACRO
if ($resourcePath = getResourcePathByName($pearDB, $resourceName)) {
unset($explodedCommandPath[0]);
return rtrim($resourcePath, '/') . '/' . implode('/', $explodedCommandPath);
}
return $commandPath;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/command/javascript/commandJs.php | centreon/www/include/configuration/configObject/command/javascript/commandJs.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
?>
<script type="text/javascript">
var listArea;
var macroSvc = new Array();
var macroHost = new Array();
function goPopup() {
var cmd_line;
var tmpStr;
var reg = new RegExp("(\n)", "g");
listArea = document.getElementById('listOfArg');
tmpStr = listArea.value;
tmpStr = encodeURIComponent(tmpStr.replace(reg, ";;;"));
cmd_line = document.getElementById('command_line').value;
var popin = jQuery('<div id="config-popin">');
popin.centreonPopin({
url: './include/configuration/configObject/command/formArguments.php?cmd_line=' + cmd_line +
'&textArea=' + tmpStr,
open: true,
ajaxDataType: 'html'
});
}
function setDescriptions() {
var i;
var tmpStr2;
var listDiv;
tmpStr2 = "";
listArea = document.getElementById('listOfArg');
listDiv = document.getElementById('listOfArgDiv');
for (i = 1; document.getElementById('desc_' + i); i++) {
tmpStr2 += "ARG" + document.getElementById('macro_' + i).value + " : " +
document.getElementById('desc_' + i).value + "\n";
}
listArea.cols = 100;
listArea.rows = i;
listArea.value = tmpStr2;
listDiv.style.visibility = "visible";
jQuery('#config-popin').centreonPopin('close');
}
function closeBox() {
jQuery('#config-popin').centreonPopin('close');
}
function clearArgs() {
listArea = document.getElementById('listOfArg');
listArea.value = "";
}
function manageMacros() {
var commandLine = document.Form.command_line.value;
var commandId = document.Form.command_id.value;
var tmpStr = "";
var popin = jQuery('<div id="config-popin">');
popin.centreonPopin({
url: './include/configuration/configObject/command/formMacros.php?cmd_line=' + commandLine +
'&cmdId=' + commandId + '&textArea=' + tmpStr,
open: true,
ajaxDataType: 'html'
});
}
function setMacrosDescriptions() {
var i;
var tmpStr2;
var listDiv;
tmpStr2 = "";
listArea = document.getElementById('listOfMacros');
listDiv = document.getElementById('listOfMacros');
for (i = 0; document.getElementById('desc_' + i); i++) {
var type = "HOST";
if (document.getElementById('type_' + i).value == 2) {
type = "SERVICE";
}
tmpStr2 += "MACRO (" + type + ") " + document.getElementById('macro_' + i).value + " : " +
document.getElementById('desc_' + i).value + "\n";
}
listArea.cols = 100;
listArea.rows = i;
listArea.value = tmpStr2;
listDiv.style.visibility = "visible";
jQuery('#config-popin').centreonPopin('close');
}
function checkType(value) {
var action = jQuery('form#Form').attr('action');
switch (value) {
case '1':
action = action.replace(/p=\d+/, 'p=60802');
break;
case '2':
action = action.replace(/p=\d+/, 'p=60801');
break;
case '3':
action = action.replace(/p=\d+/, 'p=60803');
break;
case '4':
action = action.replace(/p=\d+/, 'p=60807');
break;
default:
action = action.replace(/p=\d+/, 'p=60801');
break;
}
if (action.match(/&type=/)) {
action = action.replace(/&type=\d+/, '&type=' + value);
} else {
action += '&type=' + value;
}
jQuery('form#Form').attr('action', action);
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/timeperiod/timeperiod.php | centreon/www/include/configuration/configObject/timeperiod/timeperiod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
// Path to the configuration dir
$path = './include/configuration/configObject/timeperiod/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
$tp_id = filter_var(
$_GET['tp_id'] ?? $_POST['tp_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
switch ($o) {
case 'a': // Add a Timeperiod
case 'w': // Watch a Timeperiod
case 'c': // Modify a Timeperiod
require_once $path . 'formTimeperiod.php';
break;
case 's': // Show Timeperiod
require_once $path . 'renderTimeperiod.php';
break;
case 'm': // Duplicate n Timeperiods
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleTimeperiodInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
} else {
unvalidFormMessage();
}
require_once $path . 'listTimeperiod.php';
break;
case 'd': // Delete n Timeperiods
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteTimePeriodInAPI(is_array($select) ? array_keys($select) : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listTimeperiod.php';
break;
default:
require_once $path . 'listTimeperiod.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/timeperiod/formTimeperiod.php | centreon/www/include/configuration/configObject/timeperiod/formTimeperiod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$tp = [];
if (($o == 'c' || $o == 'w') && $tp_id) {
$dbResult = $pearDB->prepare('SELECT * FROM timeperiod WHERE tp_id = :tp_id LIMIT 1');
$dbResult->bindValue(':tp_id', $tp_id, PDO::PARAM_INT);
$dbResult->execute();
// Set base value
$tp = array_map('myDecode', $dbResult->fetchRow());
$tp['contact_exclude'] = [];
}
$j = 0;
$dbResult = $pearDB->prepare(
'SELECT exception_id, timeperiod_id, days, timerange
FROM timeperiod_exceptions
WHERE timeperiod_id = :tp_id ORDER BY `days`'
);
$dbResult->bindValue(':tp_id', $tp_id, PDO::PARAM_INT);
$dbResult->execute();
while ($exceptionTab = $dbResult->fetchRow()) {
$exception_id[$j] = $exceptionTab['exception_id'];
$exception_days[$j] = $exceptionTab['days'];
$exception_timerange[$j] = $exceptionTab['timerange'];
$exception_timeperiod_id[$j] = $exceptionTab['timeperiod_id'];
$j++;
}
$dbResult->closeCursor();
// Var information to format the element
$attrsText = ['size' => '35'];
$attrsTextLong = ['size' => '55', 'maxlength' => '2048'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 130px;'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$timeAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod&action=list'
. ($tp_id ? "&exclude={$tp_id}" : ''); // exclude this timeperiod from list
$attrTimeperiods = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $timeAvRoute, 'multiple' => true, 'linkedObject' => 'centreonTimeperiod'];
// Form begin
$form = new HTML_QuickFormCustom(
'Form',
'post',
'?p=' . $p,
'',
['onsubmit' => 'return formValidate()', 'data-centreon-validate' => '']
);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a Time Period'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a Time Period'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a Time Period'));
}
// Time Period basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'tp_name', _('Time Period Name'), $attrsText);
$form->addElement('text', 'tp_alias', _('Alias'), $attrsTextLong);
// Notification informations
$form->addElement('header', 'include', _('Extended Settings'));
$form->addElement('text', 'tp_sunday', _('Sunday'), $attrsTextLong);
$form->addElement('text', 'tp_monday', _('Monday'), $attrsTextLong);
$form->addElement('text', 'tp_tuesday', _('Tuesday'), $attrsTextLong);
$form->addElement('text', 'tp_wednesday', _('Wednesday'), $attrsTextLong);
$form->addElement('text', 'tp_thursday', _('Thursday'), $attrsTextLong);
$form->addElement('text', 'tp_friday', _('Friday'), $attrsTextLong);
$form->addElement('text', 'tp_saturday', _('Saturday'), $attrsTextLong);
// Include Timeperiod
$timeDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod'
. '&action=defaultValues&target=timeperiodRenderer&field=tp_include&id=' . $tp_id;
$attrTimeperiod1 = array_merge(
$attrTimeperiods,
['defaultDatasetRoute' => $timeDeRoute]
);
$form->addElement('select2', 'tp_include', _('Timeperiod templates'), [], $attrTimeperiod1);
// Multiple exceptions relations stored in DB
$mTp = [];
$k = 0;
$DBRESULT = $pearDB->prepare('SELECT exception_id FROM timeperiod_exceptions WHERE timeperiod_id = :tp_id');
$DBRESULT->bindValue(':tp_id', $tp_id, PDO::PARAM_INT);
$DBRESULT->execute();
while ($multiTp = $DBRESULT->fetchRow()) {
$mTp[$k] = $multiTp['exception_id'];
$k++;
}
$DBRESULT->closeCursor();
// Include javascript for dynamique entries
require_once './include/configuration/configObject/timeperiod/timeperiod_JS.php';
if ($o == 'c' || $o == 'a' || $o == 'mc') {
echo '<script type="text/javascript">';
echo 'var tab = [];';
for ($k = 0; isset($mTp[$k]); $k++) {
echo "tab[{$k}] = " . $mTp[$k] . ';';
}
for ($k = 0; isset($exception_id[$k]); $k++) { ?>
globalExceptionTabId[<?php echo $k; ?>] = <?php echo $exception_id[$k]; ?>;
globalExceptionTabName[<?php echo $k; ?>] = '<?php echo $exception_days[$k]; ?>';
globalExceptionTabTimerange[<?php echo $k; ?>] = '<?php echo $exception_timerange[$k]; ?>';
globalExceptionTabTimeperiodId[<?php echo $k; ?>] = <?php echo $exception_timeperiod_id[$k]; ?>;
<?php
}
echo '</script>';
}
// Further informations
$form->addElement('hidden', 'tp_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Form Rules
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['tp_name']);
}
// Set rules
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('tp_name', 'myReplace');
$form->registerRule('exist', 'callback', 'testTPExistence');
$form->registerRule('format', 'callback', 'checkHours');
// Name Check
$form->addRule('tp_name', _('Compulsory Name'), 'required');
$form->addRule('tp_name', _('Name is already in use'), 'exist');
$form->addRule('tp_alias', _('Compulsory Alias'), 'required');
// Check Hours format
$form->addRule('tp_sunday', _('Error in hour definition'), 'format');
$form->addRule('tp_monday', _('Error in hour definition'), 'format');
$form->addRule('tp_tuesday', _('Error in hour definition'), 'format');
$form->addRule('tp_wednesday', _('Error in hour definition'), 'format');
$form->addRule('tp_thursday', _('Error in hour definition'), 'format');
$form->addRule('tp_friday', _('Error in hour definition'), 'format');
$form->addRule('tp_saturday', _('Error in hour definition'), 'format');
// Check for template loops
$form->registerRule('templateLoop', 'callback', 'testTemplateLoop');
$form->addRule('tp_include', _('The selected template has the same time period as a template'), 'templateLoop');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
if ($o == 'w') {
// Just watch a Time Period information
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&tp_id=' . $tp_id . "'"]
);
}
$form->setDefaults($tp);
$form->freeze();
} elseif ($o == 'c') {
// Modify a Time Period information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($tp);
} elseif ($o == 'a') {
// Add a Time Period information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
// Translations
$tpl->assign('tRDay', _('Days'));
$tpl->assign('tRHours', _('Time Range'));
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange",'
. ' TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"],'
. ' WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$valid = false;
if ($form->validate()) {
$tpObj = $form->getElement('tp_id');
if ($form->getSubmitValue('submitA')) {
if (null !== $timeperiodId = insertTimePeriodInAPI()) {
$tpObj->setValue($timeperiodId);
$o = null;
$valid = true;
}
} elseif ($form->getSubmitValue('submitC')) {
if (updateTimeperiodInAPI($tpObj->getValue())) {
$o = null;
$valid = true;
}
}
}
if ($valid) {
require_once $path . 'listTimeperiod.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign('gmtUsed', $centreon->CentreonGMT->used());
$tpl->assign('noExceptionMessage', _('GMT is activated on your system. Exceptions will not be generated.'));
$tpl->assign('exceptionLabel', _('Exceptions'));
$tpl->assign('countExceptions', $k);
$tpl->display('formTimeperiod.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/timeperiod/help.php | centreon/www/include/configuration/configObject/timeperiod/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
// Basic Settings
$help['timeperiod_name'] = dgettext('help', 'Define a short name to identify the time period.');
$help['alias'] = dgettext('help', 'Use the alias as a longer name or description to identify the time period.');
$help['weekday'] = dgettext(
'help',
'The weekday directives are comma-delimited lists of time ranges that are "valid" times for a particular '
. 'day of the week. Each time range is in the form of HH:MM-HH:MM, where hours are specified on a 24 hour '
. 'clock. For example, 00:15-24:00 means 12:15am in the morning for this day until 12:00am midnight '
. '(a 23 hour, 45 minute total time range). If you wish to exclude an entire day from the timeperiod, simply '
. 'do not include it in the timeperiod definition.'
);
$help['exception'] = dgettext(
'help',
'You can specify several different types of exceptions to the standard rotating weekday schedule. '
. 'Exceptions can take a number of different forms including single days of a specific or generic month, '
. 'single weekdays in a month, or single calendar dates. You can also specify a range of days/dates and even '
. 'specify skip intervals to obtain functionality described by "every 3 days between these dates". '
. 'Weekdays and different types of exceptions all have different levels of precedence, so it is important '
. 'to understand how they can affect each other.'
);
// Advanced Settings
$help['include'] = dgettext('help', 'This directive is used to specify other timeperiod used as a timeperiod model.');
$help['exclude'] = dgettext(
'help',
'This directive is used to specify other timeperiod definitions whose time ranges should be excluded '
. 'from this timeperiod.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/timeperiod/renderTimeperiod.php | centreon/www/include/configuration/configObject/timeperiod/renderTimeperiod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$tpG = $_GET['tp_id'] ?? null;
$tpP = $_POST['tp_id'] ?? null;
$tp_id = $tpG ?: $tpP;
$path = './include/configuration/configObject/timeperiod/';
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
require_once _CENTREON_PATH_ . 'www/class/centreonTimeperiodRenderer.class.php';
$imgpath = './include/common/javascript/scriptaculous/images/bramus/';
$imgs = scandir($imgpath);
$t = null;
if ($tp_id) {
$t = new CentreonTimePeriodRenderer($pearDB, $tp_id, 1);
$t->timeBars();
}
$query = 'SELECT tp_name, tp_id FROM timeperiod';
$DBRESULT = $pearDB->query($query);
$tplist[0] = _('Select Timeperiod...');
while ($row = $DBRESULT->fetchRow()) {
$tplist[$row['tp_id']] = $row['tp_name'];
}
$form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p . '&o=s');
$attrs1 = ['onchange' => "javascript: setTP(this.form.elements['tp_id'].value); submit();"];
$form->addElement('select', 'tp_id', null, $tplist, $attrs1);
$form->setDefaults(['tp_id' => null]);
$tpel = $form->getElement('tp_id');
if ($tp_id) {
$tpel->setValue($tp_id);
$tpel->setSelected($tp_id);
}
$attrsTextLong = ['size' => '55'];
$form->addElement('header', 'title', _('Resulting Time Period with inclusions'));
$form->addElement('header', 'information', _('General Information'));
$form->addElement('header', 'notification', _('Time Range'));
$form->addElement('header', 'exception', _('Exception List'));
$form->addElement('text', 'tp_name', _('Timeperiod Name'), $attrsTextLong);
$form->addElement('text', 'tp_alias', _('Timeperiod Alias'), $attrsTextLong);
$form->addElement('text', 'tp_sunday', _('Sunday'), $attrsTextLong);
$form->addElement('text', 'tp_monday', _('Monday'), $attrsTextLong);
$form->addElement('text', 'tp_tuesday', _('Tuesday'), $attrsTextLong);
$form->addElement('text', 'tp_wednesday', _('Wednesday'), $attrsTextLong);
$form->addElement('text', 'tp_thursday', _('Thursday'), $attrsTextLong);
$form->addElement('text', 'tp_friday', _('Friday'), $attrsTextLong);
$form->addElement('text', 'tp_saturday', _('Saturday'), $attrsTextLong);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$labels = ['unset_timerange' => _('Unset Timerange'), 'included_timerange' => _('Included Timerange'), 'excluded_timerange' => _('Excluded Timerange'), 'timerange_overlaps' => _('Timerange Overlaps'), 'hover_for_info' => _('Hover on timeline to see more information'), 'no_tp_selected' => _('No time period selected')];
$tpl->assign('labels', $labels);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('tpId', $tp_id);
$tpl->assign('tp', $t);
$tpl->assign('path', $path);
$tpl->display('renderTimeperiod.ihtml');
?>
<script type="text/javascript">
var tipDiv;
jQuery(function () {
genToolTip();
});
/**
* Set Time period
*/
function setTP(_i) {
document.forms['form'].elements['tp_id'].value = _i;
}
/**
* The tool tip is created and referenced as a global object
*/
function genToolTip() {
if (document.createElement) {
tipDiv = document.createElement('div');
document.body.appendChild(tipDiv);
tipDiv.appendChild(document.createTextNode('initial text'));
tipDiv.className = 'toolTip';
tipDiv.style.display = 'none';
}
}
/**
* Show tooltip
*/
function showTip(e, txt) {
if (tipDiv) {
var e = e || window.event;
var xy = cursorPos(e);
tipDiv.firstChild.data = txt;
tipDiv.style.left = (xy[0] + 5) + 'px';
tipDiv.style.top = (xy[1] + 15) + 'px';
tipDiv.style.display = '';
}
}
/**
* Hide tooltip
*/
function hideTip() {
if (tipDiv) {
tipDiv.style.display = 'none';
}
}
/**
* Based on quirskmode 'get cursor position' script
*/
function cursorPos(e) {
if (e.pageX || e.pageY) {
return [e.pageX, e.pageY];
} else if (e.clientX || e.clientY) {
return [
e.clientX + document.body.scrollLeft,
e.clientY + document.body.scrollTop
];
}
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/timeperiod/timeperiod_JS.php | centreon/www/include/configuration/configObject/timeperiod/timeperiod_JS.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
?>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/qtip/jquery-qtip.js"></script>
<script type="text/javascript" src="./lib/HTML/QuickForm/qfamsHandler-min.js"></script>
<script type="text/javascript" src="./include/common/javascript/jquery/plugins/centreon/jquery.centreonValidate.js"></script>
<script type="text/javascript">
/*
* This second block is the javascript code for the multi exception creation
*/
function addBlankInput() {
var tabElem = document.getElementById('exceptionTable');
var keyElem = document.createElement('input');
var valueElem = document.createElement('input');
var imgElem = document.createElement('img');
var trElem = document.createElement('tr');
var tbodyElem = document.createElement('tbody');
trElem.id = "trElem_" + globalj;
if (trExceptionClassFlag) {
trElem.className = "list_one";
trExceptionClassFlag = 0;
} else {
trElem.className = "list_two";
trExceptionClassFlag = 1;
}
trElem.id = "trExceptionInput_" + globalj;
var tdElem1 = document.createElement('td');
tdElem1.className = "ListColLeft";
var tdElem2 = document.createElement('td');
tdElem2.className = "ListColLeft";
var tdElem3 = document.createElement('td');
tdElem3.className = "ListColCenter";
keyElem.id = 'exceptionInput_' + globalj;
keyElem.name = 'exceptionInput_' + globalj;
keyElem.value = '';
keyElem.className = 'v_required v_regex';
keyElem.setAttribute('data-validator', '^((([0-9]{4}-[0-9]{2}-[0-9]{2})|(day ([0-9]{1,2}|-[0-9]{1,2})( - ([0-9]{1,2}|-[0-9]{1,2}))?)|((sunday|monday|tuesday|wednesday|thursday|friday|saturday) ([0-9]{1,2}|-[0-9]{1,2})( (january|february|march|april|may|june|july|august|september|october|november|december))?)|((january|february|march|april|may|june|july|august|september|october|november|december) ([0-9]{1,2}|-[0-9]{1,2})( - ([0-9]{1,2}|-[0-9]{1,2}))?))( - )?( \/ [0-9]{1,2})?)+$');
tdElem1.appendChild(keyElem);
valueElem.id = 'exceptionTimerange_' + globalj;
valueElem.name = 'exceptionTimerange_' + globalj;
valueElem.value = "";
valueElem.className = 'v_required v_regex';
valueElem.setAttribute('data-validator', '^([0-9]{2}:[0-9]{2}-[0-9]{2}:[0-9]{2}(,)?)+$');
tdElem2.appendChild(valueElem);
imgElem.src = "./img/icons/circle-cross.png";
imgElem.class = 'ico-14';
imgElem.id = globalj;
imgElem.onclick = function () {
var response = window.confirm('<?php echo _('Do you confirm this deletion?'); ?>');
if (response) {
if (navigator.appName == "Microsoft Internet Explorer") {
document.getElementById('trExceptionInput_' + this.id).innerText = "";
} else {
document.getElementById('trExceptionInput_' + this.id).innerHTML = "";
}
}
}
tdElem3.appendChild(imgElem);
trElem.appendChild(tdElem1);
trElem.appendChild(tdElem2);
trElem.appendChild(tdElem3);
tbodyElem.appendChild(trElem);
tabElem.appendChild(tbodyElem);
globalj++;
document.getElementById('hiddenExInput').value = globalj;
}
/*
* Function for displaying existing exceptions
*/
function displayExistingExceptions(max) {
for (var i = 0; i < max; i++) {
var keyElem = document.createElement('input');
var valueElem = document.createElement('input');
var imgElem = document.createElement('img');
var tabElem = document.getElementById('exceptionTable');
var trElem = document.createElement('tr');
var tbodyElem = document.createElement('tbody');
var _o = '<?php echo $o; ?>';
trElem.id = "trElem_" + globalj;
if (trExceptionClassFlag) {
trElem.className = "list_one";
trExceptionClassFlag = 0;
} else {
trElem.className = "list_two";
trExceptionClassFlag = 1;
}
trElem.id = "trExceptionInput_" + globalj;
var tdElem1 = document.createElement('td');
tdElem1.className = "ListColLeft";
var tdElem2 = document.createElement('td');
tdElem2.className = "ListColLeft";
var tdElem3 = document.createElement('td');
tdElem3.className = "ListColCenter";
keyElem.id = 'exceptionInput_' + globalj;
keyElem.name = 'exceptionInput_' + globalj;
keyElem.value = globalExceptionTabName[globalj];
tdElem1.appendChild(keyElem);
valueElem.id = 'exceptionTimerange_' + globalj;
valueElem.name = 'exceptionTimerange_' + globalj;
valueElem.value = globalExceptionTabTimerange[globalj];
tdElem2.appendChild(valueElem);
if (_o == "w") {
keyElem.disabled = true;
valueElem.disabled = true;
}
imgElem.src = "./img/icons/circle-cross.png";
imgElem.class = 'ico-14';
imgElem.id = globalj;
imgElem.onclick = function () {
var response = window.confirm('<?php echo _('Do you confirm this deletion?'); ?>');
if (response) {
if (navigator.appName == "Microsoft Internet Explorer") {
document.getElementById('trExceptionInput_' + this.id).innerText = "";
}
else {
document.getElementById('trExceptionInput_' + this.id).innerHTML = "";
}
}
}
tdElem3.appendChild(imgElem);
trElem.appendChild(tdElem1);
trElem.appendChild(tdElem2);
if (_o != "w") {
trElem.appendChild(tdElem3);
}
globalj++;
tbodyElem.appendChild(trElem);
tabElem.appendChild(tbodyElem);
}
document.getElementById('hiddenExInput').value = globalj;
}
/*
* Dynamic validation of Time range exceptions fileds
*/
function purgeHideInput(tab) {
jQuery('.tab').each(function(idx, el){
if (el.id != tab) {
jQuery(el).find(':input').each(function(idx, input){
jQuery(input).qtip('destroy');
});
}
});
}
function formValidate() {
jQuery('#Form').centreonValidate();
jQuery('#Form').centreonValidate('validate');
if (jQuery('#Form').centreonValidate('hasError')) {
var activeTab = jQuery('.tab').filter(function(index) { return jQuery(this).css('display') === 'block'; })[0];
purgeHideInput(activeTab.id);
return false;
}
return true;
}
/*
* Global variables
*/
var globalj = 0;
var trExceptionClassFlag = 1;
var globalExceptionTabId = new Array();
var globalExceptionTabName = new Array();
var globalExceptionTabTimerange = new Array();
var globalExceptionTabTimeperiodId = new Array();
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/timeperiod/listTimeperiod.php | centreon/www/include/configuration/configObject/timeperiod/listTimeperiod.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include './include/common/autoNumLimit.php';
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchTP'] ?? $_GET['searchTP'] ?? null
);
if (isset($_POST['searchTP']) || isset($_GET['searchTP'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$SearchTool = '';
if ($search) {
$SearchTool .= " WHERE tp_name LIKE '%" . htmlentities($search, ENT_QUOTES, 'UTF-8') . "%'";
}
// Timeperiod list
$query = "SELECT SQL_CALC_FOUND_ROWS tp_id, tp_name, tp_alias FROM timeperiod {$SearchTool} "
. 'ORDER BY tp_name LIMIT ' . $num * $limit . ', ' . $limit;
$dbResult = $pearDB->query($query);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Description'));
$tpl->assign('headerMenu_options', _('Options'));
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
for ($i = 0; $timeperiod = $dbResult->fetch(); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $timeperiod['tp_id'] . ']');
$moptions .= ' <input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr["
. $timeperiod['tp_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => $timeperiod['tp_name'], 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&tp_id=' . $timeperiod['tp_id'], 'RowMenu_desc' => $timeperiod['tp_alias'], 'RowMenu_options' => $moptions, 'resultingLink' => 'main.php?p=' . $p . '&o=s&tp_id=' . $timeperiod['tp_id']];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. "if (this.form.elements['" . $option . "'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['" . $option . "'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 3) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. ''];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchTP', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listTimeperiod.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/timeperiod/DB-Func.php | centreon/www/include/configuration/configObject/timeperiod/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use App\Kernel;
if (! isset($centreon)) {
exit();
}
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Infrastructure\Common\Api\Router;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
function includeExcludeTimeperiods($tpId, $includeTab = [], $excludeTab = [])
{
global $pearDB;
// Insert inclusions
if (isset($includeTab) && is_array($includeTab)) {
$str = '';
foreach ($includeTab as $tpIncludeId) {
if ($str != '') {
$str .= ', ';
}
$str .= "('" . $tpId . "', '" . $tpIncludeId . "')";
}
if (strlen($str)) {
$query = 'INSERT INTO timeperiod_include_relations (timeperiod_id, timeperiod_include_id ) VALUES ' . $str;
$pearDB->query($query);
}
}
// Insert exclusions
if (isset($excludeTab) && is_array($excludeTab)) {
$str = '';
foreach ($excludeTab as $tpExcludeId) {
if ($str != '') {
$str .= ', ';
}
$str .= "('" . $tpId . "', '" . $tpExcludeId . "')";
}
if (strlen($str)) {
$query = 'INSERT INTO timeperiod_exclude_relations (timeperiod_id, timeperiod_exclude_id ) VALUES ' . $str;
$pearDB->query($query);
}
}
}
function testTPExistence($name = null)
{
global $pearDB, $form, $centreon;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('tp_id');
}
$query = 'SELECT tp_name, tp_id FROM timeperiod WHERE tp_name = :tp_name';
$statement = $pearDB->prepare($query);
$statement->bindValue(
':tp_name',
htmlentities($centreon->checkIllegalChar($name), ENT_QUOTES, 'UTF-8'),
PDO::PARAM_STR
);
$statement->execute();
$tp = $statement->fetch(PDO::FETCH_ASSOC);
// Modif case
if ($statement->rowCount() >= 1 && $tp['tp_id'] == $id) {
return true;
}
return ! ($statement->rowCount() >= 1 && $tp['tp_id'] != $id); // Duplicate entry
}
function multipleTimeperiodInDB($timeperiods = [], $nbrDup = [])
{
global $centreon;
foreach ($timeperiods as $key => $value) {
global $pearDB;
$fields = [];
$dbResult = $pearDB->query("SELECT * FROM timeperiod WHERE tp_id = '" . $key . "' LIMIT 1");
$query = "SELECT days, timerange FROM timeperiod_exceptions WHERE timeperiod_id = '" . $key . "'";
$res = $pearDB->query($query);
while ($row = $res->fetch()) {
foreach ($row as $keyz => $valz) {
$fields[$keyz] = $valz;
}
}
$row = $dbResult->fetch();
$row['tp_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = [];
foreach ($row as $key2 => $value2) {
if ($key2 == 'tp_name') {
$value2 .= '_' . $i;
}
if ($key2 == 'tp_name') {
$tp_name = $value2;
}
$val[] = $value2 ?: null;
if ($key2 != 'tp_id') {
$fields[$key2] = $value2;
}
if (isset($tp_name)) {
$fields['tp_name'] = $tp_name;
}
}
if (isset($tp_name) && testTPExistence($tp_name)) {
$params = [
'values' => $val,
'timeperiod_id' => $key,
];
$tpId = duplicateTimePeriod($params);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_TIMEPERIOD,
object_id: $tpId,
object_name: $tp_name,
action_type: ActionLog::ACTION_TYPE_ADD,
fields: $fields
);
}
}
}
}
/**
* Form validator.
* @param mixed $hourString
*/
function checkHours($hourString)
{
if ($hourString == '') {
return true;
}
if (strstr($hourString, ',')) {
$tab1 = preg_split("/\,/", $hourString);
for ($i = 0; isset($tab1[$i]); $i++) {
if (preg_match('/([0-9]*):([0-9]*)-([0-9]*):([0-9]*)/', $tab1[$i], $str)) {
if ($str[1] > 24 || $str[3] > 24) {
return false;
}
if ($str[2] > 59 || $str[4] > 59) {
return false;
}
if (($str[3] * 60 * 60 + $str[4] * 60) > 86400 || ($str[1] * 60 * 60 + $str[2] * 60) > 86400) {
return false;
}
} else {
return false;
}
}
return true;
}
if (preg_match('/([0-9]*):([0-9]*)-([0-9]*):([0-9]*)/', $hourString, $str)) {
if ($str[1] > 24 || $str[3] > 24) {
return false;
}
if ($str[2] > 59 || $str[4] > 59) {
return false;
}
return ! (($str[3] * 60 * 60 + $str[4] * 60) > 86400 || ($str[1] * 60 * 60 + $str[2] * 60) > 86400);
}
return false;
}
/**
* Get time period id by name
*
* @param string $name
* @return int
*/
function getTimeperiodIdByName($name)
{
global $pearDB;
$id = 0;
$res = $pearDB->query("SELECT tp_id FROM timeperiod WHERE tp_name = '" . $pearDB->escape($name) . "'");
if ($res->rowCount()) {
$row = $res->fetch();
$id = $row['tp_id'];
}
return $id;
}
/**
* Get chain of time periods via template relation
*
* @global \Pimple\Container $dependencyInjector
* @param array $tpIds List of selected time period as IDs
* @return array
*/
function getTimeperiodsFromTemplate(array $tpIds)
{
global $dependencyInjector;
$db = $dependencyInjector['centreon.db-manager'];
$result = [];
foreach ($tpIds as $tpId) {
$db->getRepository(Centreon\Domain\Repository\TimePeriodRepository::class)
->getIncludeChainByParent($tpId, $result);
}
return $result;
}
/**
* Validator prevent loops via template
*
* @global \HTML_QuickFormCustom $form Access to the form object
* @param array $value List of selected time period as IDs
* @return bool
*/
function testTemplateLoop($value)
{
// skip check if template field is empty
if (! $value) {
return true;
}
global $form;
$data = $form->getSubmitValues();
// skip check if timeperiod is new
if (! $data['tp_id']) {
return true;
}
if (in_array($data['tp_id'], $value)) {
// try to skip heavy check of templates
return false;
}
return ! (in_array($data['tp_id'], getTimeperiodsFromTemplate($value)));
// get list of all timeperiods related via templates
}
/**
* All in one function to duplicate time periods
*
* @param array $params
* @return int
*/
function duplicateTimePeriod(array $params): int
{
global $pearDB;
$isAlreadyInTransaction = $pearDB->inTransaction();
if (! $isAlreadyInTransaction) {
$pearDB->beginTransaction();
}
try {
$params['tp_id'] = createTimePeriod($params);
createTimePeriodsExceptions($params);
createTimePeriodsIncludeRelations($params);
createTimePeriodsExcludeRelations($params);
if (! $isAlreadyInTransaction) {
$pearDB->commit();
}
} catch (Exception $e) {
if (! $isAlreadyInTransaction) {
$pearDB->rollBack();
}
}
return $params['tp_id'];
}
/**
* Creates time period and returns id.
*
* @param array $params
* @return int
*/
function createTimePeriod(array $params): int
{
global $pearDB;
$queryBindValues = [];
foreach ($params['values'] as $index => $value) {
$queryBindValues[':value_' . $index] = $value;
}
$bindValues = implode(', ', array_keys($queryBindValues));
$statement = $pearDB->prepare("INSERT INTO timeperiod VALUES ({$bindValues})");
foreach ($queryBindValues as $bindKey => $bindValue) {
if (array_key_first($queryBindValues) === $bindKey) {
$statement->bindValue($bindKey, (int) $bindValue, PDO::PARAM_INT);
} else {
$statement->bindValue($bindKey, $bindValue, PDO::PARAM_STR);
}
}
$statement->execute();
return (int) $pearDB->lastInsertId();
}
/**
* Creates time periods exclude relations
*
* @param array $params
*/
function createTimePeriodsExcludeRelations(array $params): void
{
global $pearDB;
$query = 'INSERT INTO timeperiod_exclude_relations (timeperiod_id, timeperiod_exclude_id) '
. 'SELECT :tp_id, timeperiod_exclude_id FROM timeperiod_exclude_relations '
. 'WHERE timeperiod_id = :timeperiod_id';
$statement = $pearDB->prepare($query);
$statement->bindValue(':tp_id', $params['tp_id'], PDO::PARAM_INT);
$statement->bindValue(':timeperiod_id', (int) $params['timeperiod_id'], PDO::PARAM_INT);
$statement->execute();
}
/**
* Creates time periods include relations
*
* @param array $params
*/
function createTimePeriodsIncludeRelations(array $params): void
{
global $pearDB;
$query = 'INSERT INTO timeperiod_include_relations (timeperiod_id, timeperiod_include_id) '
. 'SELECT :tp_id, timeperiod_include_id FROM timeperiod_include_relations '
. 'WHERE timeperiod_id = :timeperiod_id';
$statement = $pearDB->prepare($query);
$statement->bindValue(':tp_id', $params['tp_id'], PDO::PARAM_INT);
$statement->bindValue(':timeperiod_id', (int) $params['timeperiod_id'], PDO::PARAM_INT);
$statement->execute();
}
/**
* Creates time periods exceptions
*
* @param array $params
*/
function createTimePeriodsExceptions(array $params): void
{
global $pearDB;
$query = 'INSERT INTO timeperiod_exceptions (timeperiod_id, days, timerange) '
. 'SELECT :tp_id, days, timerange FROM timeperiod_exceptions '
. 'WHERE timeperiod_id = :timeperiod_id';
$statement = $pearDB->prepare($query);
$statement->bindValue(':tp_id', $params['tp_id'], PDO::PARAM_INT);
$statement->bindValue(':timeperiod_id', (int) $params['timeperiod_id'], PDO::PARAM_INT);
$statement->execute();
}
// ----------------- API CALLS --------------------
/**
* Create a new timeperiod form formData.
*
* @param array<mixed> $ret
*
* @return int|null
*/
function insertTimePeriodInAPI(array $ret = []): int|null
{
global $form, $basePath;
$formData = $ret === [] ? $form->getSubmitValues() : $ret;
try {
return insertTimeperiodByApi($formData, $basePath);
} catch (Throwable $th) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error while inserting timeperiod by api : {$th->getMessage()}",
customContext: ['form_data' => $formData, 'base_path' => $basePath],
exception: $th
);
echo "<div class='msg' align='center'>" . _($th->getMessage()) . '</div>';
return null;
}
}
/**
* Make the API request to create a new timeeperiod and return the new ID.
*
* @param array $formData
* @param string $basePath
*
* @throws Throwable
*
* @return int
*/
function insertTimeperiodByApi(array $formData, string $basePath): int
{
$kernel = Kernel::createForWeb();
/** @var Router $router */
$router = $kernel->getContainer()->get(Router::class);
$client = new CurlHttpClient();
$payload = getPayloadForTimePeriod($formData);
$url = $router->generate(
'AddTimePeriod',
$basePath ? ['base_uri' => $basePath] : [],
UrlGeneratorInterface::ABSOLUTE_URL,
);
$headers = [
'Content-Type' => 'application/json',
'Cookie' => CentreonSession::resolveSessionCookie(),
];
$response = $client->request(
'POST',
$url,
[
'headers' => $headers,
'body' => json_encode(value: $payload, flags: JSON_THROW_ON_ERROR),
],
);
if ($response->getStatusCode() !== 201) {
$content = json_decode(json: $response->getContent(false), flags: JSON_THROW_ON_ERROR);
throw new Exception($content->message ?? 'Unexpected return status');
}
$data = $response->toArray();
/** @var array{id:int} $data */
return $data['id'];
}
/**
* Update a timeperiod.
*
* @param mixed $tp_id
*
* @return bool
*/
function updateTimeperiodInAPI($tp_id = null): bool
{
if (! $tp_id) {
return true;
}
global $form, $basePath;
$formData = $form->getSubmitValues();
try {
updateTimeperiodByApi($formData, $basePath);
return true;
} catch (Throwable $th) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error while updating timeperiod by api : {$th->getMessage()}",
customContext: ['form_data' => $formData, 'base_path' => $basePath],
exception: $th
);
echo "<div class='msg' align='center'>" . _($th->getMessage()) . '</div>';
return false;
}
}
/**
* Make the API request to update a timeeperiod .
* @param array $formData
* @param string $basePath
*
* @throws Throwable
*
* @return void
*/
function updateTimeperiodByApi(array $formData, string $basePath): void
{
$kernel = Kernel::createForWeb();
/** @var Router $router */
$router = $kernel->getContainer()->get(Router::class);
$client = new CurlHttpClient();
$payload = getPayloadForTimePeriod($formData);
$url = $router->generate(
'UpdateTimePeriod',
$basePath ? ['base_uri' => $basePath, 'id' => $formData['tp_id']] : [],
UrlGeneratorInterface::ABSOLUTE_URL,
);
$headers = [
'Content-Type' => 'application/json',
'Cookie' => CentreonSession::resolveSessionCookie(),
];
$response = $client->request(
'PUT',
$url,
[
'headers' => $headers,
'body' => json_encode(value: $payload, flags: JSON_THROW_ON_ERROR),
],
);
if ($response->getStatusCode() !== 204) {
$content = json_decode(json: $response->getContent(false), flags: JSON_THROW_ON_ERROR);
throw new Exception($content->message ?? 'Unexpected return status');
}
}
/**
* @param int[] $timeperiods
*
* @return bool
*/
function deleteTimePeriodInAPI(array $timeperiods = []): bool
{
global $basePath;
try {
deleteTimeperiodByApi($basePath, $timeperiods);
return true;
} catch (Throwable $th) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error while deleting timeperiod by api : {$th->getMessage()}",
customContext: ['timeperiods' => $timeperiods, 'base_path' => $basePath],
exception: $th
);
echo "<div class='msg' align='center'>" . _($th->getMessage()) . '</div>';
return false;
}
}
/**
* @param string $basePath
* @param int[] $timePeriodIds
*
* @throws Throwable
*/
function deleteTimePeriodByAPI(string $basePath, array $timePeriodIds): void
{
$kernel = Kernel::createForWeb();
/** @var Router $router */
$router = $kernel->getContainer()->get(Router::class);
$client = new CurlHttpClient();
$headers = [
'Content-Type' => 'application/json',
'Cookie' => CentreonSession::resolveSessionCookie(),
];
foreach ($timePeriodIds as $id) {
$url = $router->generate(
'DeleteTimePeriod',
$basePath ? ['base_uri' => $basePath, 'id' => $id] : [],
UrlGeneratorInterface::ABSOLUTE_URL,
);
$response = $client->request('DELETE', $url, ['headers' => $headers]);
if ($response->getStatusCode() !== 204) {
$content = json_decode($response->getContent(false), true);
$message = $content['message'] ?? 'Unknown error';
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error while deleting timeperiod by API : {$message}",
customContext: ['timeperiod_id' => $id]
);
}
}
}
/**
* @param array<mixed> $formData
*
* @return array<string,mixed>
*/
function getPayloadForTimePeriod(array $formData): array
{
$days = [];
$exceptions = [];
$weekDays = [
'tp_monday' => 1,
'tp_tuesday' => 2,
'tp_wednesday' => 3,
'tp_thursday' => 4,
'tp_friday' => 5,
'tp_saturday' => 6,
'tp_sunday' => 7,
];
foreach ($formData as $name => $value) {
if (str_starts_with($name, 'exceptionInput_')) {
$exceptions[] = [
'day_range' => $value,
'time_range' => $formData[str_replace('Input', 'Timerange', $name)],
];
}
if (in_array($name, array_keys($weekDays), true) && $value !== '') {
$days[] = ['day' => $weekDays[$name], 'time_range' => $value];
}
}
return [
'name' => $formData['tp_name'],
'alias' => $formData['tp_alias'],
'days' => $days,
'templates' => array_map(static fn (string $id): int => (int) $id, $formData['tp_include'] ?? []),
'exceptions' => $exceptions,
];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/connector/listConnector.php | centreon/www/include/configuration/configObject/connector/listConnector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
include_once './class/centreonUtils.class.php';
include_once './include/common/autoNumLimit.php';
// restoring the pagination if we stay on this menu
$num = 0;
if ($centreon->historyLastUrl === $url && isset($_GET['num'])) {
$num = $_GET['num'];
}
try {
$connectorsList = $connectorObj->getList(false, (int) $num, (int) $limit);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign('mode_access', $lvl_access);
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['" . $option . "'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['" . $option . "'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 3) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "this.form.elements['" . $option . "'].selectedIndex = 0"];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
$elemArr = [];
$j = 0;
$attrsText = ['size' => '2'];
$nbConnectors = count($connectorsList);
$centreonToken = createCSRFToken();
for ($i = 0; $i < $nbConnectors; $i++) {
$result = $connectorsList[$i];
$moptions = '';
$MyOption = $form->addElement('text', 'options[' . $result['id'] . ']', _('Options'), $attrsText);
$form->setDefaults(['options[' . $result['id'] . ']' => '1']);
$selectedElements = $form->addElement('checkbox', 'select[' . $result['id'] . ']');
if ($result) {
if ($lvl_access == 'w') {
if ($result['enabled']) {
$moptions = "<a href='main.php?p="
. $p . '&id=' . $result['id'] . '&o=u&limit=' . $limit . '&num=' . $num
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Disabled') . "'></a> ";
} else {
$moptions = "<a href='main.php?p="
. $p . '&id=' . $result['id'] . '&o=s&limit=' . $limit . '&num=' . $num
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Enabled') . "'></a> ";
}
$moptions .= ' '
. '<input onKeypress="if(event.keyCode > 31 '
. '&& (event.keyCode < 45 || event.keyCode > 57)) event.returnValue = false;'
. ' if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;"'
. " maxlength=\"3\" size=\"3\" value='1'"
. " style=\"margin-bottom:0px;\" name='options[" . $result['id'] . "]'></input>";
$moptions .= ' ';
} else {
$moptions = ' ';
}
$elemArr[$j] = ['RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&id=' . $result['id'], 'RowMenu_name' => CentreonUtils::escapeSecure($result['name']), 'RowMenu_description' => CentreonUtils::escapeSecure($result['description']), 'RowMenu_command_line' => CentreonUtils::escapeSecure($result['command_line']), 'RowMenu_enabled' => $result['enabled'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $result['enabled'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
}
$j++;
}
/**
* @todo implement
*/
$rows = $connectorObj->count(false);
include_once './include/common/checkPagination.php';
$tpl->assign('elemArr', $elemArr);
$tpl->assign('p', $p);
$tpl->assign('connectorsList', $connectorsList);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('limit', $limit);
$tpl->display('listConnector.ihtml');
} catch (Exception $e) {
echo 'Erreur n°' . $e->getCode() . ' : ' . $e->getMessage();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/connector/help.php | centreon/www/include/configuration/configObject/connector/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['connector_name'] = dgettext('help', 'Name which will be used for identifying the connector.');
$help['connector_description'] = dgettext('help', 'A short description of the connector.');
$help['command_line'] = dgettext('help', 'The connector binary that centreon-engine will launch.');
$help['connector_status'] = dgettext('help', 'Whether or not the connector is enabled.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/connector/connector.php | centreon/www/include/configuration/configObject/connector/connector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonConnector.class.php';
$path = _CENTREON_PATH_ . 'www/include/configuration/configObject/connector/';
require_once $path . 'DB-Func.php';
$connectorObj = new CentreonConnector($pearDB);
if (isset($_REQUEST['select'])) {
$select = $_REQUEST['select'];
}
if (isset($_REQUEST['id'])) {
$connector_id = $_REQUEST['id'];
}
if (isset($_REQUEST['options'])) {
$options = $_REQUEST['options'];
}
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
switch ($o) {
case 'a':
require_once $path . 'formConnector.php';
break;
case 'w':
require_once $path . 'formConnector.php';
break;
case 'c':
require_once $path . 'formConnector.php';
break;
case 's':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($lvl_access == 'w') {
$myConnector = $connectorObj->read($connector_id);
$myConnector['enabled'] = '1';
$connectorObj->update((int) $connector_id, $myConnector);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listConnector.php';
break;
case 'u':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($lvl_access == 'w') {
$myConnector = $connectorObj->read($connector_id);
$myConnector['enabled'] = '0';
$connectorObj->update((int) $connector_id, $myConnector);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listConnector.php';
break;
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($lvl_access == 'w') {
$selectedConnectors = array_keys($select);
foreach ($selectedConnectors as $connectorId) {
$connectorObj->copy($connectorId, (int) $options[$connectorId]);
}
}
} else {
unvalidFormMessage();
}
require_once $path . 'listConnector.php';
break;
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if ($lvl_access == 'w') {
$selectedConnectors = array_keys($select);
foreach ($selectedConnectors as $connectorId) {
$connectorObj->delete($connectorId);
}
}
} else {
unvalidFormMessage();
}
require_once $path . 'listConnector.php';
break;
default:
require_once $path . 'listConnector.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/connector/formConnector.php | centreon/www/include/configuration/configObject/connector/formConnector.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once __DIR__ . '/formConnectorFunction.php';
try {
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$cnt = [];
if (($o == 'c' || $o == 'w') && isset($connector_id)) {
$cnt = $connectorObj->read((int) $connector_id);
$cnt['connector_name'] = $cnt['name'];
$cnt['connector_description'] = $cnt['description'];
$cnt['command_line'] = $cnt['command_line'];
$cnt['connector_status'] = $cnt['enabled'] ? '1' : '0';
$cnt['connector_id'] = $cnt['id'];
unset($cnt['name'], $cnt['description'], $cnt['status'], $cnt['id']);
}
// Resource Macro
$resource = [];
$DBRESULT = $pearDB->query('SELECT DISTINCT `resource_name`, `resource_comment`
FROM `cfg_resource`
ORDER BY `resource_name`');
while ($row = $DBRESULT->fetchRow()) {
$resource[$row['resource_name']] = $row['resource_name'];
if (isset($row['resource_comment']) && $row['resource_comment'] != '') {
$resource[$row['resource_name']] .= ' (' . $row['resource_comment'] . ')';
}
}
unset($row);
$DBRESULT->closeCursor();
// Nagios Macro
$macros = [];
$DBRESULT = $pearDB->query('SELECT `macro_name` FROM `nagios_macro` ORDER BY `macro_name`');
while ($row = $DBRESULT->fetchRow()) {
$macros[$row['macro_name']] = $row['macro_name'];
}
unset($row);
$DBRESULT->closeCursor();
$availableConnectors_list = return_plugin(($oreon->optGen['cengine_path_connectors'] ?? null));
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$form->addElement('header', 'information', _('General information'));
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a Connector'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a Connector'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a Connector'));
}
$attrsText = ['size' => '35'];
$attrsTextarea = ['rows' => '9', 'cols' => '65', 'id' => 'command_line'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 100px;'];
$attrCommands = ['datasourceOrigin' => 'ajax', 'multiple' => true, 'defaultDatasetRoute' => './include/common/webServices/rest/internal.php?'
. 'object=centreon_configuration_command&action=defaultValues&target=connector&field=command_id&id='
. ($connector_id ?? ''), 'availableDatasetRoute' => './include/common/webServices/rest/internal.php?'
. 'object=centreon_configuration_command&action=list', 'linkedObject' => 'centreonCommand'];
$form->addElement('text', 'connector_name', _('Connector Name'), $attrsText);
$form->addElement('text', 'connector_description', _('Connector Description'), $attrsText);
$form->addElement('textarea', 'command_line', _('Command Line'), $attrsTextarea);
$form->addElement('select', 'resource', null, $resource);
$form->addElement('select', 'macros', null, $macros);
ksort($availableConnectors_list);
$form->addElement('select', 'plugins', null, $availableConnectors_list);
$form->addElement('select2', 'command_id', _('Used by command'), [], $attrCommands);
$cntStatus = [];
$cntStatus[] = $form->createElement('radio', 'connector_status', null, _('Enabled'), '1');
$cntStatus[] = $form->createElement('radio', 'connector_status', null, _('Disabled'), '0');
$form->addGroup($cntStatus, 'connector_status', _('Connector Status'), ' ');
if (isset($cnt['connector_status']) && is_numeric($cnt['connector_status'])) {
$form->setDefaults(['connector_status' => $cnt['connector_status']]);
} else {
$form->setDefaults(['connector_status' => '0']);
}
if ($o == 'w') {
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p="
. $p . '&o=c&connector_id=' . $connector_id . '&status=' . $status . "'"]
);
}
$form->setDefaults($cnt);
$form->freeze();
} elseif ($o == 'c') {
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($cnt);
} elseif ($o == 'a') {
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$form->addRule('connector_name', _('Name'), 'required');
$form->addRule('command_line', _('Command Line'), 'required');
$form->registerRule('exist', 'callback', 'testConnectorExistence');
$form->addRule('connector_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
$form->addElement('hidden', 'connector_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$valid = false;
if ($form->validate()) {
$cntObj = new CentreonConnector($pearDB);
$tab = $form->getSubmitValues();
$connectorValues = [];
$connectorValues['name'] = $tab['connector_name'];
$connectorValues['description'] = $tab['connector_description'];
$connectorValues['enabled'] = $tab['connector_status']['connector_status'] === '0' ? 0 : 1;
$connectorValues['command_id'] = $tab['command_id'] ?? null;
$connectorValues['command_line'] = $tab['command_line'];
$connectorId = (int) $tab['connector_id'];
if (! empty($connectorValues['name'])) {
if ($form->getSubmitValue('submitA')) {
$connectorId = $cntObj->create($connectorValues, true);
} elseif ($form->getSubmitValue('submitC')) {
$cntObj->update($connectorId, $connectorValues);
}
$valid = true;
}
}
if ($valid) {
require_once $path . 'listConnector.php';
} else {
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange",'
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH,'
. '-300, SHADOW, true, TEXTALIGN, "justify"'
);
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$tpl->display('formConnector.ihtml');
}
} catch (Exception $e) {
echo 'Erreur n°' . $e->getCode() . ' : ' . $e->getMessage();
}
?>
<script type='text/javascript'>
<!--
function insertValueQuery(elem)
{
var myQuery = document.Form.command_line;
if(elem == 1)
var myListBox = document.Form.resource;
else if (elem == 2)
var myListBox = document.Form.plugins;
else if (elem == 3)
var myListBox = document.Form.macros;
if (myListBox.options.length > 0)
{
var chaineAj = '';
var NbSelect = 0;
for (var i=0; i<myListBox.options.length; i++)
{
if (myListBox.options[i].selected)
{
NbSelect++;
if (NbSelect > 1)
chaineAj += ', ';
chaineAj += myListBox.options[i].value;
}
}
if (document.selection)
{
// IE support
myQuery.focus();
sel = document.selection.createRange();
sel.text = chaineAj;
document.Form.insert.focus();
}
else if (document.Form.command_line.selectionStart || document.Form.command_line.selectionStart == '0')
{
// MOZILLA/NETSCAPE support
var startPos = document.Form.command_line.selectionStart;
var endPos = document.Form.command_line.selectionEnd;
var chaineSql = document.Form.command_line.value;
myQuery.value = chaineSql.substring(0, startPos)
+ chaineAj
+ chaineSql.substring(endPos, chaineSql.length);
}
else
myQuery.value += chaineAj;
}
}
//-->
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/connector/DB-Func.php | centreon/www/include/configuration/configObject/connector/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
function testConnectorExistence($name = null)
{
global $connectorObj, $form;
$id = isset($form) ? $form->getSubmitValue('connector_id') : null;
return $connectorObj->isNameAvailable($name, $id);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/connector/formConnectorFunction.php | centreon/www/include/configuration/configObject/connector/formConnectorFunction.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
function return_plugin($rep)
{
global $centreon;
$availableConnectors = [];
$is_not_a_plugin = ['.' => 1, '..' => 1, 'oreon.conf' => 1, 'oreon.pm' => 1, 'utils.pm' => 1, 'negate' => 1, 'centreon.conf' => 1, 'centreon.pm' => 1];
if (is_readable($rep)) {
$handle[$rep] = opendir($rep);
while (false != ($filename = readdir($handle[$rep]))) {
if ($filename != '.' && $filename != '..') {
if (is_dir($rep . $filename)) {
$plg_tmp = return_plugin($rep . '/' . $filename);
$availableConnectors = array_merge($availableConnectors, $plg_tmp);
unset($plg_tmp);
} elseif (! isset($is_not_a_plugin[$filename])
&& ! str_ends_with($filename, '~')
&& ! str_ends_with($filename, '#')
) {
if (isset($oreon)) {
$key = substr($rep . '/' . $filename, strlen($oreon->optGen['cengine_path_connectors']));
} else {
$key = substr($rep . '/' . $filename, 0);
}
$availableConnectors[$key] = $key;
}
}
}
closedir($handle[$rep]);
}
return $availableConnectors;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_template_model/hostTemplateModel.php | centreon/www/include/configuration/configObject/host_template_model/hostTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$hostId = filter_var(
$_GET['host_id'] ?? $_POST['host_id'] ?? null,
FILTER_VALIDATE_INT
);
// Path to the configuration dir
$path = './include/configuration/configObject/host_template_model/';
$hostConfigurationPath = './include/configuration/configObject/host/';
// PHP functions
require_once $hostConfigurationPath . 'DB-Func.php';
require_once './include/common/common-Func.php';
global $isCloudPlatform;
$isCloudPlatform = isCloudPlatform();
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
$hostObj = new CentreonHost($pearDB);
$lockedElements = $hostObj->getLockedHostTemplates();
// Set the real page
if (
isset($ret)
&& is_array($ret)
&& $ret['topology_page'] !== ''
&& $p !== $ret['topology_page']
) {
$p = $ret['topology_page'];
}
const HOST_TEMPLATE_ADD = 'a',
HOST_TEMPLATE_WATCH = 'w',
HOST_TEMPLATE_MODIFY = 'c',
HOST_TEMPLATE_MASSIVE_CHANGE = 'mc',
HOST_TEMPLATE_ACTIVATION = 's',
HOST_TEMPLATE_MASSIVE_ACTIVATION = 'ms',
HOST_TEMPLATE_DEACTIVATION = 'u',
HOST_TEMPLATE_MASSIVE_DEACTIVATION = 'mu',
HOST_TEMPLATE_DUPLICATION = 'm',
HOST_TEMPLATE_DELETION = 'd';
switch ($o) {
case HOST_TEMPLATE_ADD:
case HOST_TEMPLATE_WATCH:
case HOST_TEMPLATE_MODIFY:
case HOST_TEMPLATE_MASSIVE_CHANGE:
require_once $path . 'formHostTemplateModel.php';
break;
case HOST_TEMPLATE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableHostInDB($hostId);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostTemplateModel.php';
break;
case HOST_TEMPLATE_MASSIVE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableHostInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostTemplateModel.php';
break;
case HOST_TEMPLATE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableHostInDB($hostId);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostTemplateModel.php';
break;
case HOST_TEMPLATE_MASSIVE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableHostInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostTemplateModel.php';
break;
case HOST_TEMPLATE_DUPLICATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleHostInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostTemplateModel.php';
break;
case HOST_TEMPLATE_DELETION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteHostInApi(hosts: is_array($select) ? array_keys($select) : [], isTemplate: true);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostTemplateModel.php';
break;
default:
require_once $path . 'listHostTemplateModel.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_template_model/listHostTemplateModel.php | centreon/www/include/configuration/configObject/host_template_model/listHostTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
// Init Host Method
$host_method = new CentreonHost($pearDB);
$mediaObj = new CentreonMedia($pearDB);
// Get Extended informations
$ehiCache = [];
$DBRESULT = $pearDB->query('SELECT ehi_icon_image, host_host_id FROM extended_host_information');
while ($ehi = $DBRESULT->fetch()) {
$ehiCache[$ehi['host_host_id']] = $ehi['ehi_icon_image'];
}
$DBRESULT->closeCursor();
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchHT'] ?? $_GET['searchHT'] ?? $centreon->historySearch[$url]['search'] ?? ''
);
$displayLocked = filter_var(
$_POST['displayLocked'] ?? $_GET['displayLocked'] ?? 'off',
FILTER_VALIDATE_BOOLEAN
);
// keep checkbox state if navigating in pagination
// this trick is mandatory cause unchecked checkboxes do not post any data
if (
(isset($centreon->historyPage[$url]) && $centreon->historyPage[$url] > 0 || $num !== 0)
&& isset($centreon->historySearch[$url]['displayLocked'])
) {
$displayLocked = $centreon->historySearch[$url]['displayLocked'];
}
// store filters in session
$centreon->historySearch[$url] = [
'search' => $search,
'displayLocked' => $displayLocked,
];
// Locked filter
$lockedFilter = $displayLocked ? '' : 'AND host_locked = 0 ';
// Host Template list
$rq = 'SELECT SQL_CALC_FOUND_ROWS host_id, host_name, host_alias, host_template_model_htm_id '
. 'FROM host '
. "WHERE host_register = '0' "
. $lockedFilter;
if ($search) {
$rq .= "AND (host_name LIKE '%" . CentreonDB::escape($search) . "%' OR host_alias LIKE '%"
. CentreonDB::escape($search) . "%')";
}
$rq .= ' ORDER BY host_name LIMIT ' . $num * $limit . ', ' . $limit;
$DBRESULT = $pearDB->query($rq);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Alias'));
$tpl->assign('headerMenu_svChilds', _('Linked Services Templates'));
$tpl->assign('headerMenu_parent', _('Templates'));
$tpl->assign('headerMenu_options', _('Options'));
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $host = $DBRESULT->fetch(); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $host['host_id'] . ']');
if (isset($lockedElements[$host['host_id']])) {
$selectedElements->setAttribute('disabled', 'disabled');
} else {
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) '
. "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" "
. "name='dupNbr[" . $host['host_id'] . "]' />";
}
// If the name of our Host Model is in the Template definition, we have to catch it, whatever the level of it :-)
if (! $host['host_name']) {
$host['host_name'] = getMyHostName($host['host_template_model_htm_id']);
}
// TPL List
$tplArr = [];
$tplStr = null;
$tplArr = getMyHostMultipleTemplateModels($host['host_id']);
if (count($tplArr)) {
$firstTpl = 1;
foreach ($tplArr as $key => $value) {
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
if ($firstTpl) {
$tplStr .= "<a href='main.php?p=60103&o=c&host_id=" . $key . "'>" . $value . '</a>';
$firstTpl = 0;
} else {
$tplStr .= " | <a href='main.php?p=60103&o=c&host_id=" . $key . "'>" . $value . '</a>';
}
}
}
// Check icon
$isHostTemplateSvgFile = true;
if ((isset($ehiCache[$host['host_id']]) && $ehiCache[$host['host_id']])) {
$isHostTemplateSvgFile = false;
$host_icone = './img/media/' . $mediaObj->getFilename($ehiCache[$host['host_id']]);
} elseif (
$icone = $host_method->replaceMacroInString(
$host['host_id'],
getMyHostExtendedInfoImage($host['host_id'], 'ehi_icon_image', 1)
)
) {
$isHostTemplateSvgFile = false;
$host_icone = './img/media/' . $icone;
} else {
$isHostTemplateSvgFile = true;
$host_icone = returnSvg('www/img/icons/host.svg', 'var(--icons-fill-color)', 16, 16);
}
// Service List
$svArr = [];
$svStr = null;
$svArr = getMyHostServices($host['host_id']);
$elemArr[$i] = [
'MenuClass' => 'list_' . $style,
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => $host['host_name'],
'RowMenu_link' => 'main.php?p=' . $p . '&o=c&host_id=' . $host['host_id'],
'RowMenu_desc' => $host['host_alias'],
'RowMenu_icone' => $host_icone,
'RowMenu_svChilds' => count($svArr),
'RowMenu_parent' => CentreonUtils::escapeSecure($tplStr),
'RowMenu_options' => $moptions,
'isHostTemplateSvgFile' => $isHostTemplateSvgFile,
];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</SCRIPT>
<?php
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. 'var bChecked = isChecked();'
. "if (this.form.elements['{$option}'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['{$option}'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['{$option}'].value); submit();} "
. "else if (this.form.elements['{$option}'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['{$option}'].value); submit();} "
. "else if (this.form.elements['{$option}'].selectedIndex == 3 || "
. "this.form.elements['{$option}'].selectedIndex == 4 || this.form.elements['{$option}'].selectedIndex == 5){"
. " setO(this.form.elements['{$option}'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change')],
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
$tpl->assign('limit', $limit);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('searchHT', $search);
$tpl->assign('displayLocked', $displayLocked);
$tpl->display('listHostTemplateModel.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_template_model/formHostTemplateModel.php | centreon/www/include/configuration/configObject/host_template_model/formHostTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if ($isCloudPlatform) {
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
}
const PASSWORD_REPLACEMENT_VALUE = '**********';
const BASE_ROUTE = './include/common/webServices/rest/internal.php';
$datasetRoutes = [
'timeperiods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=list',
'default_check_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=host&field=timeperiod_tp_id&id=' . $hostId,
'default_notification_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=host&field=timeperiod_tp_id2&id=' . $hostId,
'hosts' => BASE_ROUTE . '?object=centreon_configuration_host&action=list',
'default_host_parents' => BASE_ROUTE . '?object=centreon_configuration_host&action=defaultValues&target=host&field=host_parents&id=' . $hostId,
'default_host_child' => BASE_ROUTE . '?object=centreon_configuration_host&action=defaultValues&target=host&field=host_childs&id=' . $hostId,
'host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=list',
'default_host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=defaultValues&target=host&field=host_hgs&id=' . $hostId,
'host_categories' => BASE_ROUTE . '?object=centreon_configuration_hostcategory&action=list&t=c',
'default_host_categories' => BASE_ROUTE . '?object=centreon_configuration_hostcategory&action=defaultValues&target=host&field=host_hcs&id=' . $hostId,
'default_contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=defaultValues&target=host&field=host_cs&id=' . $hostId,
'contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=list',
'default_contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=defaultValues&target=host&field=host_cgs&id=' . $hostId,
'contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=list',
'default_timezones' => BASE_ROUTE . '?object=centreon_configuration_timezone&action=defaultValues&target=host&field=host_location&id=' . $hostId,
'timezones' => BASE_ROUTE . '?object=centreon_configuration_timezone&action=list',
'default_commands' => BASE_ROUTE . '?object=centreon_configuration_comman&action=defaultValues&target=host&field=command_command_id&id=' . $hostId,
'check_commands' => BASE_ROUTE . '?object=centreon_configuration_command&action=list&t=2',
'event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=list',
'default_event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=defaultValues&target=host&field=command_command_id2&id=' . $hostId,
'default_acl_groups' => BASE_ROUTE . '?object=centreon_administration_aclgroup&action=defaultValues&target=host&field=acl_groups&id=' . $hostId,
'acl_groups' => BASE_ROUTE . '?object=centreon_administration_aclgroup&action=list',
'service_templates' => BASE_ROUTE . '?object=centreon_configuration_servicetemplate&action=list',
'default_service_templates' => BASE_ROUTE . '?object=centreon_configuration_servicetemplate&action=defaultValues&target=host&field=host_svTpls&id=' . $hostId,
];
$attributes = [
'check_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_check_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'notification_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_notification_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'host_parents' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['hosts'],
'defaultDatasetRoute' => $datasetRoutes['default_host_parents'],
'multiple' => true,
'linkedObject' => 'centreonHost',
],
'host_child' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['hosts'],
'defaultDatasetRoute' => $datasetRoutes['default_host_child'],
'multiple' => true,
'linkedObject' => 'centreonHost',
],
'host_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['host_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_host_groups'],
'multiple' => true,
'linkedObject' => 'centreonHostgroups',
],
'host_categories' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['host_categories'],
'defaultDatasetRoute' => $datasetRoutes['default_host_categories'],
'multiple' => true,
'linkedObject' => 'centreonHostcategories',
],
'contacts' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contacts'],
'defaultDatasetRoute' => $datasetRoutes['default_contacts'],
'multiple' => true,
'linkedObject' => 'centreonContact',
],
'contact_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contact_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_contact_groups'],
'multiple' => true,
'linkedObject' => 'centreonContactgroup',
],
'timezones' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timezones'],
'defaultDatasetRoute' => $datasetRoutes['default_timezones'],
'multiple' => false,
'linkedObject' => 'centreonGMT',
],
'check_commands' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_commands'],
'availableDatasetRoute' => $datasetRoutes['check_commands'],
],
'event_handlers' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_event_handlers'],
'availableDatasetRoute' => $datasetRoutes['event_handlers'],
],
'acl_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['acl_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_acl_groups'],
'multiple' => true,
],
'service_templates' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['service_templates'],
'defaultDatasetRoute' => $datasetRoutes['default_service_templates'],
'multiple' => true,
'linkedObject' => 'centreonServicetemplates',
],
];
$hostObj = new CentreonHost($pearDB);
$hTpls ??= [];
//
// # Database retrieve information for Host
//
$host = [];
$macroArray = [];
// Used to store all macro passwords
$macroPasswords = [];
if (($o === HOST_TEMPLATE_MODIFY || $o === HOST_TEMPLATE_WATCH) && isset($hostId)) {
if (isset($lockedElements[$hostId])) {
$o = HOST_TEMPLATE_WATCH;
}
$statement = $pearDB->prepare(
'SELECT * FROM host
INNER JOIN extended_host_information ehi
ON ehi.host_host_id = host.host_id
WHERE host_id = :host_id LIMIT 1'
);
$statement->bindValue(':host_id', $hostId, PDO::PARAM_INT);
$statement->execute();
// Set base value
if ($statement->rowCount()) {
$host = array_map('myDecode', $statement->fetch());
if (! empty($host['host_snmp_community'])) {
$host['host_snmp_community'] = PASSWORD_REPLACEMENT_VALUE;
}
$cmdId = $host['command_command_id'];
// Set Host Notification Options
$tmp = explode(',', $host['host_notification_options']);
foreach ($tmp as $key => $value) {
$host['host_notifOpts'][trim($value)] = 1;
}
// Set criticality
$statement = $pearDB->prepare(
'SELECT hc.hc_id
FROM hostcategories hc
INNER JOIN hostcategories_relation hcr
ON hcr.hostcategories_hc_id = hc.hc_id
WHERE hcr.host_host_id = :host_id AND hc.level IS NOT NULL
ORDER BY hc.level ASC LIMIT 1'
);
$statement->bindValue(':host_id', $hostId, PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount()) {
$cr = $statement->fetch();
$host['criticality_id'] = $cr['hc_id'];
}
}
// Preset values of macros
$aTemplates = $hostObj->getTemplateChain($hostId, [], -1);
if (! isset($cmdId)) {
$cmdId = '';
}
if (isset($_REQUEST['macroInput'])) {
/**
* We don't taking into account the POST data sent from the interface in order the retrieve the original value
* of all passwords.
*/
$macroArray = $hostObj->getMacros($hostId, $aTemplates, $cmdId);
/**
* If a password has been modified from the interface, we retrieve the old password existing in the repository
* (giving by the $aMacros variable) to inject it before saving.
* Passwords will be saved using the $_REQUEST variable.
*/
foreach ($_REQUEST['macroInput'] as $index => $macroName) {
if (
! isset($_REQUEST['macroFrom'][$index])
|| ! isset($_REQUEST['macroPassword'][$index])
|| $_REQUEST['macroPassword'][$index] !== '1' // Not a password
|| $_REQUEST['macroValue'][$index] !== PASSWORD_REPLACEMENT_VALUE // The password has not changed
) {
continue;
}
foreach ($macroArray as $macroAlreadyExist) {
if (
$macroAlreadyExist['macroInput_#index#'] === $macroName
&& $_REQUEST['macroFrom'][$index] === $macroAlreadyExist['source']
) {
/**
* if the password has not been changed, we replace the password coming from the interface with
* the original value (from the repository) before saving.
*/
$_REQUEST['macroValue'][$index] = $macroAlreadyExist['macroValue_#index#'];
}
}
}
}
$macroArray = $hostObj->getMacros($hostId, $aTemplates, $cmdId, $_POST);
// We hide all passwords in the jsData property to prevent them from appearing in the HTML code.
foreach ($macroArray as $index => $macroValues) {
if ($macroValues['macroPassword_#index#'] === 1) {
$macroPasswords[$index]['password'] = $macroArray[$index]['macroValue_#index#'];
// It's a password macro
$macroArray[$index]['macroOldValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
$macroArray[$index]['macroValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
// Keep the original name of the input field in case its name changes.
$macroArray[$index]['macroOriginalName_#index#'] = $macroArray[$index]['macroInput_#index#'];
}
}
}
$cdata = CentreonData::getInstance();
$cdata->addJsData('clone-values-macro', htmlspecialchars(
json_encode($macroArray),
ENT_QUOTES
));
$cdata->addJsData('clone-count-macro', count($macroArray));
// Preset values of host templates
$tplArray = $hostObj->getTemplates($hostId ?? null);
$cdata->addJsData('clone-values-template', htmlspecialchars(
json_encode($tplArray),
ENT_QUOTES
));
$cdata->addJsData('clone-count-template', count($tplArray));
// IMG comes from DB -> Store in $extImg Array
$extImg = [];
$extImg = return_image_list(1);
$extImgStatusmap = [];
$extImgStatusmap = return_image_list(2);
//
// End of "database-retrieved" information
// #########################################################
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '6'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 100px;'];
$attrsAdvSelect2 = ['style' => 'width: 300px; height: 200px;'];
$attrsTextarea = ['rows' => '4', 'cols' => '80'];
$advancedSelectTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td>'
. '<td align="center">{add}<br /><br /><br />{remove}</td><td>'
. '<div class="ams">{label_3}</div>{selected}</td></tr></table>';
// For a shitty reason, Quickform set checkbox with stal[o] name
unset($_POST['o']);
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o === HOST_TEMPLATE_ADD) {
$form->addElement('header', 'title', _('Add a Host Template'));
} elseif ($o === HOST_TEMPLATE_MODIFY) {
$form->addElement('header', 'title', _('Modify a Host Template'));
} elseif ($o === HOST_TEMPLATE_WATCH) {
$form->addElement('header', 'title', _('View a Host Template'));
} elseif ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->addElement('header', 'title', _('Mass Change'));
}
// # Sort 1 - Host Template Configuration
//
// # Host basic information
//
$form->addElement('header', 'information', _('General Information'));
// No possibility to change name and alias, because there's no interest
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->addElement('text', 'host_name', _('Name'), $attrsText);
$form->addElement('text', 'host_alias', _('Alias'), $attrsText);
}
$form->addElement('select', 'host_snmp_version', _('Version'), [null => null, 1 => '1', '2c' => '2c', 3 => '3']);
switch ($o) {
case HOST_TEMPLATE_ADD:
case HOST_TEMPLATE_MASSIVE_CHANGE:
$form->addElement('text', 'host_snmp_community', _('SNMP Community'), $attrsText);
break;
default:
$snmpAttribute = $attrsText;
$snmpAttribute['onClick'] = 'javascript:change_snmp_community_input_type(this)';
$form->addElement('password', 'host_snmp_community', _('SNMP Community'), $snmpAttribute);
break;
}
$form->addElement('select2', 'host_location', _('Timezone'), [], $attributes['timezones']);
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_tplp = [
$form->createElement('radio', 'mc_mod_tplp', null, _('Incremental'), '0'),
$form->createElement('radio', 'mc_mod_tplp', null, _('Replacement'), '1'),
];
$form->addGroup($mc_mod_tplp, 'mc_mod_tplp', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_tplp' => '0']);
}
$form->addElement('text', 'host_parallel_template', _('Templates'), $hTpls);
?>
<script type="text/javascript" src="lib/wz_tooltip/wz_tooltip.js"></script>
<?php
$form->addElement(
'static',
'tplTextParallel',
_('A host or host template can have several templates. See help for more details.')
);
$form->addElement('static', 'tplText', _('Using a Template allows you to have multi-level Template connection'));
$cloneSetTemplate = [];
$listPpTemplate = $hostObj->getLimitedList();
$listAllTemplate = $hostObj->getList(false, true, null);
$mTp = $hostObj->getSavedTpl($hostId);
$validTemplate = array_diff_key($listAllTemplate, $listPpTemplate);
$listTemplate = [null => null] + $mTp + $validTemplate;
$cloneSetTemplate = [
$form->addElement(
'select',
'tpSelect[#index#]',
'',
$listTemplate,
[
'id' => 'tpSelect_#index#',
'class' => 'select2',
'type' => 'select-one',
]
),
];
$cloneSetMacro = [
$form->addElement(
'hidden',
'macroId[#index#]',
null,
['id' => 'macroId_#index#', 'size' => 25]
),
$form->addElement(
'text',
'macroInput[#index#]',
_('Macro name'),
[
'id' => 'macroInput_#index#',
'size' => 25,
]
),
$form->addElement(
'text',
'macroValue[#index#]',
_('Macro value'),
[
'id' => 'macroValue_#index#',
'size' => 25,
]
),
$form->addElement(
'checkbox',
'macroPassword[#index#]',
_('Password'),
null,
[
'id' => 'macroPassword_#index#',
'onClick' => 'javascript:change_macro_input_type(this, false)',
]
),
$form->addElement(
'hidden',
'macroFrom[#index#]',
'direct',
['id' => 'macroFrom_#index#']
),
];
$form->addElement('header', 'check', _('Host Check Properties'));
$checkCommandSelect = $form->addElement('select2', 'command_command_id', _('Check Command'), [], $attributes['check_commands']);
$checkCommandSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id","example1");'
);
$form->addElement('text', 'command_command_id_arg1', _('Args'), $attrsText);
$hostEHE = [
$form->createElement('radio', 'host_event_handler_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'host_event_handler_enabled', null, _('No'), '0'),
$form->createElement('radio', 'host_event_handler_enabled', null, _('Default'), '2'),
];
$form->addGroup($hostEHE, 'host_event_handler_enabled', _('Event Handler Enabled'), ' ');
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['host_event_handler_enabled' => '2']);
}
$eventHandlerSelect = $form->addElement('select2', 'command_command_id2', _('Event Handler'), [], $attributes['event_handlers']);
$eventHandlerSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id2","example2");'
);
$form->addElement('text', 'command_command_id_arg2', _('Args'), $attrsText);
// Check information
if (! $isCloudPlatform) {
$hostACE = [
$form->createElement('radio', 'host_active_checks_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'host_active_checks_enabled', null, _('No'), '0'),
$form->createElement('radio', 'host_active_checks_enabled', null, _('Default'), '2'),
];
$form->addGroup($hostACE, 'host_active_checks_enabled', _('Active Checks Enabled'), ' ');
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['host_active_checks_enabled' => '2']);
}
$hostPCE = [
$form->createElement('radio', 'host_passive_checks_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'host_passive_checks_enabled', null, _('No'), '0'),
$form->createElement('radio', 'host_passive_checks_enabled', null, _('Default'), '2'),
];
$form->addGroup($hostPCE, 'host_passive_checks_enabled', _('Passive Checks Enabled'), ' ');
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['host_passive_checks_enabled' => '2']);
}
}
$form->addElement('text', 'host_check_interval', _('Normal Check Interval'), $attrsText2);
$form->addElement('text', 'host_retry_check_interval', _('Retry Check Interval'), $attrsText2);
$form->addElement('text', 'host_max_check_attempts', _('Max Check Attempts'), $attrsText2);
$form->addElement('select2', 'timeperiod_tp_id', _('Check Period'), [], $attributes['check_periods']);
/**
* Acknowledgement timeout.
*/
$form->addElement('text', 'host_acknowledgement_timeout', _('Acknowledgement timeout'), $attrsText2);
// #
// # Notification informations
// #
$form->addElement('header', 'notification', _('Notification'));
$hostNE[] = $form->createElement('radio', 'host_notifications_enabled', null, _('Yes'), '1');
$hostNE[] = $form->createElement('radio', 'host_notifications_enabled', null, _('No'), '0');
$hostNE[] = $form->createElement('radio', 'host_notifications_enabled', null, _('Default'), '2');
$form->addGroup($hostNE, 'host_notifications_enabled', _('Notification Enabled'), ' ');
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['host_notifications_enabled' => '2']);
}
// Additive
$dbResult = $pearDB->query('SELECT `value` FROM options WHERE `key` = "inheritance_mode"');
$inheritanceMode = $dbResult->fetch();
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$contactAdditive = [
$form->createElement('radio', 'mc_contact_additive_inheritance', null, _('Yes'), '1'),
$form->createElement('radio', 'mc_contact_additive_inheritance', null, _('No'), '0'),
$form->createElement(
'radio',
'mc_contact_additive_inheritance',
null,
_('Default'),
'2'
),
];
$form->addGroup($contactAdditive, 'mc_contact_additive_inheritance', _('Contact additive inheritance'), ' ');
$contactGroupAdditive = [
$form->createElement('radio', 'mc_cg_additive_inheritance', null, _('Yes'), '1'),
$form->createElement('radio', 'mc_cg_additive_inheritance', null, _('No'), '0'),
$form->createElement(
'radio',
'mc_cg_additive_inheritance',
null,
_('Default'),
'2'
),
];
$form->addGroup(
$contactGroupAdditive,
'mc_cg_additive_inheritance',
_('Contact group additive inheritance'),
' '
);
} else {
$form->addElement('checkbox', 'contact_additive_inheritance', '', _('Contact additive inheritance'));
$form->addElement('checkbox', 'cg_additive_inheritance', '', _('Contact group additive inheritance'));
}
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopt_first_notification_delay = [
$form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Replacement'),
'1'
),
];
$form->addGroup(
$mc_mod_notifopt_first_notification_delay,
'mc_mod_notifopt_first_notification_delay',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_first_notification_delay' => '0']);
}
$form->addElement('text', 'host_first_notification_delay', _('First notification delay'), $attrsText2);
$form->addElement('text', 'host_recovery_notification_delay', _('Recovery notification delay'), $attrsText2);
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_hcg = [];
$mc_mod_hcg[] = $form->createElement('radio', 'mc_mod_hcg', null, _('Incremental'), '0');
$mc_mod_hcg[] = $form->createElement('radio', 'mc_mod_hcg', null, _('Replacement'), '1');
$form->addGroup($mc_mod_hcg, 'mc_mod_hcg', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_hcg' => '0']);
}
// Contacts
$form->addElement('select2', 'host_cs', _('Linked Contacts'), [], $attributes['contacts']);
// Contact groups
$form->addElement('select2', 'host_cgs', _('Linked Contact Groups'), [], $attributes['contact_groups']);
// Categories
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_hhc = [];
$mc_mod_hhc[] = $form->createElement('radio', 'mc_mod_hhc', null, _('Incremental'), '0');
$mc_mod_hhc[] = $form->createElement('radio', 'mc_mod_hhc', null, _('Replacement'), '1');
$form->addGroup($mc_mod_hhc, 'mc_mod_hhc', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_hhc' => '0']);
}
$form->addElement('select2', 'host_hcs', _('Host Categories'), [], $attributes['host_categories']);
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopt_notification_interval = [];
$mc_mod_notifopt_notification_interval = [
$form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Replacement'),
'1'
),
];
$form->addGroup(
$mc_mod_notifopt_notification_interval,
'mc_mod_notifopt_notification_interval',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_notification_interval' => '0']);
}
$form->addElement('text', 'host_notification_interval', _('Notification Interval'), $attrsText2);
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopt_timeperiod = [
$form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Replacement'),
'1'
),
];
$form->addGroup($mc_mod_notifopt_timeperiod, 'mc_mod_notifopt_timeperiod', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopt_timeperiod' => '0']);
}
$form->addElement('select2', 'timeperiod_tp_id2', _('Notification Period'), [], $attributes['notification_periods']);
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopts = [
$form->createElement('radio', 'mc_mod_notifopts', null, _('Incremental'), '0'),
$form->createElement('radio', 'mc_mod_notifopts', null, _('Replacement'), '1'),
];
$form->addGroup($mc_mod_notifopts, 'mc_mod_notifopts', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopts' => '0']);
}
$hostNotifOpt = [
$form->createElement(
'checkbox',
'd',
' ',
_('Down'),
['id' => 'notifD', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'u',
' ',
_('Unreachable'),
['id' => 'notifU', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'r',
' ',
_('Recovery'),
['id' => 'notifR', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'f',
' ',
_('Flapping'),
['id' => 'notifF', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
's',
' ',
_('Downtime Scheduled'),
['id' => 'notifDS', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'notifN', 'onClick' => 'uncheckNotifOption(this);']
),
];
$form->addGroup($hostNotifOpt, 'host_notifOpts', _('Notification Options'), ' ');
$hostStalOpt = [
$form->createElement('checkbox', 'o', ' ', _('Up')),
$form->createElement('checkbox', 'd', ' ', _('Down')),
$form->createElement('checkbox', 'u', ' ', _('Unreachable')),
];
$form->addGroup($hostStalOpt, 'host_stalOpts', _('Stalking Options'), ' ');
//
// # Further informations
//
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$form->addElement('textarea', 'host_comment', _('Comments'), $attrsTextarea);
//
// # Sort 2 - Host Relations
//
$form->addElement('header', 'HGlinks', _('Hostgroup Relations'));
$form->addElement('header', 'HClinks', _('Host Categories Relations'));
if ($o === HOST_TEMPLATE_ADD) {
$form->addElement('header', 'title2', _('Add relations'));
} elseif ($o === HOST_TEMPLATE_MODIFY) {
$form->addElement('header', 'title2', _('Modify relations'));
} elseif ($o === HOST_TEMPLATE_WATCH) {
$form->addElement('header', 'title2', _('View relations'));
} elseif ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->addElement('header', 'title2', _('Mass Change'));
}
$form->addElement('header', 'links', _('Relations'));
if ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_htpl = [];
$mc_mod_htpl[] = $form->createElement('radio', 'mc_mod_htpl', null, _('Incremental'), '0');
$mc_mod_htpl[] = $form->createElement('radio', 'mc_mod_htpl', null, _('Replacement'), '1');
$form->addGroup($mc_mod_htpl, 'mc_mod_htpl', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_htpl' => '0']);
}
$form->addElement('select2', 'host_svTpls', _('Linked Service Templates'), [], $attributes['service_templates']);
//
// # Sort 3 - Data treatment
//
if ($o === HOST_TEMPLATE_ADD) {
$form->addElement('header', 'title3', _('Add Data Processing'));
} elseif ($o === HOST_TEMPLATE_MODIFY) {
$form->addElement('header', 'title3', _('Modify Data Processing'));
} elseif ($o === HOST_TEMPLATE_WATCH) {
$form->addElement('header', 'title3', _('View Data Processing'));
} elseif ($o === HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->addElement('header', 'title2', _('Mass Change'));
}
$form->addElement('header', 'treatment', _('Data Processing'));
$hostCF = [
$form->createElement('radio', 'host_check_freshness', null, _('Yes'), '1'),
$form->createElement('radio', 'host_check_freshness', null, _('No'), '0'),
$form->createElement('radio', 'host_check_freshness', null, _('Default'), '2'),
];
$form->addGroup($hostCF, 'host_check_freshness', _('Check Freshness'), ' ');
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['host_check_freshness' => '2']);
}
$hostFDE = [
$form->createElement('radio', 'host_flap_detection_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'host_flap_detection_enabled', null, _('No'), '0'),
$form->createElement('radio', 'host_flap_detection_enabled', null, _('Default'), '2'),
];
$form->addGroup($hostFDE, 'host_flap_detection_enabled', _('Flap Detection Enabled'), ' ');
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['host_flap_detection_enabled' => '2']);
}
$form->addElement('text', 'host_freshness_threshold', _('Freshness Threshold'), $attrsText2);
$form->addElement('text', 'host_low_flap_threshold', _('Low Flap Threshold'), $attrsText2);
$form->addElement('text', 'host_high_flap_threshold', _('High Flap Threshold'), $attrsText2);
$hostPPD = [
$form->createElement('radio', 'host_process_perf_data', null, _('Yes'), '1'),
$form->createElement('radio', 'host_process_perf_data', null, _('No'), '0'),
$form->createElement('radio', 'host_process_perf_data', null, _('Default'), '2'),
];
$form->addGroup($hostPPD, 'host_process_perf_data', _('Process Perf Data'), ' ');
if ($o !== HOST_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['host_process_perf_data' => '2']);
}
//
// # Sort 4 - Extended Infos
//
if ($o === HOST_TEMPLATE_ADD) {
$form->addElement('header', 'title4', _('Add a Host Extended Info'));
} elseif ($o === HOST_TEMPLATE_MODIFY) {
$form->addElement('header', 'title4', _('Modify a Host Extended Info'));
} elseif ($o === HOST_TEMPLATE_WATCH) {
$form->addElement('header', 'title4', _('View a Host Extended Info'));
}
$form->addElement('header', 'nagios', _('Monitoring engine'));
$form->addElement('text', 'ehi_notes', _('Note'), $attrsText);
$form->addElement('text', 'ehi_notes_url', _('Note URL'), $attrsText);
$form->addElement('text', 'ehi_action_url', _('Action URL'), $attrsText);
$form->addElement('select', 'ehi_icon_image', _('Icon'), $extImg, [
'id' => 'ehi_icon_image',
'onChange' => "showLogo('ehi_icon_image_img',this.value)",
'onkeyup' => 'this.blur();this.focus();',
]);
$form->addElement('text', 'ehi_icon_image_alt', _('Alt icon'), $attrsText);
$form->addElement('select', 'ehi_statusmap_image', _('Status Map Image'), $extImgStatusmap, [
'id' => 'ehi_statusmap_image',
'onChange' => "showLogo('ehi_statusmap_image_img',this.value)",
'onkeyup' => 'this.blur();this.focus();',
]);
// Criticality
$criticality = new CentreonCriticality($pearDB);
$critList = $criticality->getList();
$criticalityIds = [null => null];
foreach ($critList as $critId => $critData) {
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contactgroup/contactGroup.php | centreon/www/include/configuration/configObject/contactgroup/contactGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$cG = $_GET['cg_id'] ?? null;
$cP = $_POST['cg_id'] ?? null;
$cg_id = $cG ?: $cP;
$cG = $_GET['select'] ?? null;
$cP = $_POST['select'] ?? null;
$select = $cG ?: $cP;
$cG = $_GET['dupNbr'] ?? null;
$cP = $_POST['dupNbr'] ?? null;
$dupNbr = $cG ?: $cP;
// Path to the configuration dir
$path = './include/configuration/configObject/contactgroup/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $centreon->user->access;
$allowedContacts = $acl->getContactAclConf(['fields' => ['contact_id', 'contact_name'], 'keys' => ['contact_id'], 'get_row' => 'contact_name', 'order' => 'contact_name']);
$allowedAclGroups = $acl->getAccessGroups();
$contactstring = '';
if (count($allowedContacts)) {
$first = true;
foreach ($allowedContacts as $key => $val) {
if ($first) {
$first = false;
} else {
$contactstring .= ',';
}
$contactstring .= "'" . $key . "'";
}
} else {
$contactstring = "''";
}
switch ($o) {
case 'a':
// Add a contactgroup
require_once $path . 'formContactGroup.php';
break;
case 'w':
// Watch a contactgroup
require_once $path . 'formContactGroup.php';
break;
case 'c':
// Modify a contactgroup
require_once $path . 'formContactGroup.php';
break;
case 's':
// Activate a contactgroup
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableContactGroupInDB($cg_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactGroup.php';
break;
case 'u':
// Desactivate a contactgroup
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableContactGroupInDB($cg_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactGroup.php';
break;
case 'm':
// Duplicate n contact group
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleContactGroupInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactGroup.php';
break;
case 'd':
// Delete a contact group
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteContactGroupInDB($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactGroup.php';
break;
case 'dn':
require_once $path . 'displayNotification.php';
break;
default:
require_once $path . 'listContactGroup.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contactgroup/help.php | centreon/www/include/configuration/configObject/contactgroup/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['contactgroup_name'] = dgettext(
'help',
'The contact group name is a short name used to identify the contact group in other sections.'
);
$help['alias'] = dgettext('help', 'The alias is a longer name or description used to identify the contact group.');
$help['members'] = dgettext(
'help',
'The linked contacts define a list of contacts that should be included in this group. This definition is '
. 'an alternative way to specifying the contact groups in contact definitions.'
);
$help['acl_groups'] = dgettext(
'help',
'Refers to the ACL groups this contact group is linked to. This parameter is mandatory if you are '
. 'not an administrator.'
);
// unsupported in Centreon
$help['contactgroup_members'] = dgettext(
'help',
'This optional directive can be used to include contacts from other "sub" contact groups in this '
. 'contact group. Specify a list of other contact groups whose members should be included in this group.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contactgroup/displayNotification.php | centreon/www/include/configuration/configObject/contactgroup/displayNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonNotification.class.php';
/**
* Get user list
*/
$contact = ['' => null];
$DBRESULT = $pearDB->query('SELECT cg_id, cg_name FROM contactgroup cg ORDER BY cg_alias');
while ($ct = $DBRESULT->fetchRow()) {
$contact[$ct['cg_id']] = $ct['cg_name'];
}
$DBRESULT->closeCursor();
// Object init
$mediaObj = new CentreonMedia($pearDB);
$host_method = new CentreonHost($pearDB);
$oNotification = new CentreonNotification($pearDB);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// start header menu
$tpl->assign('headerMenu_host', _('Hosts'));
$tpl->assign('headerMenu_service', _('Services'));
$tpl->assign('headerMenu_host_esc', _('Escalated Hosts'));
$tpl->assign('headerMenu_service_esc', _('Escalated Services'));
// Different style between each lines
$style = 'one';
$groups = "''";
if (isset($_POST['contact'])) {
$contactgroup_id = (int) htmlentities($_POST['contact'], ENT_QUOTES, 'UTF-8');
} else {
$contactgroup_id = 0;
$formData = ['contact' => $contactgroup_id];
}
$formData = ['contact' => $contactgroup_id];
// Create select form
$form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p);
$form->addElement('select', 'contact', _('Contact'), $contact, ['id' => 'contact', 'onChange' => 'submit();']);
$form->setDefaults($formData);
// Host escalations
$elemArrHostEsc = [];
if ($contactgroup_id) {
$hostEscResources = $oNotification->getNotificationsContactGroup(2, $contactgroup_id);
}
if (isset($hostEscResources)) {
foreach ($hostEscResources as $hostId => $hostName) {
$elemArrHostEsc[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icones/16x16/server_network.gif', 'RowMenu_host' => myDecode($hostName)];
$style = $style != 'two' ? 'two' : 'one';
}
}
$tpl->assign('elemArrHostEsc', $elemArrHostEsc);
// Service escalations
$elemArrSvcEsc = [];
if ($contactgroup_id) {
$svcEscResources = $oNotification->getNotificationsContactGroup(3, $contactgroup_id);
}
if (isset($svcEscResources)) {
foreach ($svcEscResources as $hostId => $hostTab) {
foreach ($hostTab as $serviceId => $tab) {
$elemArrSvcEsc[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icones/16x16/server_network.gif', 'RowMenu_host' => myDecode($tab['host_name']), 'RowMenu_service' => myDecode($tab['service_description'])];
$style = $style != 'two' ? 'two' : 'one';
}
}
}
$tpl->assign('elemArrSvcEsc', $elemArrSvcEsc);
// Hosts
$elemArrHost = [];
if ($contactgroup_id) {
$hostResources = $oNotification->getNotificationsContactGroup(0, $contactgroup_id);
}
if (isset($hostResources)) {
foreach ($hostResources as $hostId => $hostName) {
$elemArrHost[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icones/16x16/server_network.gif', 'RowMenu_host' => myDecode($hostName)];
$style = $style != 'two' ? 'two' : 'one';
}
}
$tpl->assign('elemArrHost', $elemArrHost);
// Services
$elemArrSvc = [];
if ($contactgroup_id) {
$svcResources = $oNotification->getNotificationsContactGroup(1, $contactgroup_id);
}
if (isset($svcResources)) {
foreach ($svcResources as $hostId => $hostTab) {
foreach ($hostTab as $serviceId => $tab) {
$elemArrSvc[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icones/16x16/server_network.gif', 'RowMenu_host' => myDecode($tab['host_name']), 'RowMenu_service' => myDecode($tab['service_description'])];
$style = $style != 'two' ? 'two' : 'one';
}
}
}
$tpl->assign('elemArrSvc', $elemArrSvc);
$labels = ['host_escalation' => _('Host escalations'), 'service_escalation' => _('Service escalations'), 'host_notifications' => _('Host notifications'), 'service_notifications' => _('Service notifications')];
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('msgSelect', _('Please select a user in order to view his notifications'));
$tpl->assign('p', $p);
$tpl->assign('contact', $contactgroup_id);
$tpl->assign('labels', $labels);
$tpl->display('displayNotification.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contactgroup/listContactGroup.php | centreon/www/include/configuration/configObject/contactgroup/listContactGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './include/common/autoNumLimit.php';
$SearchSTR = '';
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchCG'] ?? $_GET['searchCG'] ?? null
);
if (isset($_POST['searchCG']) || isset($_GET['searchCG'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$clauses = [];
if ($search) {
$clauses = ['cg_name' => ['LIKE', '%' . $search . '%'], 'cg_alias' => ['OR', 'LIKE', '%' . $search . '%']];
}
$aclOptions = ['fields' => ['cg_id', 'cg_name', 'cg_alias', 'cg_activate'], 'keys' => ['cg_id'], 'order' => ['cg_name'], 'conditions' => $clauses];
$cgs = $acl->getContactGroupAclConf($aclOptions);
$rows = count($cgs);
include_once './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Description'));
$tpl->assign('headerMenu_contacts', _('Contacts'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
// Contactgroup list
$aclOptions['pages'] = $num * $limit . ', ' . $limit;
$cgs = $acl->getContactGroupAclConf($aclOptions);
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
foreach ($cgs as $cg) {
$selectedElements = $form->addElement('checkbox', 'select[' . $cg['cg_id'] . ']');
if ($cg['cg_activate']) {
$moptions = "<a href='main.php?p=" . $p . '&cg_id=' . $cg['cg_id'] . '&o=u&limit=' . $limit . '&num=' . $num
. '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' border='0' "
. "alt='" . _('Disabled') . "'></a> ";
} else {
$moptions = "<a href='main.php?p=" . $p . '&cg_id=' . $cg['cg_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right'"
. "border='0' alt='" . _('Enabled') . "'></a> ";
}
$moptions .= ' ';
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $cg['cg_id'] . "]' />";
// Contacts
$ctNbr = [];
$rq = "SELECT COUNT(DISTINCT contact_contact_id) AS `nbr`
FROM `contactgroup_contact_relation` `cgr`
WHERE `cgr`.`contactgroup_cg_id` = '" . $cg['cg_id'] . "' "
. $acl->queryBuilder('AND', 'contact_contact_id', $contactstring);
$dbResult2 = $pearDB->query($rq);
$ctNbr = $dbResult2->fetch();
$elemArr[] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => $cg['cg_name'], 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&cg_id=' . $cg['cg_id'], 'RowMenu_desc' => $cg['cg_alias'], 'RowMenu_contacts' => $ctNbr['nbr'], 'RowMenu_status' => $cg['cg_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $cg['cg_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?'), 'view_notif' => _('View contact group notifications')]
);
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['" . $option . "'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['" . $option . "'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 3) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. ''];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('limit', $limit);
$tpl->assign('searchCG', $search);
$tpl->display('listContactGroup.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contactgroup/formContactGroup.php | centreon/www/include/configuration/configObject/contactgroup/formContactGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if (! $centreon->user->admin && $cg_id) {
$aclOptions = ['fields' => ['cg_id', 'cg_name'], 'keys' => ['cg_id'], 'get_row' => 'cg_name', 'conditions' => ['cg_id' => $cg_id]];
$cgs = $acl->getContactGroupAclConf($aclOptions);
if (! count($cgs)) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this contact group'));
return null;
}
}
$initialValues = [];
// Database retrieve information for Contact
$cg = [];
if (($o == 'c' || $o == 'w') && $cg_id) {
// Get host Group information
$statement = $pearDB->prepare('SELECT * FROM `contactgroup` WHERE `cg_id` = :cg_id LIMIT 1');
$statement->bindValue(':cg_id', (int) $cg_id, PDO::PARAM_INT);
$statement->execute();
// Set base value
$cg = array_map('myDecode', $statement->fetch(PDO::FETCH_ASSOC));
}
$attrsText = ['size' => '30'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 100px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '60'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$contactRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contact&action=list';
$attrContacts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $contactRoute, 'multiple' => true, 'linkedObject' => 'centreonContact'];
$aclgRoute = './include/common/webServices/rest/internal.php?object=centreon_administration_aclgroup&action=list';
$attrAclgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $aclgRoute, 'multiple' => true, 'linkedObject' => 'centreonAclGroup'];
// form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a Contact Group'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a Contact Group'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a Contact Group'));
}
// Contact basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'cg_name', _('Contact Group Name'), $attrsText);
$form->addElement('text', 'cg_alias', _('Alias'), $attrsText);
// Contacts Selection
$form->addElement('header', 'notification', _('Relations'));
$contactRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contact'
. '&action=defaultValues&target=contactgroup&field=cg_contacts&id=' . $cg_id;
$attrContact1 = array_merge(
$attrContacts,
['defaultDatasetRoute' => $contactRoute]
);
$form->addElement('select2', 'cg_contacts', _('Linked Contacts'), [], $attrContact1);
// Acl group selection
$aclRoute = './include/common/webServices/rest/internal.php?object=centreon_administration_aclgroup'
. '&action=defaultValues&target=contactgroup&field=cg_acl_groups&id=' . $cg_id;
$attrAclgroup1 = array_merge(
$attrAclgroups,
['defaultDatasetRoute' => $aclRoute]
);
$form->addElement('select2', 'cg_acl_groups', _('Linked ACL groups'), [], $attrAclgroup1);
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$cgActivation[] = $form->createElement('radio', 'cg_activate', null, _('Enabled'), '1');
$cgActivation[] = $form->createElement('radio', 'cg_activate', null, _('Disabled'), '0');
$form->addGroup($cgActivation, 'cg_activate', _('Status'), ' ');
$form->setDefaults(['cg_activate' => '1']);
$form->addElement('textarea', 'cg_comment', _('Comments'), $attrsTextarea);
$form->addElement('hidden', 'cg_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
// Set rules
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('cg_name', _('Compulsory Name'), 'required');
$form->addRule('cg_alias', _('Compulsory Alias'), 'required');
if (! $centreon->user->admin) {
$form->addRule('cg_acl_groups', _('Compulsory field'), 'required');
}
$form->registerRule('exist', 'callback', 'testContactGroupExistence');
$form->addRule('cg_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, '
. '"orange", TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"],'
. ' WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
if ($o == 'w') {
// Just watch a Contact Group information
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&cg_id=' . $cg_id . "'"]
);
}
$form->setDefaults($cg);
$form->freeze();
} elseif ($o == 'c') {
// Modify a Contact Group information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($cg);
} elseif ($o == 'a') {
// Add a Contact Group information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if ($form->validate()) {
$cgObj = $form->getElement('cg_id');
if ($form->getSubmitValue('submitA')) {
$cgObj->setValue(insertContactGroupInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateContactGroupInDB($cgObj->getValue());
}
$o = null;
$valid = true;
}
if ($valid) {
require_once $path . 'listContactGroup.php';
} else {
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formContactGroup.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contactgroup/DB-Func.php | centreon/www/include/configuration/configObject/contactgroup/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
function testContactGroupExistence($name = null)
{
global $pearDB, $form, $centreon;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('cg_id');
}
$query = 'SELECT `cg_name`, `cg_id` FROM `contactgroup` '
. "WHERE `cg_name` = '" . htmlentities($centreon->checkIllegalChar($name)) . "'";
$dbResult = $pearDB->query($query);
$cg = $dbResult->fetch();
if ($dbResult->rowCount() >= 1 && $cg['cg_id'] == $id) {
// Modif case
return true;
}
return ! ($dbResult->rowCount() >= 1 && $cg['cg_id'] != $id);
// Duplicate entry
}
function enableContactGroupInDB($cg_id = null)
{
global $pearDB, $centreon;
if (! $cg_id) {
return;
}
$pearDB->query("UPDATE `contactgroup` SET `cg_activate` = '1' WHERE `cg_id` = '" . (int) $cg_id . "'");
$dbResult2 = $pearDB->query("SELECT cg_name FROM `contactgroup` WHERE `cg_id` = '" . (int) $cg_id . "' LIMIT 1");
$row = $dbResult2->fetch();
$centreon->CentreonLogAction->insertLog('contactgroup', $cg_id, $row['cg_name'], 'enable');
}
function disableContactGroupInDB($cg_id = null)
{
global $pearDB, $centreon;
if (! $cg_id) {
return;
}
$pearDB->query("UPDATE `contactgroup` SET `cg_activate` = '0' WHERE `cg_id` = '" . (int) $cg_id . "'");
$dbResult2 = $pearDB->query("SELECT cg_name FROM `contactgroup` WHERE `cg_id` = '" . (int) $cg_id . "' LIMIT 1");
$row = $dbResult2->fetch();
$centreon->CentreonLogAction->insertLog('contactgroup', $cg_id, $row['cg_name'], 'disable');
}
function deleteContactGroupInDB($contactGroups = [])
{
global $pearDB, $centreon;
foreach ($contactGroups as $key => $value) {
$query = "SELECT cg_name FROM `contactgroup` WHERE `cg_id` = '" . (int) $key . "' LIMIT 1";
$dbResult2 = $pearDB->query($query);
$row = $dbResult2->fetch();
$pearDB->query("DELETE FROM `contactgroup` WHERE `cg_id` = '" . (int) $key . "'");
$centreon->CentreonLogAction->insertLog('contactgroup', $key, $row['cg_name'], 'd');
}
}
function multipleContactGroupInDB($contactGroups = [], $nbrDup = [])
{
global $pearDB, $centreon;
foreach ($contactGroups as $key => $value) {
$dbResult = $pearDB->query("SELECT * FROM `contactgroup` WHERE `cg_id` = '" . (int) $key . "' LIMIT 1");
$row = $dbResult->fetch();
$row['cg_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if ($key2 == 'cg_name') {
$cg_name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$val
? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL');
if ($key2 != 'cg_id') {
$fields[$key2] = $value2;
}
if (isset($cg_name)) {
$fields['cg_name'] = $cg_name;
}
}
if (isset($cg_name) && testContactGroupExistence($cg_name)) {
$rq = $val ? 'INSERT INTO `contactgroup` VALUES (' . $val . ')' : null;
$pearDB->query($rq);
$dbResult = $pearDB->query('SELECT MAX(cg_id) FROM `contactgroup`');
$maxId = $dbResult->fetch();
if (isset($maxId['MAX(cg_id)'])) {
$query = 'SELECT DISTINCT `acl_group_id` FROM `acl_group_contactgroups_relations` '
. 'WHERE `cg_cg_id` = ' . (int) $key;
$dbResult = $pearDB->query($query);
$fields['cg_aclRelation'] = '';
$aclContactStatement = $pearDB->prepare('INSERT INTO `acl_group_contactgroups_relations` '
. 'VALUES (:maxId, :cgAcl)');
while ($cgAcl = $dbResult->fetch()) {
$aclContactStatement->bindValue(':maxId', (int) $maxId['MAX(cg_id)'], PDO::PARAM_INT);
$aclContactStatement->bindValue(':cgAcl', (int) $cgAcl['acl_group_id'], PDO::PARAM_INT);
$aclContactStatement->execute();
$fields['cg_aclRelation'] .= $cgAcl['acl_group_id'] . ',';
}
$query = 'SELECT DISTINCT `cgcr`.`contact_contact_id` FROM `contactgroup_contact_relation` `cgcr`'
. " WHERE `cgcr`.`contactgroup_cg_id` = '" . (int) $key . "'";
$dbResult = $pearDB->query($query);
$fields['cg_contacts'] = '';
$contactStatement = $pearDB->prepare('INSERT INTO `contactgroup_contact_relation` '
. 'VALUES (:cct, :maxId)');
while ($cct = $dbResult->fetch()) {
$contactStatement->bindValue(':cct', (int) $cct['contact_contact_id'], PDO::PARAM_INT);
$contactStatement->bindValue(':maxId', (int) $maxId['MAX(cg_id)'], PDO::PARAM_INT);
$contactStatement->execute();
$fields['cg_contacts'] .= $cct['contact_contact_id'] . ',';
}
$fields['cg_contacts'] = trim($fields['cg_contacts'], ',');
$centreon->CentreonLogAction->insertLog(
'contactgroup',
$maxId['MAX(cg_id)'],
$cg_name,
'a',
$fields
);
}
}
}
}
}
function insertContactGroupInDB($ret = [])
{
$cg_id = insertContactGroup($ret);
updateContactGroupContacts($cg_id, $ret);
updateContactGroupAclGroups($cg_id, $ret);
return $cg_id;
}
/**
* @param $ret
* @return int
*/
function insertContactGroup($ret)
{
global $form, $pearDB, $centreon;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$cgName = $centreon->checkIllegalChar(
HtmlAnalyzer::sanitizeAndRemoveTags($ret['cg_name'])
);
$cgAlias = HtmlAnalyzer::sanitizeAndRemoveTags($ret['cg_alias']);
$cgComment = HtmlAnalyzer::sanitizeAndRemoveTags($ret['cg_comment']);
$cgActivate = $ret['cg_activate']['cg_activate'] === '0' ? '0' : '1'; // enum
$stmt = $pearDB->prepare(
'INSERT INTO `contactgroup` (`cg_name`, `cg_alias`, `cg_comment`, `cg_activate`)
VALUES (:cgName, :cgAlias, :cgComment, :cgActivate)'
);
$stmt->bindValue(':cgName', $cgName, PDO::PARAM_STR);
$stmt->bindValue(':cgAlias', $cgAlias, PDO::PARAM_STR);
$stmt->bindValue(':cgComment', $cgComment, PDO::PARAM_STR);
$stmt->bindValue(':cgActivate', $cgActivate, PDO::PARAM_STR);
$stmt->execute();
$dbResult = $pearDB->query('SELECT MAX(cg_id) FROM `contactgroup`');
$cgId = $dbResult->fetch();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
'contactgroup',
$cgId['MAX(cg_id)'],
$cgName,
'a',
$fields
);
return (int) $cgId['MAX(cg_id)'];
}
function updateContactGroupInDB($cg_id = null, $params = [])
{
if (! $cg_id) {
return;
}
updateContactGroup($cg_id, $params);
updateContactGroupContacts($cg_id, $params);
updateContactGroupAclGroups($cg_id, $params);
}
/**
* @param null $cgId
* @param array $params
*/
function updateContactGroup($cgId = null, $params = [])
{
global $form, $pearDB, $centreon;
if (! $cgId) {
return;
}
$ret = [];
$ret = count($params) ? $params : $form->getSubmitValues();
$cgName = $centreon->checkIllegalChar(
HtmlAnalyzer::sanitizeAndRemoveTags($ret['cg_name'])
);
$cgAlias = HtmlAnalyzer::sanitizeAndRemoveTags($ret['cg_alias']);
$cgComment = HtmlAnalyzer::sanitizeAndRemoveTags($ret['cg_comment']);
$cgActivate = $ret['cg_activate']['cg_activate'] === '0' ? '0' : '1'; // enum
$stmt = $pearDB->prepare(
'UPDATE `contactgroup` SET `cg_name` = :cgName, `cg_alias` = :cgAlias, `cg_comment` = :cgComment, '
. '`cg_activate` = :cgActivate WHERE `cg_id` = ' . (int) $cgId
);
$stmt->bindValue(':cgName', $cgName, PDO::PARAM_STR);
$stmt->bindValue(':cgAlias', $cgAlias, PDO::PARAM_STR);
$stmt->bindValue(':cgComment', $cgComment, PDO::PARAM_STR);
$stmt->bindValue(':cgActivate', $cgActivate, PDO::PARAM_STR);
$stmt->execute();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog('contactgroup', $cgId, $cgName, 'c', $fields);
}
function updateContactGroupContacts($cg_id, $ret = [])
{
global $centreon, $form, $pearDB;
if (! $cg_id) {
return;
}
$rq = "DELETE FROM `contactgroup_contact_relation` WHERE `contactgroup_cg_id` = '" . (int) $cg_id . "'";
$dbResult = $pearDB->query($rq);
$ret = $ret['cg_contacts'] ?? CentreonUtils::mergeWithInitialValues($form, 'cg_contacts');
$counter = count($ret);
for ($i = 0; $i < $counter; $i++) {
$rq = 'INSERT INTO `contactgroup_contact_relation` (`contact_contact_id`, `contactgroup_cg_id`) ';
$rq .= "VALUES ('" . $ret[$i] . "', '" . (int) $cg_id . "')";
$dbResult = $pearDB->query($rq);
CentreonCustomView::syncContactGroupCustomView($centreon, $pearDB, $ret[$i]);
}
}
function updateContactGroupAclGroups($cg_id, $ret = [])
{
global $form, $pearDB;
if (! $cg_id) {
return;
}
$rq = 'DELETE FROM `acl_group_contactgroups_relations` WHERE `cg_cg_id` = ' . (int) $cg_id;
$res = $pearDB->query($rq);
if (isset($ret['cg_acl_groups'])) {
$ret = $ret['cg_acl_groups'];
} else {
$ret = CentreonUtils::mergeWithInitialValues($form, 'cg_acl_groups');
}
$counter = count($ret);
for ($i = 0; $i < $counter; $i++) {
$rq = 'INSERT INTO `acl_group_contactgroups_relations` (`acl_group_id`, `cg_cg_id`) ';
$rq .= "VALUES ('" . $ret[$i] . "', '" . (int) $cg_id . "')";
$dbResult = $pearDB->query($rq);
}
}
/**
* Get contact group id by name
*
* @param string $name
* @return int
*/
function getContactGroupIdByName($name)
{
global $pearDB;
$id = 0;
$res = $pearDB->query("SELECT cg_id FROM contactgroup WHERE cg_name = '" . CentreonDB::escape($name) . "'");
if ($res->rowCount()) {
$row = $res->fetch();
$id = $row['cg_id'];
}
return $id;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_categories/formServiceCategories.php | centreon/www/include/configuration/configObject/service_categories/formServiceCategories.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if (! $oreon->user->admin) {
if ($sc_id && $scString != "''" && ! str_contains($scString, "'" . $sc_id . "'")) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this service category'));
return null;
}
}
// Database retrieve information for Contact
$cct = [];
if (($o == 'c' || $o == 'w') && $sc_id) {
$DBRESULT = $pearDB->prepare('SELECT * FROM `service_categories` WHERE `sc_id` = :sc_id LIMIT 1');
$DBRESULT->bindValue(':sc_id', $sc_id, PDO::PARAM_INT);
$DBRESULT->execute();
// Set base value
$sc = array_map('myDecode', $DBRESULT->fetchRow());
$DBRESULT->closeCursor();
$sc['sc_severity_level'] = $sc['level'];
$sc['sc_severity_icon'] = $sc['icon_id'];
$sc['sc_svc'] = [];
}
// Define Template
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '60'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 150px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$servTplAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicetemplate'
. '&action=list';
$attrServicetemplates = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $servTplAvRoute, 'multiple' => true, 'linkedObject' => 'centreonServicetemplates'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a Service Category'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a Service Category'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a Service Category'));
}
// Contact basic information
$form->addElement('header', 'information', _('Information'));
$form->addElement('header', 'links', _('Relations'));
// No possibility to change name and alias, because there's no interest
$form->addElement('text', 'sc_name', _('Name'), $attrsText);
$form->addElement('text', 'sc_description', _('Description'), $attrsText);
// Severity
$sctype = $form->addElement('checkbox', 'sc_type', _('Severity type'), null, ['id' => 'sc_type']);
if (isset($sc_id, $sc['level']) && $sc['level'] != '') {
$sctype->setValue('1');
}
$form->addElement('text', 'sc_severity_level', _('Level'), ['size' => '10']);
$iconImgs = return_image_list(1);
$form->addElement('select', 'sc_severity_icon', _('Icon'), $iconImgs, ['id' => 'icon_id', 'onChange' => "showLogo('icon_id_ctn', this.value)", 'onkeyup' => 'this.blur(); this.focus();']);
$servTplDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicetemplate'
. '&action=defaultValues&target=servicecategories&field=sc_svcTpl&id=' . $sc_id;
$attrServicetemplate1 = array_merge(
$attrServicetemplates,
['defaultDatasetRoute' => $servTplDeRoute]
);
$form->addElement('select2', 'sc_svcTpl', _('Linked Templates'), [], $attrServicetemplate1);
$sc_activate[] = $form->createElement('radio', 'sc_activate', null, _('Enabled'), '1');
$sc_activate[] = $form->createElement('radio', 'sc_activate', null, _('Disabled'), '0');
$form->addGroup($sc_activate, 'sc_activate', _('Status'), ' ');
$form->setDefaults(['sc_activate' => '1']);
$form->addElement('hidden', 'sc_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
if (is_array($select)) {
$select_str = null;
foreach ($select as $key => $value) {
$select_str .= $key . ',';
}
$select_pear = $form->addElement('hidden', 'select');
$select_pear->setValue($select_str);
}
// Form Rules
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['contact_name']);
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('contact_name', 'myReplace');
$from_list_menu = false;
$form->addRule('sc_name', _('Compulsory Name'), 'required');
$form->addRule('sc_description', _('Compulsory Alias'), 'required');
$form->registerRule('existName', 'callback', 'testServiceCategorieExistence');
$form->addRule('sc_name', _('Name is already in use'), 'existName');
$form->addRule('sc_severity_level', _('Must be a number'), 'numeric');
$form->registerRule('shouldNotBeEqTo0', 'callback', 'shouldNotBeEqTo0');
$form->addRule('sc_severity_level', _("Can't be equal to 0"), 'shouldNotBeEqTo0');
$form->addFormRule('checkSeverity');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange",'
. ' TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"],'
. ' WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
if ($o == 'w') {
// Just watch a service_categories information
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&sc_id=' . $sc_id . "'"]
);
}
$form->setDefaults($sc);
$form->freeze();
} elseif ($o == 'c') {
// Modify a service_categories information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($sc);
} elseif ($o == 'a') {
// Add a service_categories information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if ($form->validate() && $from_list_menu == false) {
$cctObj = $form->getElement('sc_id');
if ($form->getSubmitValue('submitA')) {
$cctObj->setValue(insertServiceCategorieInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateServiceCategorieInDB();
}
$o = null;
$valid = true;
}
if ($valid) {
require_once $path . 'listServiceCategories.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign('p', $p);
$tpl->display('formServiceCategories.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_categories/listServiceCategories.php | centreon/www/include/configuration/configObject/service_categories/listServiceCategories.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($oreon)) {
exit();
}
include './include/common/autoNumLimit.php';
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchSC'] ?? $_GET['searchSC'] ?? null
);
if (isset($_POST['searchSC']) || isset($_GET['searchSC'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$searchTool = null;
if ($search) {
$searchTool .= "WHERE (sc_name LIKE '%" . $search . "%' "
. "OR sc_description LIKE '%" . $search . "%') ";
}
$aclCond = '';
if (! $oreon->user->admin && $scString != "''") {
$clause = is_null($searchTool) ? ' WHERE ' : ' AND ';
$aclCond .= $acl->queryBuilder($clause, 'sc_id', $scString);
}
// Services Categories Lists
$dbResult = $pearDB->query(
'SELECT SQL_CALC_FOUND_ROWS * FROM service_categories ' . $searchTool . $aclCond
. 'ORDER BY sc_name LIMIT ' . $num * $limit . ', ' . $limit
);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Description'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_linked_svc', _('Number of linked services'));
$tpl->assign('headerMenu_sc_type', _('Type'));
$tpl->assign('headerMenu_options', _('Options'));
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
$statement = $pearDB->prepare('SELECT COUNT(*) FROM `service_categories_relation` WHERE `sc_id` = :sc_id');
for ($i = 0; $sc = $dbResult->fetch(); $i++) {
$moptions = '';
$statement->bindValue(':sc_id', (int) $sc['sc_id'], PDO::PARAM_INT);
$statement->execute();
$nb_svc = $statement->fetch();
$selectedElements = $form->addElement('checkbox', 'select[' . $sc['sc_id'] . ']');
if ($sc['sc_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&sc_id=' . $sc['sc_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Disabled') . "'></a> ";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&sc_id=' . $sc['sc_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a> ";
}
$moptions .= ' ';
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) '
. "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" "
. "name='dupNbr[" . $sc['sc_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'sc_name' => htmlentities($sc['sc_name'], ENT_QUOTES, 'UTF-8'), 'sc_link' => 'main.php?p=' . $p . '&o=c&sc_id=' . $sc['sc_id'], 'sc_description' => htmlentities($sc['sc_description'], ENT_QUOTES, 'UTF-8'), 'svc_linked' => $nb_svc['COUNT(*)'], 'sc_type' => ($sc['level'] ? _('Severity') . ' (' . $sc['level'] . ')' : _('Regular')), 'sc_activated' => $sc['sc_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $sc['sc_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign('msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add')]);
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3 || this.form.elements['o1'].selectedIndex == 4 "
. "||this.form.elements['o1'].selectedIndex == 5){"
. " setO(this.form.elements['o1'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3 || "
. "this.form.elements['o2'].selectedIndex == 4 ||this.form.elements['o2'].selectedIndex == 5){"
. " setO(this.form.elements['o2'].value); submit();} "
. "this.form.elements['o2'].selectedIndex = 0"];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'ms' => _('Enable'), 'mu' => _('Disable')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchSC', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listServiceCategories.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_categories/serviceCategories.php | centreon/www/include/configuration/configObject/service_categories/serviceCategories.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
// Path to the configuration dir
$path = './include/configuration/configObject/service_categories/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
$sc_id = filter_var(
$_GET['sc_id'] ?? $_POST['sc_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $oreon->user->access;
$dbmon = new CentreonDB('centstorage');
$aclDbName = $acl->getNameDBAcl();
$scString = $acl->getServiceCategoriesString();
switch ($o) {
case 'a': // Add a service category
case 'w': // Watch a service category
case 'c': // Modify a service category
require_once $path . 'formServiceCategories.php';
break;
case 's': // Activate a ServiceCategories
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceCategorieInDB($sc_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceCategories.php';
break;
case 'ms':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceCategorieInDB(null, is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceCategories.php';
break;
case 'u': // Desactivate a service category
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceCategorieInDB($sc_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceCategories.php';
break;
case 'mu':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceCategorieInDB(null, is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceCategories.php';
break;
case 'm': // Duplicate n service categories
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleServiceCategorieInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceCategories.php';
break;
case 'd': // Delete n service categories
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteServiceCategorieInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceCategories.php';
break;
default:
require_once $path . 'listServiceCategories.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_categories/help.php | centreon/www/include/configuration/configObject/service_categories/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['name'] = dgettext(
'help',
'Define a short name for this category. It will be displayed with this name in the ACL configuration.'
);
$help['description'] = dgettext('help', 'Use this field for a longer description of this category.');
$help['service_template'] = dgettext(
'help',
'Select the service templates this category should be linked to. Every service based on the selected '
. 'templates will be automatically linked with this category.'
);
$help['sc_type'] = dgettext(
'help',
'Whether this category is a severity. Severities appear on the monitoring consoles.'
);
$help['sc_severity_level'] = dgettext(
'help',
'Severity level, must be a number. The items displayed will be sorted in ascending order. '
. 'Thus the lowest severity is considered than the highest priority.'
);
$help['sc_severity_icon'] = dgettext('help', 'Icon for this severity.');
$help['sc_activate'] = dgettext('help', 'Whether or not this category is enabled.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_categories/DB-Func.php | centreon/www/include/configuration/configObject/service_categories/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Core\ActionLog\Domain\Model\ActionLog;
if (! isset($oreon)) {
exit();
}
/**
* Rule that checks whether severity data is set
* @param mixed $fields
*/
function checkSeverity($fields)
{
$arr = [];
if (isset($fields['sc_type']) && $fields['sc_severity_level'] == '') {
$arr['sc_severity_level'] = 'Severity level is required';
}
if (isset($fields['sc_type']) && $fields['sc_severity_icon'] == '') {
$arr['sc_severity_icon'] = 'Severity icon is required';
}
if ($arr !== []) {
return $arr;
}
return true;
}
function testServiceCategorieExistence($name = null)
{
global $pearDB, $form;
$name = HtmlAnalyzer::sanitizeAndRemoveTags($name);
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('sc_id');
}
$query = 'SELECT `sc_name`, `sc_id` FROM `service_categories` WHERE `sc_name` = :sc_name';
$statement = $pearDB->prepare($query);
$statement->bindValue(':sc_name', $name, PDO::PARAM_STR);
$statement->execute();
$sc = $statement->fetch();
return ! ($statement->rowCount() >= 1 && $sc['sc_id'] != $id);
}
function shouldNotBeEqTo0($value)
{
return (bool) ($value);
}
function multipleServiceCategorieInDB($sc = [], $nbrDup = [])
{
global $pearDB, $centreon;
$scAcl = [];
foreach ($sc as $key => $value) {
$scId = filter_var($key, FILTER_VALIDATE_INT);
$query = 'SELECT * FROM `service_categories` WHERE `sc_id` = :sc_id LIMIT 1';
$statement = $pearDB->prepare($query);
$statement->bindValue(':sc_id', $scId, PDO::PARAM_INT);
$statement->execute();
$row = $statement->fetch();
for ($i = 1; $i <= $nbrDup[$scId]; $i++) {
$val = null;
$bindParams = [];
$fields = [];
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
switch ($key2) {
case 'sc_name':
$value2 = HtmlAnalyzer::sanitizeAndRemoveTags($value2);
$sc_name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
$bindParams[':sc_name'] = [
PDO::PARAM_STR => $value2,
];
break;
case 'sc_description':
$value2 = HtmlAnalyzer::sanitizeAndRemoveTags($value2);
$bindParams[':sc_description'] = [
PDO::PARAM_STR => $value2,
];
break;
case 'level':
$value2 = filter_var($value2, FILTER_VALIDATE_INT);
$value2
? $bindParams[':sc_level'] = [PDO::PARAM_INT => $value2]
: $bindParams[':sc_level'] = [PDO::PARAM_NULL => 'NULL'];
break;
case 'icon_id':
$value2 = filter_var($value2, FILTER_VALIDATE_INT);
$value2
? $bindParams[':sc_icon_id'] = [PDO::PARAM_INT => $value2]
: $bindParams[':sc_icon_id'] = [PDO::PARAM_NULL => 'NULL'];
break;
case 'sc_activate':
$value2 = filter_var($value2, FILTER_VALIDATE_INT);
$value2
? $bindParams[':sc_activate'] = [PDO::PARAM_STR => $value2]
: $bindParams[':sc_activate'] = [PDO::PARAM_STR => '0'];
break;
}
$val
? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL');
if ($key2 != 'sc_id') {
$fields[$key2] = $value2;
}
}
if ($val === null) {
continue;
}
$fields['sc_name'] = $sc_name;
if (testServiceCategorieExistence($sc_name)) {
$statement = $pearDB->prepare(
<<<'SQL'
INSERT INTO `service_categories`
VALUES (NULL, :sc_name, :sc_description, :sc_level, :sc_icon_id, :sc_activate)
SQL
);
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$statement->bindValue($token, $value, $paramType);
}
}
$statement->execute();
$statement = $pearDB->query('SELECT MAX(sc_id) as maxid FROM `service_categories`');
$maxId = $statement->fetch();
if (isset($maxId['maxid'])) {
$scAcl[$maxId['maxid']] = $scId;
try {
$selectServiceIdsStatement = $pearDB->prepareQuery(
<<<'SQL'
SELECT service_service_id FROM service_categories_relation
WHERE sc_id = :sc_id
SQL
);
$pearDB->executePreparedQuery($selectServiceIdsStatement, ['sc_id' => $scId]);
$insertNewRelationStatement = $pearDB->prepareQuery(
<<<'SQL'
INSERT INTO service_categories_relation (service_service_id, sc_id)
VALUES (:serviceId, :maxId)
SQL
);
$foundServiceIds = [];
while ($serviceId = $pearDB->fetchColumn($selectServiceIdsStatement)) {
$pearDB->executePreparedQuery($insertNewRelationStatement, [
'serviceId' => $serviceId,
'maxId' => $maxId['maxid'],
]);
$foundServiceIds[] = $serviceId;
}
if ($foundServiceIds !== []) {
$fields['sc_services'] = implode(', ', $foundServiceIds);
}
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICECATEGORIES,
object_id: $maxId['maxid'],
object_name: $sc_name,
action_type: ActionLog::ACTION_TYPE_ADD,
fields: $fields
);
} catch (CentreonDbException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while duplicating service categories: ' . $ex->getMessage(),
customContext: ['service_category_id' => $scId],
exception: $ex,
);
throw $ex;
}
}
}
}
}
CentreonACL::duplicateScAcl($scAcl);
$centreon->user->access->updateACL();
}
function enableServiceCategorieInDB(?int $serviceCategoryId = null, array $serviceCategories = [])
{
if (! $serviceCategoryId && $serviceCategories === []) {
return;
}
global $pearDB, $centreon;
if ($serviceCategoryId) {
$serviceCategories = [$serviceCategoryId => '1'];
}
try {
$updateStatement = $pearDB->prepareQuery(
<<<'SQL'
UPDATE service_categories
SET sc_activate = '1'
WHERE sc_id = :serviceCategoryId
SQL
);
$selectStatement = $pearDB->prepareQuery(
<<<'SQL'
SELECT sc_name FROM `service_categories`
WHERE `sc_id` = :serviceCategoryId LIMIT 1
SQL
);
foreach (array_keys($serviceCategories) as $serviceCategoryId) {
$pearDB->executePreparedQuery($updateStatement, ['serviceCategoryId' => $serviceCategoryId]);
$pearDB->executePreparedQuery($selectStatement, ['serviceCategoryId' => $serviceCategoryId]);
$result = $pearDB->fetch($selectStatement);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICECATEGORIES,
object_id: $serviceCategoryId,
object_name: $result['sc_name'],
action_type: ActionLog::ACTION_TYPE_ENABLE
);
}
} catch (CentreonDbException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while enabling service category: ' . $ex->getMessage(),
customContext: ['service_category_id' => $serviceCategoryId],
exception: $ex,
);
throw $ex;
}
}
function disableServiceCategorieInDB(?int $serviceCategoryId = null, array $serviceCategories = [])
{
if (! $serviceCategoryId && $serviceCategories === []) {
return;
}
global $pearDB, $centreon;
if ($serviceCategoryId) {
$serviceCategories = [$serviceCategoryId => '1'];
}
try {
$updateStatement = $pearDB->prepareQuery(
<<<'SQL'
UPDATE service_categories
SET sc_activate = '0'
WHERE sc_id = :serviceCategoryId
SQL
);
$selectStatement = $pearDB->prepareQuery(
<<<'SQL'
SELECT sc_name FROM `service_categories`
WHERE `sc_id` = :serviceCategoryId LIMIT 1
SQL
);
foreach (array_keys($serviceCategories) as $serviceCategoryId) {
$pearDB->executePreparedQuery($updateStatement, ['serviceCategoryId' => $serviceCategoryId]);
$pearDB->executePreparedQuery($selectStatement, ['serviceCategoryId' => $serviceCategoryId]);
$result = $pearDB->fetch($selectStatement);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICECATEGORIES,
object_id: $serviceCategoryId,
object_name: $result['sc_name'],
action_type: ActionLog::ACTION_TYPE_DISABLE
);
}
} catch (CentreonDbException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while disabling service category: ' . $ex->getMessage(),
customContext: ['service_category_id' => implode(', ', array_keys($serviceCategories))],
exception: $ex,
);
throw $ex;
}
}
function insertServiceCategorieInDB()
{
global $form, $pearDB, $centreon;
$formValues = $form->getSubmitValues();
$scName = HtmlSanitizer::createFromString($formValues['sc_name'])->sanitize()->getString();
$scDescription = HtmlSanitizer::createFromString($formValues['sc_description'])->sanitize()->getString();
$scSeverityLevel = filter_var($formValues['sc_severity_level'], FILTER_VALIDATE_INT);
$scType = filter_var($formValues['sc_type'] ?? false, FILTER_VALIDATE_INT);
$scSeverityIconId = filter_var($formValues['sc_severity_icon'], FILTER_VALIDATE_INT);
$scActivate = filter_var($formValues['sc_activate']['sc_activate'], FILTER_VALIDATE_INT);
$bindParams = [];
$bindParams[':sc_name'] = [
PDO::PARAM_STR => $scName,
];
$bindParams[':sc_description'] = [
PDO::PARAM_STR => $scDescription,
];
($scSeverityLevel === false || $scType === false)
? $bindParams[':sc_severity_level'] = [PDO::PARAM_NULL => 'NULL']
: $bindParams[':sc_severity_level'] = [PDO::PARAM_INT => $scSeverityLevel];
($scSeverityIconId === false || $scType === false)
? $bindParams[':sc_icon_id'] = [PDO::PARAM_NULL => 'NULL']
: $bindParams[':sc_icon_id'] = [PDO::PARAM_INT => $scSeverityIconId];
($scActivate === false)
? $bindParams[':sc_activate'] = [PDO::PARAM_STR => '0']
: $bindParams[':sc_activate'] = [PDO::PARAM_STR => $scActivate];
if (testServiceCategorieExistence($scName)) {
$query = '
INSERT INTO `service_categories` (`sc_name`, `sc_description`, `level`, `icon_id`, `sc_activate`)
VALUES (:sc_name, :sc_description, :sc_severity_level, :sc_icon_id, :sc_activate)';
$statement = $pearDB->prepare($query);
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$statement->bindValue($token, $value, $paramType);
}
}
$statement->execute();
$query = 'SELECT MAX(sc_id) FROM `service_categories` WHERE sc_name LIKE :sc_name';
$statement = $pearDB->prepare($query);
$statement->bindValue(':sc_name', $scName, PDO::PARAM_STR);
$statement->execute();
$data = $statement->fetch();
}
updateServiceCategoriesServices($data['MAX(sc_id)']);
$centreon->user->access->updateACL();
$fields = CentreonLogAction::prepareChanges($formValues);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICECATEGORIES,
object_id: $data['MAX(sc_id)'],
object_name: $scName,
action_type: ActionLog::ACTION_TYPE_ADD,
fields: $fields
);
}
function updateServiceCategorieInDB()
{
global $form, $pearDB, $centreon;
$formValues = $form->getSubmitValues();
$scId = filter_var($formValues['sc_id'], FILTER_VALIDATE_INT);
$scName = HtmlSanitizer::createFromString($formValues['sc_name'])->sanitize()->getString();
$scDescription = HtmlSanitizer::createFromString($formValues['sc_description'])->sanitize()->getString();
$scSeverityLevel = filter_var($formValues['sc_severity_level'], FILTER_VALIDATE_INT);
$scType = filter_var($formValues['sc_type'] ?? false, FILTER_VALIDATE_INT);
$scSeverityIconId = filter_var($formValues['sc_severity_icon'], FILTER_VALIDATE_INT);
$scActivate = filter_var($formValues['sc_activate']['sc_activate'], FILTER_VALIDATE_INT);
$bindParams = [];
$bindParams[':sc_id'] = [
PDO::PARAM_INT => $scId,
];
$bindParams[':sc_name'] = [
PDO::PARAM_STR => $scName,
];
$bindParams[':sc_description'] = [
PDO::PARAM_STR => $scDescription,
];
($scSeverityLevel === false || $scType === false)
? $bindParams[':sc_severity_level'] = [PDO::PARAM_NULL => 'NULL']
: $bindParams[':sc_severity_level'] = [PDO::PARAM_INT => $scSeverityLevel];
($scSeverityIconId === false || $scType === false)
? $bindParams[':sc_icon_id'] = [PDO::PARAM_NULL => 'NULL']
: $bindParams[':sc_icon_id'] = [PDO::PARAM_INT => $scSeverityIconId];
($scActivate === false)
? $bindParams[':sc_activate'] = [PDO::PARAM_STR => '0']
: $bindParams[':sc_activate'] = [PDO::PARAM_STR => $scActivate];
$query = '
UPDATE `service_categories`
SET `sc_name` = :sc_name,
`sc_description` = :sc_description,
`level` = :sc_severity_level,
`icon_id` = :sc_icon_id,
`sc_activate` = :sc_activate
WHERE `sc_id` = :sc_id';
$statement = $pearDB->prepare($query);
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$statement->bindValue($token, $value, $paramType);
}
}
$statement->execute();
updateServiceCategoriesServices($scId);
$centreon->user->access->updateACL();
$fields = CentreonLogAction::prepareChanges($formValues);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICECATEGORIES,
object_id: $scId,
object_name: $scName,
action_type: ActionLog::ACTION_TYPE_CHANGE,
fields: $fields
);
}
function deleteServiceCategorieInDB($serviceCategoryIds = null)
{
global $pearDB, $centreon;
if (is_null($serviceCategoryIds)) {
return;
}
try {
$deleteStatement = $pearDB->prepareQuery(
<<<'SQL'
DELETE FROM `service_categories`
WHERE `sc_id` = :sc_id
SQL
);
$selectStatement = $pearDB->prepareQuery(
<<<'SQL'
SELECT sc_name FROM `service_categories`
WHERE `sc_id` = :serviceCategoryId LIMIT 1
SQL
);
foreach (array_keys($serviceCategoryIds) as $serviceCategoryId) {
$serviceCategoryId = filter_var($serviceCategoryId, FILTER_VALIDATE_INT)
?: throw new Exception('Invalid service category id');
$pearDB->executePreparedQuery($selectStatement, ['serviceCategoryId' => $serviceCategoryId]);
$result = $pearDB->fetch($selectStatement);
$pearDB->executePreparedQuery($deleteStatement, ['sc_id' => $serviceCategoryId]);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_SERVICECATEGORIES,
object_id: $serviceCategoryId,
object_name: $result['sc_name'],
action_type: ActionLog::ACTION_TYPE_DELETE
);
}
$centreon->user->access->updateACL();
} catch (CentreonDbException $ex) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while deleting service categories: ' . $ex->getMessage(),
customContext: ['service_category_id' => implode(', ', $serviceCategoryIds)],
exception: $ex,
);
throw $ex;
}
}
function updateServiceCategoriesServices(int $sc_id)
{
global $pearDB, $form;
if (! $sc_id) {
return;
}
$query = "
DELETE FROM service_categories_relation WHERE sc_id = :sc_id
AND service_service_id IN (SELECT service_id FROM service WHERE service_register = '0')";
$statement = $pearDB->prepare($query);
$statement->bindValue(':sc_id', $sc_id, PDO::PARAM_INT);
$statement->execute();
if (isset($_POST['sc_svcTpl'])) {
foreach ($_POST['sc_svcTpl'] as $serviceId) {
$serviceId = filter_var($serviceId, FILTER_VALIDATE_INT);
$query = '
INSERT INTO service_categories_relation (service_service_id, sc_id)
VALUES (:service_id, :sc_id)';
$statement = $pearDB->prepare($query);
$statement->bindValue(':service_id', $serviceId, PDO::PARAM_INT);
$statement->bindValue(':sc_id', $sc_id, PDO::PARAM_INT);
$statement->execute();
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/hostgroup_dependency/DB-Func.php | centreon/www/include/configuration/configObject/hostgroup_dependency/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
if (! isset($centreon)) {
exit();
}
function testHostGroupDependencyExistence(?string $name = null): bool
{
global $pearDB, $form;
// If no name provided, consider it as non-existent
if (empty($name)) {
return true;
}
try {
CentreonDependency::purgeObsoleteDependencies($pearDB);
$id = $form?->getSubmitValue('dep_id');
$query = $pearDB->createQueryBuilder()
->select('dep_name', 'dep_id')
->from('dependency')
->where('dep_name = :depName')
->getQuery();
$params = QueryParameters::create([
QueryParameter::string('depName', CentreonDB::escape($name)),
]);
$row = $pearDB->fetchAssociative($query, $params);
if ($row === false) {
return true;
}
return (int) $row['dep_id'] === (int) $id;
} catch (Exception $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error checking host group dependency existence: {$e->getMessage()}",
customContext: [
'dependency_name' => $name,
'dependency_id' => $id,
],
exception: $e
);
return false;
}
}
function testHostGroupDependencyCycle(array $childs = []): bool
{
global $form;
$parents = [];
if (isset($form)) {
$parents = $form->getSubmitValue('dep_hgParents');
$childs = $form->getSubmitValue('dep_hgChilds');
$childs = array_flip($childs);
}
foreach ($parents as $parent) {
if (array_key_exists($parent, $childs)) {
return false;
}
}
return true;
}
function deleteHostGroupDependencyInDB(array $dependencies = []): void
{
global $pearDB, $centreon;
foreach ($dependencies as $key => $value) {
try {
$query = $pearDB->createQueryBuilder()
->select('dep_name')
->from('dependency')
->where('dep_id = :depId')
->limit(1)
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $key),
]);
$row = $pearDB->fetchAssociative($query, $params);
if (! $row) {
continue;
}
$query = $pearDB->createQueryBuilder()
->delete('dependency')
->where('dep_id = :depId')
->getQuery();
$pearDB->executeStatement($query, $params);
$centreon->CentreonLogAction->insertLog('hostgroup dependency', $key, $row['dep_name'], 'd');
} catch (Exception $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error deleting hostgroup dependency: {$e->getMessage()}",
customContext: [
'dependency_id' => $key,
],
exception: $e
);
continue;
}
}
}
function multipleHostGroupDependencyInDB(array $dependencies = [], array $nbrDup = [])
{
global $pearDB, $centreon;
foreach ($dependencies as $key => $value) {
try {
$query = $pearDB->createQueryBuilder()
->select('*')
->from('dependency')
->where('dep_id = :depId')
->limit(1)
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $key),
]);
$row = $pearDB->fetchAssociative($query, $params);
if (! $row) {
continue;
}
$row['dep_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if ($key2 == 'dep_name') {
$dep_name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$val
? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL');
if ($key2 != 'dep_id') {
$fields[$key2] = $value2;
}
if (isset($dep_name)) {
$fields['dep_name'] = $dep_name;
}
}
if (isset($dep_name) && testHostGroupDependencyExistence($dep_name)) {
$columns = ['dep_id', 'dep_name', 'dep_description', 'inherits_parent', 'execution_failure_criteria',
'notification_failure_criteria', 'dep_comment'];
$qb = $pearDB->createQueryBuilder()
->insert('dependency')
->values(
array_combine($columns,
explode(
', ',
$val
)
)
)
->getQuery();
$pearDB->executeStatement($qb);
$qb = $pearDB->createQueryBuilder()
->select('MAX(dep_id) AS max_dep_id')
->from('dependency')
->getQuery();
$maxId = $pearDB->fetchAssociative($qb);
if (isset($maxId['max_dep_id'])) {
$qb = $pearDB->createQueryBuilder()
->select('hostgroup_hg_id')
->from('dependency_hostgroupParent_relation')
->where('dependency_dep_id = :depId')
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $key),
]);
$result = $pearDB->fetchAllAssociative($qb, $params);
$fields['dep_hgParents'] = '';
foreach ($result as $hg) {
$qb = $pearDB->createQueryBuilder()
->insert('dependency_hostgroupParent_relation')
->values([
'dependency_dep_id' => ':max_id',
'hostgroup_hg_id' => ':hg_id',
])
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('max_id', (int) $maxId['max_dep_id']),
QueryParameter::int('hg_id', (int) $hg['hostgroup_hg_id']),
]);
$pearDB->executeStatement($qb, $params);
$fields['dep_hgParents'] .= $hg['hostgroup_hg_id'] . ',';
}
$fields['dep_hgParents'] = trim($fields['dep_hgParents'], ',');
$qb = $pearDB->createQueryBuilder()
->select('hostgroup_hg_id')
->from('dependency_hostgroupChild_relation')
->where('dependency_dep_id = :depId')
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $key),
]);
$result = $pearDB->fetchAllAssociative($qb, $params);
$fields['dep_hgChilds'] = '';
foreach ($result as $hg) {
$qb = $pearDB->createQueryBuilder()
->insert('dependency_hostgroupChild_relation')
->values([
'dependency_dep_id' => ':max_id',
'hostgroup_hg_id' => ':hg_id',
])
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('max_id', (int) $maxId['max_dep_id']),
QueryParameter::int('hg_id', (int) $hg['hostgroup_hg_id']),
]);
$pearDB->executeStatement($qb, $params);
$fields['dep_hgChilds'] .= $hg['hostgroup_hg_id'] . ',';
}
$fields['dep_hgChilds'] = trim($fields['dep_hgChilds'], ',');
$centreon->CentreonLogAction->insertLog(
'hostgroup dependency',
$maxId['max_dep_id'],
$dep_name,
'a',
$fields
);
}
}
}
} catch (Exception $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error duplicating hostgroup dependency: {$e->getMessage()}",
customContext: [
'dependency_id' => $key,
],
exception: $e
);
continue;
}
}
}
function updateHostGroupDependencyInDB($dep_id = null)
{
if (! $dep_id) {
exit();
}
updateHostGroupDependency($dep_id);
updateHostGroupDependencyHostGroupParents($dep_id);
updateHostGroupDependencyHostGroupChilds($dep_id);
}
function insertHostGroupDependencyInDB(array $ret = [])
{
$dep_id = insertHostGroupDependency($ret);
updateHostGroupDependencyHostGroupParents($dep_id, $ret);
updateHostGroupDependencyHostGroupChilds($dep_id, $ret);
return $dep_id;
}
/**
* Create a host group dependency
*
* @param array<string, mixed> $ret
* @return int
*/
function insertHostGroupDependency(array $ret = []): int
{
global $form, $pearDB, $centreon;
if ($ret === []) {
$ret = $form->getSubmitValues();
}
$resourceValues = sanitizeResourceParameters($ret);
$qb = $pearDB->createQueryBuilder()
->insert('dependency')
->values(
[
'dep_name' => ':depName',
'dep_description' => ':depDescription',
'inherits_parent' => ':inheritsParent',
'execution_failure_criteria' => ':executionFailure',
'notification_failure_criteria' => ':notificationFailure',
'dep_comment' => ':depComment',
]
)
->getQuery();
$params = QueryParameters::create([
QueryParameter::string('depName', $resourceValues['dep_name']),
QueryParameter::string('depDescription', $resourceValues['dep_description']),
QueryParameter::string('inheritsParent', $resourceValues['inherits_parent']),
QueryParameter::string(
'executionFailure',
$resourceValues['execution_failure_criteria'] ?? null
),
QueryParameter::string(
'notificationFailure',
$resourceValues['notification_failure_criteria'] ?? null
),
QueryParameter::string('depComment', $resourceValues['dep_comment']),
]);
$pearDB->executeStatement($qb, $params);
$qb = $pearDB->createQueryBuilder()
->select('MAX(dep_id) as max_dep_id')
->from('dependency')
->getQuery();
$result = $pearDB->fetchAssociative($qb);
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
'hostgroup dependency',
$result['max_dep_id'],
$resourceValues['dep_name'],
'a',
$fields
);
return (int) $result['max_dep_id'];
}
/**
* Update a host group dependency
*
* @param null|int $depId
*/
function updateHostGroupDependency($depId = null): void
{
if (! $depId) {
exit();
}
global $form, $pearDB, $centreon;
try {
$resourceValues = sanitizeResourceParameters($form->getSubmitValues());
$qb = $pearDB->createQueryBuilder()
->update('dependency')
->set('dep_name', ':depName')
->set('dep_description', ':depDescription')
->set('inherits_parent', ':inheritsParent')
->set('execution_failure_criteria', ':executionFailure')
->set('notification_failure_criteria', ':notificationFailure')
->set('dep_comment', ':depComment')
->where('dep_id = :depId')
->getQuery();
$params = QueryParameters::create([
QueryParameter::string('depName', $resourceValues['dep_name']),
QueryParameter::string('depDescription', $resourceValues['dep_description']),
QueryParameter::string('inheritsParent', $resourceValues['inherits_parent']),
QueryParameter::string(
'executionFailure',
$resourceValues['execution_failure_criteria'] ?? null
),
QueryParameter::string(
'notificationFailure',
$resourceValues['notification_failure_criteria'] ?? null
),
QueryParameter::string('depComment', $resourceValues['dep_comment']),
QueryParameter::int('depId', (int) $depId),
]);
$pearDB->executeStatement($qb, $params);
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($resourceValues);
$centreon->CentreonLogAction->insertLog(
'hostgroup dependency',
$depId,
$resourceValues['dep_name'],
'c',
$fields
);
} catch (Exception $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: "Error updating host group dependency: {$e->getMessage()}",
customContext: [
'dependency_id' => $depId,
],
exception: $e
);
}
}
/**
* sanitize resources parameter for Create / Update a host group dependency
*
* @param array<string, mixed> $resources
* @return array<string, mixed>
*/
function sanitizeResourceParameters(array $resources): array
{
$sanitizedParameters = [];
$sanitizedParameters['dep_name'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_name']);
if (empty($sanitizedParameters['dep_name'])) {
throw new InvalidArgumentException(_("Dependency name can't be empty"));
}
$sanitizedParameters['dep_description'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_description']);
if (empty($sanitizedParameters['dep_description'])) {
throw new InvalidArgumentException(_("Dependency description can't be empty"));
}
$resources['inherits_parent']['inherits_parent'] == 1
? $sanitizedParameters['inherits_parent'] = '1'
: $sanitizedParameters['inherits_parent'] = '0';
if (isset($resources['execution_failure_criteria']) && is_array($resources['execution_failure_criteria'])) {
$sanitizedParameters['execution_failure_criteria'] = HtmlAnalyzer::sanitizeAndRemoveTags(
implode(
',',
array_keys($resources['execution_failure_criteria'])
)
);
}
if (isset($resources['notification_failure_criteria']) && is_array($resources['notification_failure_criteria'])) {
$sanitizedParameters['notification_failure_criteria'] = HtmlAnalyzer::sanitizeAndRemoveTags(
implode(
',',
array_keys($resources['notification_failure_criteria'])
)
);
}
$sanitizedParameters['dep_comment'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_comment']);
return $sanitizedParameters;
}
function updateHostGroupDependencyHostGroupParents($dep_id = null, array $ret = []): void
{
if (! $dep_id) {
exit();
}
global $form, $pearDB;
$qb = $pearDB->createQueryBuilder()
->delete('dependency_hostgroupParent_relation')
->where('dependency_dep_id = :depId')
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $dep_id),
]);
$pearDB->executeStatement($qb, $params);
if (isset($ret['dep_hgParents'])) {
$ret = $ret['dep_hgParents'];
} else {
$ret = CentreonUtils::mergeWithInitialValues($form, 'dep_hgParents');
}
$counter = count($ret);
for ($i = 0; $i < $counter; $i++) {
$qb = $pearDB->createQueryBuilder()
->insert('dependency_hostgroupParent_relation')
->values([
'dependency_dep_id' => ':depId',
'hostgroup_hg_id' => ':hgId',
])
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $dep_id),
QueryParameter::int('hgId', (int) $ret[$i]),
]);
$pearDB->executeStatement($qb, $params);
}
}
function updateHostGroupDependencyHostGroupChilds($dep_id = null, array $ret = []): void
{
if (! $dep_id) {
exit();
}
global $form, $pearDB;
$qb = $pearDB->createQueryBuilder()
->delete('dependency_hostgroupChild_relation')
->where('dependency_dep_id = :depId')
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $dep_id),
]);
$pearDB->executeStatement($qb, $params);
if (isset($ret['dep_hgChilds'])) {
$ret = $ret['dep_hgChilds'];
} else {
$ret = CentreonUtils::mergeWithInitialValues($form, 'dep_hgChilds');
}
$counter = count($ret);
for ($i = 0; $i < $counter; $i++) {
$qb = $pearDB->createQueryBuilder()
->insert('dependency_hostgroupChild_relation')
->values([
'dependency_dep_id' => ':depId',
'hostgroup_hg_id' => ':hgId',
])
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $dep_id),
QueryParameter::int('hgId', (int) $ret[$i]),
]);
$pearDB->executeStatement($qb, $params);
}
}
function validateParentChildAreNotCircular(array $fields): array|true
{
global $pearDB;
$parentIds = $fields['dep_hgParents'] ?? [];
$childIds = $fields['dep_hgChilds'] ?? [];
if (empty($parentIds) || empty($childIds)) {
return true;
}
// Normalize IDs to integers and remove duplicates
$parentIds = array_values(array_unique(array_map('intval', $parentIds)));
$childIds = array_values(array_unique(array_map('intval', $childIds)));
// Build safe placeholders and parameters for parents
$parentPlaceholders = [];
$queryParameters = [];
foreach ($parentIds as $index => $parentId) {
$name = 'parentId' . $index; // no leading colon
$parentPlaceholders[] = ':' . $name;
$queryParameters[] = QueryParameter::int($name, $parentId);
}
$parentIdsAsString = implode(', ', $parentPlaceholders);
$query = $pearDB->createQueryBuilder()
->select('DISTINCT host_host_id')
->from('hostgroup_relation')
->where("hostgroup_hg_id IN ({$parentIdsAsString})")
->getQuery();
$params = QueryParameters::create($queryParameters);
$parentHosts = $pearDB->fetchFirstColumn($query, $params);
// Build safe placeholders and parameters for children
$childPlaceholders = [];
$queryParameters = [];
foreach ($childIds as $index => $childId) {
$name = 'childId' . $index; // no leading colon
$childPlaceholders[] = ':' . $name;
$queryParameters[] = QueryParameter::int($name, $childId);
}
$childIdsAsString = implode(', ', $childPlaceholders);
$query = $pearDB->createQueryBuilder()
->select('DISTINCT host_host_id')
->from('hostgroup_relation')
->where("hostgroup_hg_id IN ({$childIdsAsString})")
->getQuery();
$params = QueryParameters::create($queryParameters);
$childHosts = $pearDB->fetchFirstColumn($query, $params);
$intersect = array_intersect($parentHosts, $childHosts);
if ($intersect !== []) {
return [
'dep_hgParents' => 'Circular dependency detected between parent and child host groups. Some hosts are present in both parent and child host groups.',
];
}
return true;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/hostgroup_dependency/hostGroupDependency.php | centreon/www/include/configuration/configObject/hostgroup_dependency/hostGroupDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
const ADD_DEPENDENCY = 'a';
const WATCH_DEPENDENCY = 'w';
const MODIFY_DEPENDENCY = 'c';
const DUPLICATE_DEPENDENCY = 'm';
const DELETE_DEPENDENCY = 'd';
// Path to the configuration dir
$path = './include/configuration/configObject/hostgroup_dependency/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
$depId = filter_var(
$_GET['dep_id'] ?? $_POST['dep_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $oreon->user->access;
$hgs = $acl->getHostGroupAclConf(null, 'broker');
$hgstring = CentreonUtils::toStringWithQuotes($hgs);
switch ($o) {
case ADD_DEPENDENCY:
case WATCH_DEPENDENCY:
case MODIFY_DEPENDENCY:
require_once $path . 'formHostGroupDependency.php';
break;
case DUPLICATE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleHostGroupDependencyInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostGroupDependency.php';
break;
case DELETE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteHostGroupDependencyInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostGroupDependency.php';
break;
default:
require_once $path . 'listHostGroupDependency.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/hostgroup_dependency/formHostGroupDependency.php | centreon/www/include/configuration/configObject/hostgroup_dependency/formHostGroupDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
if (! isset($centreon)) {
exit();
}
//
// # Database retrieve information for Dependency
//
$dep = [];
$initialValues = [];
if (($o == MODIFY_DEPENDENCY || $o == WATCH_DEPENDENCY) && $depId) {
$qb = $pearDB->createQueryBuilder()
->select('*')
->from('dependency')
->where('dep_id = :depId')
->limit(1)
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('depId', (int) $depId),
]);
$result = $pearDB->fetchAssociative($qb, $params);
if ($result !== false) {
// Set base value
$dep = array_map('myDecode', $result);
// Set Notification Failure Criteria
$dep['notification_failure_criteria'] = explode(',', $dep['notification_failure_criteria']);
foreach ($dep['notification_failure_criteria'] as $key => $value) {
$dep['notification_failure_criteria'][trim($value)] = 1;
}
// Set Execution Failure Criteria
$dep['execution_failure_criteria'] = explode(',', $dep['execution_failure_criteria']);
foreach ($dep['execution_failure_criteria'] as $key => $value) {
$dep['execution_failure_criteria'][trim($value)] = 1;
}
} else {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Dependency not found',
['depId' => $depId]
);
}
}
// Var information to format the element
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '10'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 150px;'];
$attrsTextarea = ['rows' => '3', 'cols' => '30'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup&action=list';
$attrHostgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => true, 'linkedObject' => 'centreonHostgroups'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == ADD_DEPENDENCY) {
$form->addElement('header', 'title', _('Add a Dependency'));
} elseif ($o == MODIFY_DEPENDENCY) {
$form->addElement('header', 'title', _('Modify a Dependency'));
} elseif ($o == WATCH_DEPENDENCY) {
$form->addElement('header', 'title', _('View a Dependency'));
}
// Dependency basic information
$form->addElement('header', 'information', _('Information'));
$form->addElement('text', 'dep_name', _('Name'), $attrsText);
$form->addElement('text', 'dep_description', _('Description'), $attrsText);
$tab = [];
$tab[] = $form->createElement('radio', 'inherits_parent', null, _('Yes'), '1');
$tab[] = $form->createElement('radio', 'inherits_parent', null, _('No'), '0');
$form->addGroup($tab, 'inherits_parent', _('Parent relationship'), ' ');
$form->setDefaults(['inherits_parent' => '1']);
$tab = [];
$tab[] = $form->createElement(
'checkbox',
'o',
' ',
_('Ok/Up'),
['id' => 'nUp', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'd',
' ',
_('Down'),
['id' => 'nDown', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unreachable'),
['id' => 'nUnreachable', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'p',
' ',
_('Pending'),
['id' => 'nPending', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'nNone', 'onClick' => 'applyNotificationRules(this);']
);
$form->addGroup($tab, 'notification_failure_criteria', _('Notification Failure Criteria'), ' ');
$tab = [];
$tab[] = $form->createElement(
'checkbox',
'o',
' ',
_('Ok/Up'),
['id' => 'eUp', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'd',
' ',
_('Down'),
['id' => 'eDown', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unreachable'),
['id' => 'eUnreachable', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'p',
' ',
_('Pending'),
['id' => 'ePending', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'eNone', 'onClick' => 'applyExecutionRules(this);']
);
$form->addGroup($tab, 'execution_failure_criteria', _('Execution Failure Criteria'), ' ');
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup'
. '&action=defaultValues&target=dependency&field=dep_hgParents&id=' . $depId;
$attrHostgroup1 = array_merge(
$attrHostgroups,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'dep_hgParents', _('Host Groups Name'), [], $attrHostgroup1);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup'
. '&action=defaultValues&target=dependency&field=dep_hgChilds&id=' . $depId;
$attrHostgroup2 = array_merge(
$attrHostgroups,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'dep_hgChilds', _('Dependent Host Groups Name'), [], $attrHostgroup2);
$form->addElement('textarea', 'dep_comment', _('Comments'), $attrsTextarea);
$form->addElement('hidden', 'dep_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
// Form Rules
$form->applyFilter('__ALL__', 'myTrim');
$form->registerRule('sanitize', 'callback', 'isNotEmptyAfterStringSanitize');
$form->addRule('dep_name', _('Compulsory Name'), 'required');
$form->addRule('dep_name', _('Unauthorized value'), 'sanitize');
$form->addRule('dep_description', _('Required Field'), 'required');
$form->addRule('dep_description', _('Unauthorized value'), 'sanitize');
$form->addRule('dep_hgParents', _('Required Field'), 'required');
$form->addRule('dep_hgChilds', _('Required Field'), 'required');
$form->addRule('execution_failure_criteria', _('Required Field'), 'required');
$form->addRule('notification_failure_criteria', _('Required Field'), 'required');
$form->registerRule('cycle', 'callback', 'testHostGroupDependencyCycle');
$form->addRule('dep_hgChilds', _('Circular Definition'), 'cycle');
$form->registerRule('exist', 'callback', 'testHostGroupDependencyExistence');
$form->addRule('dep_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
if ($o === ADD_DEPENDENCY || $o === MODIFY_DEPENDENCY) {
$form->addFormRule('validateParentChildAreNotCircular');
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Just watch a Dependency information
if ($o == WATCH_DEPENDENCY) {
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&dep_id=' . $depId . "'"]
);
}
$form->setDefaults($dep);
$form->freeze();
} elseif ($o == MODIFY_DEPENDENCY) {
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($dep);
} elseif ($o == ADD_DEPENDENCY) {
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults(['inherits_parent', '0']);
}
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", '
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, -300, '
. 'SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'include/configuration/configObject/host_dependency/help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$valid = false;
if ($form->validate()) {
$depObj = $form->getElement('dep_id');
if ($form->getSubmitValue('submitA')) {
$depObj->setValue(insertHostGroupDependencyInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateHostGroupDependencyInDB($depObj->getValue('dep_id'));
}
$o = null;
$valid = true;
}
if ($valid) {
require_once 'listHostGroupDependency.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formHostGroupDependency.ihtml');
}
?>
<script type="text/javascript">
function applyNotificationRules(object) {
if (object.id === "nNone" && object.checked) {
document.getElementById('nUp').checked = false;
document.getElementById('nDown').checked = false;
document.getElementById('nUnreachable').checked = false;
document.getElementById('nPending').checked = false;
}
else {
document.getElementById('nNone').checked = false;
}
}
function applyExecutionRules(object) {
if (object.id === "eNone" && object.checked) {
document.getElementById('eUp').checked = false;
document.getElementById('eDown').checked = false;
document.getElementById('eUnreachable').checked = false;
document.getElementById('ePending').checked = false;
}
else {
document.getElementById('eNone').checked = false;
}
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/hostgroup_dependency/listHostGroupDependency.php | centreon/www/include/configuration/configObject/hostgroup_dependency/listHostGroupDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
$list = $_GET['list'] ?? null;
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchHGD'] ?? $_GET['searchHGD'] ?? null
);
if (isset($_POST['searchHGD']) || isset($_GET['searchHGD'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
// List dependencies
$qb = $pearDB->createQueryBuilder()
->select('dep.dep_id', 'dep.dep_name', 'dep.dep_description')
->from('dependency', 'dep');
$subQueryParent = $pearDB->createQueryBuilder()
->select('COUNT(DISTINCT dhgpr_parent.dependency_dep_id)')
->from('dependency_hostgroupParent_relation', 'dhgpr_parent')
->where('dhgpr_parent.dependency_dep_id = dep.dep_id');
$subQueryChild = $pearDB->createQueryBuilder()
->select('COUNT(DISTINCT dhgpr_child.dependency_dep_id)')
->from('dependency_hostgroupChild_relation', 'dhgpr_child')
->where('dhgpr_child.dependency_dep_id = dep.dep_id');
if (! $oreon->user->admin) {
$subQueryParent->andWhere("dhgpr_parent.hostgroup_hg_id IN ({$hgstring})");
$subQueryChild->andWhere("dhgpr_child.hostgroup_hg_id IN ({$hgstring})");
}
$qb->where('(' . $subQueryParent->getQuery() . ') > 0')
->orWhere('(' . $subQueryChild->getQuery() . ') > 0');
$params = null;
if ($search) {
$qb->andWhere(
$qb->expr()->or(
$qb->expr()->like('dep.dep_name', ':search'),
$qb->expr()->like('dep.dep_description', ':search')
)
);
$params = QueryParameters::create([
QueryParameter::string('search', '%' . $search . '%'),
]);
}
$qb->orderBy('dep.dep_name')
->addOrderBy('dep.dep_description')
->offset($num * $limit)
->limit($limit);
$result = $pearDB->fetchAllAssociative($qb->getQuery(), $params ?? null);
// get rows count with same filters as the select query
$countQb = $pearDB->createQueryBuilder()
->select('COUNT(DISTINCT dep.dep_id)')
->from('dependency', 'dep');
$countSubQueryParent = $pearDB->createQueryBuilder()
->select('COUNT(DISTINCT dhgpr_parent.dependency_dep_id)')
->from('dependency_hostgroupParent_relation', 'dhgpr_parent')
->where('dhgpr_parent.dependency_dep_id = dep.dep_id');
$countSubQueryChild = $pearDB->createQueryBuilder()
->select('COUNT(DISTINCT dhgpr_child.dependency_dep_id)')
->from('dependency_hostgroupChild_relation', 'dhgpr_child')
->where('dhgpr_child.dependency_dep_id = dep.dep_id');
if (! $oreon->user->admin) {
$countSubQueryParent->andWhere("dhgpr_parent.hostgroup_hg_id IN ({$hgstring})");
$countSubQueryChild->andWhere("dhgpr_child.hostgroup_hg_id IN ({$hgstring})");
}
$countQb->where('(' . $countSubQueryParent->getQuery() . ') > 0')
->orWhere('(' . $countSubQueryChild->getQuery() . ') > 0');
if ($search) {
$countQb->andWhere(
$countQb->expr()->or(
$countQb->expr()->like('dep.dep_name', ':search'),
$countQb->expr()->like('dep.dep_description', ':search')
)
);
}
$rows = $pearDB->fetchOne($countQb->getQuery(), $params ?? null);
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_description', _('Alias'));
$tpl->assign('headerMenu_options', _('Options'));
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
foreach ($result as $i => $dep) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $dep['dep_id'] . ']');
$moptions .= ' <input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57))'
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr["
. $dep['dep_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure($dep['dep_name']), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&dep_id=' . $dep['dep_id'], 'RowMenu_description' => CentreonUtils::escapeSecure($dep['dep_description']), 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchHGD', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listHostGroupDependency.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/servicegroup/listServiceGroup.php | centreon/www/include/configuration/configObject/servicegroup/listServiceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchSG'] ?? $_GET['searchSG'] ?? null
);
if (isset($_POST['searchSG']) || isset($_GET['searchSG'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$conditionStr = '';
$sgStrParams = [];
if (! $acl->admin && $sgString) {
$sgStrList = explode(',', $sgString);
foreach ($sgStrList as $index => $sgId) {
$sgStrParams[':sg_' . $index] = (int) str_replace("'", '', $sgId);
}
$queryParams = implode(',', array_keys($sgStrParams));
$conditionStr = $search !== '' ? 'AND sg_id IN (' . $queryParams . ')' : 'WHERE sg_id IN (' . $queryParams . ')';
}
if ($search !== '') {
$statement = $pearDB->prepare('SELECT SQL_CALC_FOUND_ROWS sg_id, sg_name, sg_alias, sg_activate'
. ' FROM servicegroup WHERE (sg_name LIKE :search OR sg_alias LIKE :search) ' . $conditionStr
. ' ORDER BY sg_name LIMIT :offset, :limit');
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
} else {
$statement = $pearDB->prepare('SELECT SQL_CALC_FOUND_ROWS sg_id, sg_name, sg_alias, sg_activate'
. ' FROM servicegroup ' . $conditionStr . ' ORDER BY sg_name LIMIT :offset, :limit');
}
foreach ($sgStrParams as $key => $sgId) {
$statement->bindValue($key, $sgId, PDO::PARAM_INT);
}
$statement->bindValue(':offset', (int) $num * (int) $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', $limit, PDO::PARAM_INT);
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Description'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $sg = $statement->fetch(PDO::FETCH_ASSOC); $i++) {
$selectedElements = $form->addElement('checkbox', 'select[' . $sg['sg_id'] . ']');
$moptions = '';
if ($sg['sg_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&sg_id=' . $sg['sg_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Disabled') . "'></a>";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&sg_id=' . $sg['sg_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a>";
}
$moptions .= ' <input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;" '
. "maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $sg['sg_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure($sg['sg_name']), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&sg_id=' . $sg['sg_id'], 'RowMenu_desc' => CentreonUtils::escapeSecure($sg['sg_alias']), 'RowMenu_status' => $sg['sg_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $sg['sg_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$attrs = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs
);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchSG', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listServiceGroup.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/servicegroup/serviceGroup.php | centreon/www/include/configuration/configObject/servicegroup/serviceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
const SERVICE_GROUP_ADD = 'a';
const SERVICE_GROUP_WATCH = 'w';
const SERVICE_GROUP_MODIFY = 'c';
const SERVICE_GROUP_ACTIVATION = 's';
const SERVICE_GROUP_DEACTIVATION = 'u';
const SERVICE_GROUP_DUPLICATION = 'm';
const SERVICE_GROUP_DELETION = 'd';
// Path to the configuration dir
$path = './include/configuration/configObject/servicegroup/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
global $isCloudPlatform;
$isCloudPlatform = isCloudPlatform();
$serviceGroupId = filter_var(
$_GET['sg_id'] ?? $_POST['sg_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] !== '' && $p !== $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $oreon->user->access;
$aclDbName = $acl->getNameDBAcl();
$dbmon = new CentreonDB('centstorage');
$sgs = $acl->getServiceGroupAclConf(null, 'broker');
function mywrap($el)
{
return "'" . $el . "'";
}
$sgString = implode(',', array_map('mywrap', array_keys($sgs)));
switch ($o) {
case SERVICE_GROUP_ADD: // Add a service group
case SERVICE_GROUP_WATCH: // Watch a service group
case SERVICE_GROUP_MODIFY: // Modify a service group
require_once $path . 'formServiceGroup.php';
break;
case SERVICE_GROUP_ACTIVATION: // Activate a service group
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceGroupInDB($serviceGroupId);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceGroup.php';
break;
case SERVICE_GROUP_DEACTIVATION: // Deactivate a service group
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceGroupInDB($serviceGroupId);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceGroup.php';
break;
case SERVICE_GROUP_DUPLICATION: // Duplicate n service groups
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleServiceGroupInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceGroup.php';
break;
case SERVICE_GROUP_DELETION: // Delete n service groups
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteServiceGroupInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceGroup.php';
break;
default:
require_once $path . 'listServiceGroup.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/servicegroup/help.php | centreon/www/include/configuration/configObject/servicegroup/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['servicegroup_name'] = dgettext(
'help',
'Define a short name for the service group here. The short name will be used to display the service '
. 'group in monitoring, views and reporting.'
);
$help['alias'] = dgettext('help', 'Define a longer name or description for the service group here.');
$help['members'] = dgettext(
'help',
'This is a list of host-bound services that should be included in this service group.'
);
$help['hg_members'] = dgettext(
'help',
'This is a list of host group-bound services that should be included in this service group.'
);
$help['st_members'] = dgettext(
'help',
'This is a list of service templates that should be included in this service group. Service template needs '
. 'to be associated with a host template in order to show up here.'
);
// unsupported in Centreon
$help['servicegroup_members'] = dgettext(
'help',
'This optional directive can be used to include services from other "sub" service groups in this service group.'
);
$help['notes'] = dgettext(
'help',
'This directive is used to define an optional string of notes pertaining to the service group. If you '
. 'specify a note here, you will see it in the extended information CGI (when you are viewing information '
. 'about the specified service group).'
);
$help['notes_url'] = dgettext(
'help',
'This directive is used to define an optional URL that can be used to provide more information about the '
. 'service group. Any valid URL can be used. If you plan on using relative paths, the base path will be '
. 'the same as what is used to access the CGIs (i.e. /cgi-bin/nagios/). This can be very useful if you want '
. 'to make detailed information on the service group, emergency contact methods, '
. 'etc. available to other support staff.'
);
$help['action_url'] = dgettext(
'help',
'This directive is used to define an optional URL that can be used to provide more actions to be performed '
. 'on the service group. Any valid URL can be used. If you plan on using relative paths, the base path will '
. 'be the same as what is used to access the CGIs (i.e. /cgi-bin/nagios/).'
);
$help['geo_coords'] = dgettext(
'help',
'Geographical coordinates use by Centreon Map module to position element on map. Define "Latitude,Longitude", '
. 'for example for Paris coordinates set "48.51,2.20"'
);
$help['resource_access_rules'] = dgettext('help', 'Resource access rule to which the service group should be linked');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/servicegroup/DB-Func.php | centreon/www/include/configuration/configObject/servicegroup/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
function testServiceGroupExistence($name = null)
{
global $pearDB, $form, $centreon;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('sg_id');
}
$sgName = HtmlAnalyzer::sanitizeAndRemoveTags($name);
$statement = $pearDB->prepare('SELECT sg_name, sg_id FROM servicegroup WHERE sg_name = :sg_name');
$statement->bindValue(':sg_name', $sgName, PDO::PARAM_STR);
$statement->execute();
$sg = $statement->fetch();
return ! ($statement->rowCount() >= 1 && $sg['sg_id'] !== (int) $id);
}
function enableServiceGroupInDB($sgId = null)
{
if (! $sgId) {
return;
}
global $pearDB, $centreon;
$sgId = filter_var($sgId, FILTER_VALIDATE_INT);
$statement = $pearDB->prepare("UPDATE servicegroup SET sg_activate = '1' WHERE sg_id = :sg_id");
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
$statement2 = $pearDB->prepare('SELECT sg_name FROM `servicegroup` WHERE `sg_id` = :sg_id LIMIT 1');
$statement2->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement2->execute();
$row = $statement2->fetch();
signalConfigurationChange('servicegroup', $sgId);
$centreon->CentreonLogAction->insertLog('servicegroup', $sgId, $row['sg_name'], 'enable');
}
function disableServiceGroupInDB($sgId = null)
{
if (! $sgId) {
return;
}
global $pearDB, $centreon;
$sgId = filter_var($sgId, FILTER_VALIDATE_INT);
$statement = $pearDB->prepare("UPDATE servicegroup SET sg_activate = '0' WHERE sg_id = :sg_id");
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
$statement2 = $pearDB->prepare('SELECT sg_name FROM `servicegroup` WHERE `sg_id` = :sg_id LIMIT 1');
$statement2->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement2->execute();
$row = $statement2->fetch();
signalConfigurationChange('servicegroup', $sgId, [], false);
$centreon->CentreonLogAction->insertLog('servicegroup', $sgId, $row['sg_name'], 'disable');
}
/**
* @param int $servicegroupId
*/
function removeRelationLastServicegroupDependency(int $servicegroupId): void
{
global $pearDB;
$query = 'SELECT count(dependency_dep_id) AS nb_dependency , dependency_dep_id AS id
FROM dependency_servicegroupParent_relation
WHERE dependency_dep_id = (SELECT dependency_dep_id FROM dependency_servicegroupParent_relation
WHERE servicegroup_sg_id = ' . $servicegroupId . ')
GROUP BY dependency_dep_id';
$dbResult = $pearDB->query($query);
$result = $dbResult->fetch();
// is last parent
if (isset($result['nb_dependency']) && $result['nb_dependency'] == 1) {
$pearDB->query('DELETE FROM dependency WHERE dep_id = ' . $result['id']);
}
}
/**
* @param array $serviceGroups
*/
function deleteServiceGroupInDB($serviceGroups = [])
{
global $pearDB, $centreon;
foreach (array_keys($serviceGroups) as $key) {
$sgId = filter_var($key, FILTER_VALIDATE_INT);
$previousPollerIds = getPollersForConfigChangeFlagFromServicegroupId((int) $sgId);
removeRelationLastServicegroupDependency((int) $sgId);
$statement = $pearDB->prepare('SELECT sg_name FROM `servicegroup` WHERE `sg_id` = :sg_id LIMIT 1');
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
$row = $statement->fetch();
$statement2 = $pearDB->prepare('DELETE FROM servicegroup WHERE sg_id = :sg_id');
$statement2->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement2->execute();
signalConfigurationChange('servicegroup', $sgId, $previousPollerIds);
$centreon->CentreonLogAction->insertLog('servicegroup', $key, $row['sg_name'], 'd');
}
$centreon->user->access->updateACL();
}
function multipleServiceGroupInDB($serviceGroups = [], $nbrDup = [])
{
global $pearDB, $centreon;
$sgAcl = [];
foreach (array_keys($serviceGroups) as $key) {
$sgId = filter_var($key, FILTER_VALIDATE_INT);
$statement = $pearDB->prepare('SELECT * FROM servicegroup WHERE sg_id = :sg_id LIMIT 1');
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
$row = $statement->fetch();
$row['sg_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$bindParams = [];
foreach ($row as $key2 => $value2) {
switch ($key2) {
case 'sg_name':
$value2 = HtmlAnalyzer::sanitizeAndRemoveTags($value2);
$sgName = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
$bindParams[':sg_name'] = [PDO::PARAM_STR => $value2];
break;
case 'sg_alias':
$value2 = HtmlAnalyzer::sanitizeAndRemoveTags($value2);
$bindParams[':sg_alias'] = [PDO::PARAM_STR => $value2];
break;
case 'sg_comment':
$value2 = HtmlAnalyzer::sanitizeAndRemoveTags($value2);
$value2
? $bindParams[':sg_comment'] = [PDO::PARAM_STR => $value2]
: $bindParams[':sg_comment'] = [PDO::PARAM_NULL => null];
break;
case 'geo_coords':
centreonUtils::validateGeoCoords($value2)
? $bindParams[':geo_coords'] = [PDO::PARAM_STR => $value2]
: $bindParams[':geo_coords'] = [PDO::PARAM_NULL => null];
break;
case 'sg_activate':
$value2 = filter_var($value2, FILTER_VALIDATE_REGEXP, [
'options' => [
'regexp' => '/^0|1$/',
],
]);
$value2
? $bindParams[':sg_activate'] = [PDO::PARAM_STR => $value2]
: $bindParams[':sg_activate'] = [PDO::PARAM_STR => '0'];
break;
}
if ($key2 != 'sg_id') {
$fields[$key2] = $value2;
}
if (isset($sgName)) {
$fields['sg_name'] = $sgName;
}
}
if (testServiceGroupExistence($sgName)) {
if (! empty($bindParams)) {
$statement = $pearDB->prepare('
INSERT INTO servicegroup
VALUES (NULL, :sg_name, :sg_alias, :sg_comment, :geo_coords, :sg_activate)
');
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$statement->bindValue($token, $value, $paramType);
}
}
$statement->execute();
}
$dbResult = $pearDB->query('SELECT MAX(sg_id) FROM servicegroup');
$maxId = $dbResult->fetch();
if (isset($maxId['MAX(sg_id)'])) {
$sgAcl[$maxId['MAX(sg_id)']] = $sgId;
$dbResult->closeCursor();
$statement = $pearDB->prepare('
SELECT DISTINCT sgr.host_host_id, sgr.hostgroup_hg_id, sgr.service_service_id
FROM servicegroup_relation sgr WHERE sgr.servicegroup_sg_id = :sg_id
');
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
$fields['sg_hgServices'] = '';
while ($service = $statement->fetch()) {
$bindParams = [];
foreach ($service as $key2 => $value2) {
switch ($key2) {
case 'host_host_id':
$value2 = filter_var($value2, FILTER_VALIDATE_INT);
$value2
? $bindParams[':host_host_id'] = [PDO::PARAM_INT => $value2]
: $bindParams[':host_host_id'] = [PDO::PARAM_NULL => null];
break;
case 'hostgroup_hg_id':
$value2 = filter_var($value2, FILTER_VALIDATE_INT);
$value2
? $bindParams[':hostgroup_hg_id'] = [PDO::PARAM_INT => $value2]
: $bindParams[':hostgroup_hg_id'] = [PDO::PARAM_NULL => null];
break;
case 'service_service_id':
$value2 = filter_var($value2, FILTER_VALIDATE_INT);
$value2
? $bindParams[':service_service_id'] = [PDO::PARAM_INT => $value2]
: $bindParams[':service_service_id'] = [PDO::PARAM_NULL => null];
break;
}
$bindParams[':servicegroup_sg_id'] = [PDO::PARAM_INT => $maxId['MAX(sg_id)']];
}
$statement2 = $pearDB->prepare('
INSERT INTO servicegroup_relation
(host_host_id, hostgroup_hg_id, service_service_id, servicegroup_sg_id)
VALUES (:host_host_id, :hostgroup_hg_id, :service_service_id, :servicegroup_sg_id)
');
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$statement2->bindValue($token, $value, $paramType);
}
}
$statement2->execute();
$fields['sg_hgServices'] .= $service['service_service_id'] . ',';
}
$fields['sg_hgServices'] = trim($fields['sg_hgServices'], ',');
signalConfigurationChange('servicegroup', $maxId['MAX(sg_id)']);
$centreon->CentreonLogAction->insertLog(
'servicegroup',
$maxId['MAX(sg_id)'],
$sgName,
'a',
$fields
);
}
}
}
}
CentreonACL::duplicateSgAcl($sgAcl);
$centreon->user->access->updateACL();
}
function updateServiceGroupAcl(int $serviceGroupId, array $submittedValues = []): void
{
global $pearDB;
$ruleIds = $submittedValues['resource_access_rules'];
foreach ($ruleIds as $ruleId) {
$datasets = findDatasetsByRuleId($ruleId);
/**
* see if at least a dataset filter saved is of type servicegroup
* if so then add the new servicegroup to the dataset
* otherwise create a new dataset for this servicegroup
*/
$serviceGroupDatasetFilters = array_values(
array_filter(
$datasets,
fn (array $dataset) => $dataset['dataset_filter_type'] === 'servicegroup'
)
);
// No dataset_filter of type service group found. Create a new one
if ($serviceGroupDatasetFilters === []) {
// get the dataset with the highest ID (last one added) which is the first element of the datasets array
$lastDatasetAdded = $datasets[0];
preg_match('/dataset_for_rule_\d+_(\d+)/', $lastDatasetAdded['dataset_name'], $matches);
// calculate the new dataset_name
$newDatasetName = 'dataset_for_rule_' . $ruleId . '_' . ((int) $matches[1] + 1);
if ($pearDB->beginTransaction()) {
try {
$datasetId = createNewDataset(datasetName: $newDatasetName);
linkDatasetToRule(datasetId: $datasetId, ruleId: $ruleId);
linkServiceGroupToDataset(datasetId: $datasetId, serviceGroupId: $serviceGroupId);
createNewDatasetFilter(datasetId: $datasetId, ruleId: $ruleId, serviceGroupId: $serviceGroupId);
$pearDB->commit();
} catch (Throwable $exception) {
$pearDB->rollBack();
throw $exception;
}
}
} elseif ($pearDB->beginTransaction()) {
try {
linkServiceGroupToDataset(datasetId: $serviceGroupDatasetFilters[0]['dataset_id'], serviceGroupId: $serviceGroupId);
// Expend the existing hostgroup dataset_filter
$expendedResourceIds = $serviceGroupDatasetFilters[0]['dataset_filter_resources'] . ', ' . $serviceGroupId;
updateDatasetFiltersResourceIds(
datasetFilterId: $serviceGroupDatasetFilters[0]['dataset_filter_id'],
resourceIds: $expendedResourceIds
);
$pearDB->commit();
} catch (Throwable $exception) {
$pearDB->rollBack();
throw $exception;
}
}
}
}
/**
* @param int $datasetFilterId
* @param string $resourceIds
*/
function updateDatasetFiltersResourceIds(int $datasetFilterId, string $resourceIds): void
{
global $pearDB;
$request = <<<'SQL'
UPDATE dataset_filters SET resource_ids = :resourceIds WHERE `id` = :datasetFilterId
SQL;
$statement = $pearDB->prepare($request);
$statement->bindValue(':datasetFilterId', $datasetFilterId, PDO::PARAM_INT);
$statement->bindValue(':resourceIds', $resourceIds, PDO::PARAM_STR);
$statement->execute();
}
/**
* @param int $datasetId
* @param int $serviceGroupId
*/
function linkServiceGroupToDataset(int $datasetId, int $serviceGroupId): void
{
global $pearDB;
$query = <<<'SQL'
INSERT INTO acl_resources_sg_relations (sg_id, acl_res_id) VALUES (:serviceGroupId, :datasetId)
SQL;
$statement = $pearDB->prepare($query);
$statement->bindValue(':datasetId', $datasetId, PDO::PARAM_INT);
$statement->bindValue(':serviceGroupId', $serviceGroupId, PDO::PARAM_INT);
$statement->execute();
}
/**
* @param int $datasetId
* @param int $ruleId
* @param int $serviceGroupId
*/
function createNewDatasetFilter(int $datasetId, int $ruleId, int $serviceGroupId): void
{
global $pearDB;
$query = <<<'SQL'
INSERT INTO dataset_filters (`type`, acl_resource_id, acl_group_id, resource_ids)
VALUES ('servicegroup', :datasetId, :ruleId, :serviceGroupId)
SQL;
$statement = $pearDB->prepare($query);
$statement->bindValue(':datasetId', $datasetId, PDO::PARAM_INT);
$statement->bindValue(':ruleId', $ruleId, PDO::PARAM_INT);
$statement->bindValue(':serviceGroupId', $serviceGroupId, PDO::PARAM_STR);
$statement->execute();
}
/**
* @param string $datasetName
* @return int
*/
function createNewDataset(string $datasetName): int
{
global $pearDB;
// create new dataset
$query = <<<'SQL'
INSERT INTO acl_resources (acl_res_name, all_hosts, all_hostgroups, all_servicegroups, acl_res_activate, changed, cloud_specific)
VALUES (:name, '0', '0', '0', '1', 1, 1)
SQL;
$statement = $pearDB->prepare($query);
$statement->bindValue(':name', $datasetName, PDO::PARAM_STR);
$statement->execute();
return $pearDB->lastInsertId();
}
/**
* @param int $ruleId
*
* @throws PDOException
*
* @return list<array{
* dataset_name: string,
* dataset_filter_id: int,
* dataset_filter_parent_id: int|null,
* dataset_filter_type: string,
* dataset_filter_resources: string,
* dataset_id: int,
* rule_id: int
* }>|array{} */
function findDatasetsByRuleId(int $ruleId): array
{
global $pearDB;
$request = <<<'SQL'
SELECT
dataset.acl_res_name AS dataset_name,
id AS dataset_filter_id,
parent_id AS dataset_filter_parent_id,
type AS dataset_filter_type,
resource_ids AS dataset_filter_resources,
acl_resource_id AS dataset_id,
acl_group_id AS rule_id
FROM dataset_filters
INNER JOIN acl_resources AS dataset
ON dataset.acl_res_id = dataset_filters.acl_resource_id
WHERE dataset_filters.acl_group_id = :ruleId
ORDER BY dataset_id DESC
SQL;
$statement = $pearDB->prepare($request);
$statement->bindValue(':ruleId', $ruleId, PDO::PARAM_INT);
$statement->execute();
if ($record = $statement->fetchAll(PDO::FETCH_ASSOC)) {
return $record;
}
return [];
}
function insertServiceGroupInDB(bool $isCloudPlatform = false, array $submittedValues = [])
{
global $centreon, $form;
$submittedValues = $submittedValues ?: $form->getSubmitValues();
$serviceGroupId = insertServiceGroup($submittedValues);
updateServiceGroupServices($serviceGroupId, $submittedValues);
// Only apply ACL for cloud context
if ($isCloudPlatform) {
updateServiceGroupAcl(serviceGroupId: $serviceGroupId, submittedValues: $submittedValues);
}
signalConfigurationChange('servicegroup', $serviceGroupId);
$centreon->user->access->updateACL();
return $serviceGroupId;
}
/**
* @param int $datasetId
* @param int $ruleId
*/
function linkDatasetToRule(int $datasetId, int $ruleId): void
{
global $pearDB;
// link dataset to the rule
$query = <<<'SQL'
INSERT INTO acl_res_group_relations (acl_res_id, acl_group_id) VALUES (:datasetId, :ruleId)
SQL;
$statement = $pearDB->prepare($query);
$statement->bindValue(':ruleId', $ruleId, PDO::PARAM_INT);
$statement->bindValue(':datasetId', $datasetId, PDO::PARAM_INT);
$statement->execute();
}
function updateServiceGroupInDB(
bool $isCloudPlatform = false,
$serviceGroupId = null,
$submittedValues = [],
$increment = false,
) {
global $centreon, $form;
if (! $serviceGroupId) {
return;
}
$submittedValues = $submittedValues ?: $form->getSubmitValues();
$previousPollerIds = getPollersForConfigChangeFlagFromServiceGroupId($serviceGroupId);
updateServiceGroup($serviceGroupId, $submittedValues);
updateServiceGroupServices($serviceGroupId, $submittedValues, $increment);
if ($isCloudPlatform) {
updateServiceGroupAcl(serviceGroupId: $serviceGroupId, submittedValues: $submittedValues);
}
signalConfigurationChange('servicegroup', $serviceGroupId, $previousPollerIds);
$centreon->user->access->updateACL();
}
function insertServiceGroup($submittedValues = [])
{
global $pearDB, $centreon;
$bindParams = [];
foreach ($submittedValues as $key => $value) {
switch ($key) {
case 'sg_name':
$value = HtmlAnalyzer::sanitizeAndRemoveTags($value);
$bindParams[':sg_name'] = [PDO::PARAM_STR => $value];
break;
case 'sg_alias':
$value = HtmlAnalyzer::sanitizeAndRemoveTags($value);
$bindParams[':sg_alias'] = [PDO::PARAM_STR => $value];
break;
case 'sg_comment':
$value = HtmlAnalyzer::sanitizeAndRemoveTags($value);
$value
? $bindParams[':sg_comment'] = [PDO::PARAM_STR => $value]
: $bindParams[':sg_comment'] = [PDO::PARAM_NULL => null];
break;
case 'geo_coords':
centreonUtils::validateGeoCoords($value)
? $bindParams[':geo_coords'] = [PDO::PARAM_STR => $value]
: $bindParams[':geo_coords'] = [PDO::PARAM_NULL => null];
break;
case 'sg_activate':
$value = filter_var($value['sg_activate'], FILTER_VALIDATE_REGEXP, [
'options' => [
'regexp' => '/^0|1$/',
],
]);
$value
? $bindParams[':sg_activate'] = [PDO::PARAM_STR => $value]
: $bindParams[':sg_activate'] = [PDO::PARAM_STR => '0'];
break;
}
}
$statement = $pearDB->prepare('
INSERT INTO servicegroup (sg_name, sg_alias, sg_comment, geo_coords, sg_activate)
VALUES (:sg_name, :sg_alias, :sg_comment, :geo_coords, :sg_activate)
');
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$statement->bindValue($token, $value, $paramType);
}
}
$statement->execute();
$dbResult = $pearDB->query('SELECT MAX(sg_id) FROM servicegroup');
$sgId = $dbResult->fetch();
$dbResult->closeCursor();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($submittedValues);
$centreon->CentreonLogAction->insertLog(
'servicegroup',
$sgId['MAX(sg_id)'],
htmlentities($submittedValues['sg_name'], ENT_QUOTES, 'UTF-8'),
'a',
$fields
);
return $sgId['MAX(sg_id)'];
}
function updateServiceGroup($serviceGroupId, $submittedValues = [])
{
global $pearDB, $centreon;
if (! $serviceGroupId) {
return;
}
$bindParams = [];
$serviceGroupId = filter_var($serviceGroupId, FILTER_VALIDATE_INT);
$bindParams[':sg_id'] = [PDO::PARAM_INT => $serviceGroupId];
foreach ($submittedValues as $key => $value) {
switch ($key) {
case 'sg_name':
$value = HtmlAnalyzer::sanitizeAndRemoveTags($value);
$bindParams[':sg_name'] = [PDO::PARAM_STR => $value];
break;
case 'sg_alias':
$value = HtmlAnalyzer::sanitizeAndRemoveTags($value);
$bindParams[':sg_alias'] = [PDO::PARAM_STR => $value];
break;
case 'sg_comment':
$value = HtmlAnalyzer::sanitizeAndRemoveTags($value);
$value
? $bindParams[':sg_comment'] = [PDO::PARAM_STR => $value]
: $bindParams[':sg_comment'] = [PDO::PARAM_NULL => null];
break;
case 'geo_coords':
centreonUtils::validateGeoCoords($value)
? $bindParams[':geo_coords'] = [PDO::PARAM_STR => $value]
: $bindParams[':geo_coords'] = [PDO::PARAM_NULL => null];
break;
case 'sg_activate':
$value = filter_var($value['sg_activate'], FILTER_VALIDATE_REGEXP, [
'options' => [
'regexp' => '/^0|1$/',
],
]);
$value
? $bindParams[':sg_activate'] = [PDO::PARAM_STR => $value]
: $bindParams[':sg_activate'] = [PDO::PARAM_STR => '0'];
break;
}
}
$statement = $pearDB->prepare(
<<<'SQL'
UPDATE servicegroup SET
sg_name = :sg_name,
sg_alias = :sg_alias,
sg_comment = :sg_comment,
geo_coords = :geo_coords,
sg_activate = :sg_activate
WHERE sg_id = :sg_id
SQL
);
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$statement->bindValue($token, $value, $paramType);
}
}
$statement->execute();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($submittedValues);
$centreon->CentreonLogAction->insertLog(
'servicegroup',
$serviceGroupId,
htmlentities($submittedValues['sg_name'], ENT_QUOTES, 'UTF-8'),
'c',
$fields
);
}
function updateServiceGroupServices($sgId, $ret = [], $increment = false)
{
if (! $sgId) {
return;
}
global $pearDB, $form;
$sgId = filter_var($sgId, FILTER_VALIDATE_INT);
if ($increment == false && $sgId !== false) {
$statement = $pearDB->prepare('
DELETE FROM servicegroup_relation
WHERE servicegroup_sg_id = :sg_id
');
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
}
// service templates
$retTmp = $ret['sg_tServices'] ?? $form->getSubmitValue('sg_tServices');
if ($retTmp) {
$statement = $pearDB->prepare('
SELECT servicegroup_sg_id service FROM servicegroup_relation
WHERE host_host_id = :host_host_id AND service_service_id = :service_service_id
AND servicegroup_sg_id = :sg_id
');
$statement2 = $pearDB->prepare('
INSERT INTO servicegroup_relation (host_host_id, service_service_id, servicegroup_sg_id)
VALUES (:host_host_id, :service_service_id, :servicegroup_sg_id)
');
$counter = count($retTmp);
for ($i = 0; $i < $counter; $i++) {
if (isset($retTmp[$i]) && $retTmp[$i]) {
$t = preg_split("/\-/", $retTmp[$i]);
$hostHostId = filter_var($t[0], FILTER_VALIDATE_INT);
$serviceServiceId = filter_var($t[1], FILTER_VALIDATE_INT);
$statement->bindValue(':host_host_id', $hostHostId, PDO::PARAM_INT);
$statement->bindValue(':service_service_id', $serviceServiceId, PDO::PARAM_INT);
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
if (! $statement->rowCount()) {
$statement2->bindValue(':host_host_id', $hostHostId, PDO::PARAM_INT);
$statement2->bindValue(':service_service_id', $serviceServiceId, PDO::PARAM_INT);
$statement2->bindValue(':servicegroup_sg_id', $sgId, PDO::PARAM_INT);
$statement2->execute();
}
}
}
}
// regular services
$retTmp = $ret['sg_hServices'] ?? CentreonUtils::mergeWithInitialValues($form, 'sg_hServices');
$statement = $pearDB->prepare('
SELECT servicegroup_sg_id service FROM servicegroup_relation
WHERE host_host_id = :host_host_id AND service_service_id = :service_service_id
AND servicegroup_sg_id = :sg_id
');
$statement2 = $pearDB->prepare('
INSERT INTO servicegroup_relation (host_host_id, service_service_id, servicegroup_sg_id)
VALUES (:host_host_id, :service_service_id, :servicegroup_sg_id)
');
$counter = count($retTmp);
for ($i = 0; $i < $counter; $i++) {
if (isset($retTmp[$i]) && $retTmp[$i]) {
$t = preg_split("/\-/", $retTmp[$i]);
$hostHostId = filter_var($t[0], FILTER_VALIDATE_INT);
$serviceServiceId = filter_var($t[1], FILTER_VALIDATE_INT);
$statement->bindValue(':host_host_id', $hostHostId, PDO::PARAM_INT);
$statement->bindValue(':service_service_id', $serviceServiceId, PDO::PARAM_INT);
$statement->bindValue(':sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
if (! $statement->rowCount()) {
$statement2->bindValue(':host_host_id', $hostHostId, PDO::PARAM_INT);
$statement2->bindValue(':service_service_id', $serviceServiceId, PDO::PARAM_INT);
$statement2->bindValue(':servicegroup_sg_id', $sgId, PDO::PARAM_INT);
$statement2->execute();
}
}
}
// hostgroup services
$retTmp = $ret['sg_hgServices'] ?? CentreonUtils::mergeWithInitialValues($form, 'sg_hgServices');
$statement = $pearDB->prepare('
SELECT servicegroup_sg_id service FROM servicegroup_relation
WHERE hostgroup_hg_id = :hostgroup_hg_id AND service_service_id = :service_service_id
AND servicegroup_sg_id = :servicegroup_sg_id
');
$statement2 = $pearDB->prepare('
INSERT INTO servicegroup_relation (hostgroup_hg_id, service_service_id, servicegroup_sg_id)
VALUES (:hostgroup_hg_id, :service_service_id, :servicegroup_sg_id)
');
$counter = count($retTmp);
for ($i = 0; $i < $counter; $i++) {
$t = preg_split("/\-/", $retTmp[$i]);
$hostGroupId = filter_var($t[0], FILTER_VALIDATE_INT);
$serviceServiceId = filter_var($t[1], FILTER_VALIDATE_INT);
$statement->bindValue(':hostgroup_hg_id', $hostGroupId, PDO::PARAM_INT);
$statement->bindValue(':service_service_id', $serviceServiceId, PDO::PARAM_INT);
$statement->bindValue(':servicegroup_sg_id', $sgId, PDO::PARAM_INT);
$statement->execute();
if (! $statement->rowCount()) {
$statement2->bindValue(':hostgroup_hg_id', $hostGroupId, PDO::PARAM_INT);
$statement2->bindValue(':service_service_id', $serviceServiceId, PDO::PARAM_INT);
$statement2->bindValue(':servicegroup_sg_id', $sgId, PDO::PARAM_INT);
$statement2->execute();
}
}
}
/**
* @param int $servicegroupId
* @return int[]
*/
function getPollersForConfigChangeFlagFromServiceGroupId(int $servicegroupId): array
{
$hostIds = findHostsForConfigChangeFlagFromServiceGroupId($servicegroupId);
return findPollersForConfigChangeFlagFromHostIds($hostIds);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/servicegroup/formServiceGroup.php | centreon/www/include/configuration/configObject/servicegroup/formServiceGroup.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
const BASE_ROUTE = './include/common/webServices/rest/internal.php';
if (! $centreon->user->admin) {
if ($serviceGroupId && ! str_contains($sgString, "'" . $serviceGroupId . "'")) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this service group'));
return;
}
}
$initialValues = ['sg_hServices' => [], 'sg_hgServices' => []];
// Database retrieve information for ServiceGroup
$sg = [];
$hServices = [];
if (($o === SERVICE_GROUP_MODIFY || $o === SERVICE_GROUP_WATCH) && $serviceGroupId) {
$DBRESULT = $pearDB->prepare('SELECT * FROM servicegroup WHERE sg_id = :sg_id LIMIT 1');
$DBRESULT->bindValue(':sg_id', $serviceGroupId, PDO::PARAM_INT);
$DBRESULT->execute();
// Set base value
$sg = array_map('myDecode', $DBRESULT->fetchRow());
}
$attrsText = ['size' => '30'];
$attrsAdvSelect = ['style' => 'width: 400px; height: 250px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br />'
. '<br /><br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list';
$attrServices = [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $route,
'multiple' => true,
'linkedObject' => 'centreonService',
];
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicetemplate&action=list&l=1';
$attrServicetemplates = [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $route,
'multiple' => true,
'linkedObject' => 'centreonServicetemplates',
'defaultDatasetOptions' => ['withHosttemplate' => true],
];
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list&t=hostgroup';
$attrHostgroups = [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $route,
'multiple' => true,
'linkedObject' => 'centreonHostgroups',
];
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o === SERVICE_GROUP_ADD) {
$form->addElement('header', 'title', _('Add a Service Group'));
} elseif ($o === SERVICE_GROUP_MODIFY) {
$form->addElement('header', 'title', _('Modify a Service Group'));
} elseif ($o === SERVICE_GROUP_WATCH) {
$form->addElement('header', 'title', _('View a Service Group'));
}
//
// # Contact basic information
//
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'sg_name', _('Name'), $attrsText);
$form->addElement('text', 'sg_alias', _('Description'), $attrsText);
$form->registerRule('validate_geo_coords', 'function', 'validateGeoCoords');
$form->addElement('text', 'geo_coords', _('Geo coordinates'), $attrsText);
$form->addRule('geo_coords', _('geo coords are not valid'), 'validate_geo_coords');
$form->applyFilter('geo_coords', 'truncateGeoCoords');
$form->addElement('header', 'relation', _('Relations'));
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service'
. '&action=defaultValues&target=servicegroups&field=sg_hServices&id=' . $serviceGroupId;
$attrService1 = array_merge(
$attrServices,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'sg_hServices', _('Linked Host Services'), [], $attrService1);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service'
. '&action=defaultValues&target=servicegroups&field=sg_hgServices&id=' . $serviceGroupId;
$attrHostgroup1 = array_merge(
$attrHostgroups,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'sg_hgServices', _('Linked Host Group Services'), [], $attrHostgroup1);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicetemplate'
. '&action=defaultValues&target=servicegroups&field=sg_tServices&id=' . $serviceGroupId;
$attrServicetemplate1 = array_merge(
$attrServicetemplates,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'sg_tServices', _('Linked Service Templates'), [], $attrServicetemplate1);
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$sgActivation[] = $form->createElement('radio', 'sg_activate', null, _('Enabled'), '1');
$sgActivation[] = $form->createElement('radio', 'sg_activate', null, _('Disabled'), '0');
$form->addGroup($sgActivation, 'sg_activate', _('Status'), ' ');
$form->setDefaults(['sg_activate' => '1']);
$form->addElement('textarea', 'sg_comment', _('Comments'), $attrsTextarea);
if (
$o === SERVICE_GROUP_ADD
&& $isCloudPlatform === true
) {
$form->addElement(
'select2',
'resource_access_rules',
_('Resource Access Rule'),
[],
[
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => BASE_ROUTE . '?object=centreon_administration_aclgroup&action=list&use_ram=true',
'defaultDataset' => [],
'multiple' => true,
]
);
$form->addRule('resource_access_rules', _('Mandatory field for ACL purpose.'), 'required');
}
$form->addElement('hidden', 'sg_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
// Form Rules
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['sg_name']);
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('sg_name', 'myReplace');
$form->addRule('sg_name', _('Compulsory Name'), 'required');
$form->addRule('sg_alias', _('Compulsory Description'), 'required');
$form->registerRule('exist', 'callback', 'testServiceGroupExistence');
$form->addRule('sg_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Just watch a Service Group information
if ($o === SERVICE_GROUP_WATCH) {
if ($centreon->user->access->page($p) !== 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&sg_id=' . $serviceGroupId . "'"]
);
}
$form->setDefaults($sg);
$form->freeze();
} elseif ($o === SERVICE_GROUP_MODIFY) { // Modify a Service Group information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($sg);
} elseif ($o === SERVICE_GROUP_ADD) { // Add a Service Group information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$tpl->assign('nagios', $oreon->user->get_version());
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", '
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, -300, '
. 'SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$valid = false;
if ($form->validate()) {
$sgObj = $form->getElement('sg_id');
if ($form->getSubmitValue('submitA')) {
$sgObj->setValue(insertServiceGroupInDB(isCloudPlatform: $isCloudPlatform));
} elseif ($form->getSubmitValue('submitC')) {
updateServiceGroupInDB(
isCloudPlatform: $isCloudPlatform,
serviceGroupId: $sgObj->getValue()
);
}
$o = null;
$valid = true;
}
$action = $form->getSubmitValue('action');
if ($valid) {
require_once $path . 'listServiceGroup.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
if ($isCloudPlatform) {
$tpl->assign('resourceAccess', _('Resource Access Management'));
}
$tpl->display('formServiceGroup.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host/listHost.php | centreon/www/include/configuration/configObject/host/listHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
require_once './include/common/autoNumLimit.php';
require_once _CENTREON_PATH_ . '/www/class/centreonHost.class.php';
// Init Host Method
$host_method = new CentreonHost($pearDB);
// Object init
$mediaObj = new CentreonMedia($pearDB);
// Get Extended informations
$ehiCache = [];
$dbResult = $pearDB->query('SELECT ehi_icon_image, host_host_id FROM extended_host_information');
while ($ehi = $dbResult->fetch()) {
$ehiCache[$ehi['host_host_id']] = $ehi['ehi_icon_image'];
}
$dbResult->closeCursor();
$mainQueryParameters = [];
// initializing filters values
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchH'] ?? $_GET['searchH'] ?? null
);
$poller = filter_var(
$_POST['poller'] ?? $_GET['poller'] ?? 0,
FILTER_VALIDATE_INT
);
$hostgroup = filter_var(
$_POST['hostgroup'] ?? $_GET['hostgroup'] ?? 0,
FILTER_VALIDATE_INT
);
$template = filter_var(
$_POST['template'] ?? $_GET['template'] ?? 0,
FILTER_VALIDATE_INT
);
$status = filter_var(
$_POST['status'] ?? $_GET['status'] ?? 0,
FILTER_VALIDATE_INT
);
if (isset($_POST['search']) || isset($_GET['search'])) {
// saving chosen filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['searchH'] = $search;
$centreon->historySearch[$url]['poller'] = $poller;
$centreon->historySearch[$url]['hostgroup'] = $hostgroup;
$centreon->historySearch[$url]['template'] = $template;
$centreon->historySearch[$url]['status'] = $status;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['searchH'] ?? null;
$poller = $centreon->historySearch[$url]['poller'] ?? 0;
$hostgroup = $centreon->historySearch[$url]['hostgroup'] ?? 0;
$template = $centreon->historySearch[$url]['template'] ?? 0;
$status = $centreon->historySearch[$url]['status'] ?? 0;
}
// set object history
$centreon->poller = $poller;
$centreon->hostgroup = $hostgroup;
$centreon->template = $template;
// Status Filter
$statusFilter = [1 => _('Disabled'), 2 => _('Enabled')];
$sqlFilterCase = match((int) $status) {
2 => " AND host_activate = '1' ",
1 => " AND host_activate = '0' ",
default => '',
};
// Search active
$searchFilterQuery = '';
if (isset($search) && ! empty($search)) {
$search = str_replace('_', "\_", $search);
$mainQueryParameters[':search_string'] = [PDO::PARAM_STR => "%{$search}%"];
$searchFilterQuery = <<<'SQL'
(
h.host_name LIKE :search_string
OR host_alias LIKE :search_string
OR host_address LIKE :search_string
) AND
SQL;
}
$templateFROM = '';
if ($template) {
$templateFROM = <<<'SQL'
INNER JOIN host_template_relation htr
ON htr.host_host_id = h.host_id
AND htr.host_tpl_id = :host_tpl_id
SQL;
$mainQueryParameters[':host_tpl_id'] = [PDO::PARAM_INT => $template];
}
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Alias'));
$tpl->assign('headerMenu_address', _('IP Address / DNS'));
$tpl->assign('headerMenu_poller', _('Poller'));
$tpl->assign('headerMenu_parent', _('Templates'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
// Host list
$nagios_server = [];
$dbResult = $pearDB->query(
'SELECT ns.name, ns.id FROM nagios_server ns '
. ($aclPollerString != "''" ? $acl->queryBuilder('WHERE', 'ns.id', $aclPollerString) : '')
. ' ORDER BY ns.name'
);
while ($relation = $dbResult->fetch()) {
$nagios_server[$relation['id']] = HtmlSanitizer::createFromString($relation['name'])->sanitize()->getString();
}
$dbResult->closeCursor();
unset($relation);
$tab_relation = [];
$tab_relation_id = [];
$dbResult = $pearDB->query(
'SELECT nhr.host_host_id, nhr.nagios_server_id FROM ns_host_relation nhr'
. ($aclPollerString != "''" ? ' ' . $acl->queryBuilder('WHERE', 'nhr.nagios_server_id', $aclPollerString) : '')
);
while ($relation = $dbResult->fetch()) {
$tab_relation[$relation['host_host_id']] = $nagios_server[$relation['nagios_server_id']];
$tab_relation_id[$relation['host_host_id']] = $relation['nagios_server_id'];
}
$dbResult->closeCursor();
// Init Form
$form = new HTML_QuickFormCustom('select_form', 'POST', "?p={$p}");
// Different style between each lines
$style = 'one';
// select2 HG
$hostgroupsRoute = './api/internal.php?object=centreon_configuration_hostgroup&action=list';
$attrHostgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $hostgroupsRoute, 'multiple' => false, 'defaultDataset' => $hostgroup, 'linkedObject' => 'centreonHostgroups'];
$form->addElement('select2', 'hostgroup', '', [], $attrHostgroups);
// select2 Poller
$pollerRoute = './api/internal.php?object=centreon_configuration_poller&action=list';
$attrPoller = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $pollerRoute, 'multiple' => false, 'defaultDataset' => $poller, 'linkedObject' => 'centreonInstance'];
$form->addElement('select2', 'poller', '', [], $attrPoller);
// select2 Host Template
$hostTplRoute = './api/internal.php?object=centreon_configuration_hosttemplate&action=list';
$attrHosttemplates = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $hostTplRoute, 'multiple' => false, 'defaultDataset' => $template, 'linkedObject' => 'centreonHosttemplates'];
$form->addElement('select2', 'template', '', [], $attrHosttemplates);
// select2 Host Status
$attrHostStatus = null;
$statusDefault = '';
if ($status) {
$statusDefault = [$statusFilter[$status] => $status];
}
$attrHostStatus = ['defaultDataset' => $statusDefault];
$form->addElement('select2', 'status', '', $statusFilter, $attrHostStatus);
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.pushState('', '', '?p=" . $p . "');"];
$subS = $form->addElement('submit', 'SearchB', _('Search'), $attrBtnSuccess);
// Select hosts
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'SearchB', _('Search'), $attrBtnSuccess);
// Select hosts
$aclFrom = '';
if (! $centreon->user->admin) {
$aclGroupIds = array_keys($acl->getAccessGroups());
$preparedValueNames = [];
foreach ($aclGroupIds as $index => $groupId) {
$preparedValueName = ':acl_group_id' . $index;
$preparedValueNames[] = $preparedValueName;
$mainQueryParameters[$preparedValueName] = [PDO::PARAM_INT => $groupId];
}
$aclSubRequest = implode(',', $preparedValueNames) ?: 0;
$aclFrom = <<<SQL
INNER JOIN `{$aclDbName}`.centreon_acl acl
ON acl.host_id = h.host_id
AND acl.service_id IS NULL
AND acl.group_id IN ({$aclSubRequest})
SQL;
}
if ($hostgroup) {
$mainQueryParameters[':host_group_id'] = [PDO::PARAM_INT => $hostgroup];
if ($poller) {
$mainQueryParameters[':poller_id'] = [PDO::PARAM_INT => $poller];
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
h.host_id, h.host_name, host_alias, host_address, host_activate, host_template_model_htm_id
FROM host h
INNER JOIN ns_host_relation nshr
ON nshr.host_host_id = h.host_id
AND nshr.nagios_server_id = :poller_id
INNER JOIN hostgroup_relation hr
ON hr.host_host_id = h.host_id
AND hr.hostgroup_hg_id = :host_group_id
{$templateFROM}
{$aclFrom}
WHERE {$searchFilterQuery}
h.host_register = '1'
{$sqlFilterCase}
ORDER BY h.host_name
LIMIT :offset, :limit
SQL;
} else {
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
h.host_id, h.host_name, host_alias, host_address, host_activate, host_template_model_htm_id
FROM host h
INNER JOIN hostgroup_relation hr
ON hr.host_host_id = h.host_id
AND hr.hostgroup_hg_id = :host_group_id
{$templateFROM}
{$aclFrom}
WHERE {$searchFilterQuery}
h.host_register = '1'
{$sqlFilterCase}
ORDER BY h.host_name
LIMIT :offset, :limit
SQL;
}
} elseif ($poller) {
$mainQueryParameters[':poller_id'] = [PDO::PARAM_INT => $poller];
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
h.host_id, h.host_name, host_alias, host_address, host_activate, host_template_model_htm_id
FROM host h
INNER JOIN ns_host_relation nshr
ON nshr.host_host_id = h.host_id
AND nshr.nagios_server_id = :poller_id
{$templateFROM}
{$aclFrom}
WHERE {$searchFilterQuery}
h.host_register = '1'
{$sqlFilterCase}
ORDER BY h.host_name
LIMIT :offset, :limit
SQL;
} else {
$request = <<<SQL
SELECT SQL_CALC_FOUND_ROWS DISTINCT
h.host_id, h.host_name, host_alias, host_address, host_activate, host_template_model_htm_id
FROM host h
{$templateFROM}
{$aclFrom}
WHERE {$searchFilterQuery}
host_register = '1'
{$sqlFilterCase}
ORDER BY h.host_name
LIMIT :offset, :limit
SQL;
}
$dbResult = $pearDB->prepare($request);
$mainQueryParameters[':offset'] = [PDO::PARAM_INT => (int) ($num * $limit)];
$mainQueryParameters[':limit'] = [PDO::PARAM_INT => (int) $limit];
foreach ($mainQueryParameters as $parameterName => $data) {
$type = key($data);
$value = $data[$type];
$dbResult->bindValue($parameterName, $value, $type);
}
$dbResult->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
$search = tidySearchKey($search, $advanced_search);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$search = str_replace('\_', '_', $search ?? '');
$centreonToken = createCSRFToken();
for ($i = 0; $host = $dbResult->fetch(); $i++) {
if (
! isset($poller)
|| $poller == 0
|| ($poller != 0 && $poller == $tab_relation_id[$host['host_id']])
) {
$selectedElements = $form->addElement(
'checkbox',
'select[' . $host['host_id'] . ']'
);
if ($host['host_activate']) {
$moptions = "<a href='main.php?p={$p}&host_id={$host['host_id']}"
. "&o=u&limit={$limit}&num={$num}&searchH={$search}"
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Disabled') . "'></a>";
} else {
$moptions = "<a href='main.php?p={$p}&host_id={$host['host_id']}"
. "&o=s&limit={$limit}&num={$num}&searchH={$search}"
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a>";
}
$moptions .= '<input onKeypress="if(event.keyCode > 31 && '
. '(event.keyCode < 45 || event.keyCode > 57)) event.returnValue = false; '
. 'if(event.which > 31 && (event.which < 45 || event.which > 57)) '
. "return false;\" maxlength=\"3\" size=\"3\" value='1' "
. "style=\"margin-bottom:0px;\" name='dupNbr[{$host['host_id']}]'></input>";
if (! $host['host_name']) {
$host['host_name'] = getMyHostField($host['host_id'], 'host_name');
}
// TPL List
$tplArr = [];
$tplStr = '';
// Create Template topology
$tplArr = getMyHostMultipleTemplateModels($host['host_id']);
if (count($tplArr)) {
$firstTpl = 1;
foreach ($tplArr as $key => $value) {
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
if ($firstTpl) {
$tplStr .= "<a href='main.php?p=60103&o=c&host_id={$key}'>{$value}</a>";
$firstTpl = 0;
} else {
$tplStr .= " | <a href='main.php?p=60103&o=c&host_id={$key}'>{$value}</a>";
}
}
}
// Check icon
$host_icone = returnSvg('www/img/icons/host.svg', 'var(--icons-fill-color)', 21, 21);
$isSvgFile = true;
if (
isset($ehiCache[$host['host_id']])
&& $ehiCache[$host['host_id']]
) {
$isSvgFile = false;
$host_icone = './img/media/' . $mediaObj->getFilename($ehiCache[$host['host_id']]);
} else {
$icone = $host_method->replaceMacroInString(
$host['host_id'],
getMyHostExtendedInfoImage(
$host['host_id'],
'ehi_icon_image',
1
)
);
if ($icone) {
$isSvgFile = false;
$host_icone = './img/media/' . $icone;
}
}
// Create Array Data for template list
$elemArr[$i] = [
'MenuClass' => 'list_' . $style,
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => $host['host_name'],
'RowMenu_name_link' => HtmlAnalyzer::sanitizeAndRemoveTags($host['host_name']),
'RowMenu_id' => $host['host_id'],
'RowMenu_icone' => $host_icone,
'RowMenu_link' => 'main.php?p=' . $p . '&o=c&host_id=' . $host['host_id'],
'RowMenu_desc' => $host['host_alias'],
'RowMenu_address' => $host['host_address'],
'RowMenu_poller' => $tab_relation[$host['host_id']] ?? '',
'RowMenu_parent' => $tplStr,
'RowMenu_status' => $host['host_activate'] ? _('Enabled') : _('Disabled'),
'RowMenu_badge' => $host['host_activate'] ? 'service_ok' : 'service_critical',
'RowMenu_options' => $moptions,
'isSvgFile' => $isSvgFile,
];
$style = $style != 'two'
? 'two'
: 'one';
}
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['{$option}'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['{$option}'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['{$option}'].value); submit();} "
. "else if (this.form.elements['{$option}'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['{$option}'].value); submit();} "
. "else if (this.form.elements['{$option}'].selectedIndex == 3 ||
this.form.elements['{$option}'].selectedIndex == 4 ||
this.form.elements['{$option}'].selectedIndex == 5 ||
this.form.elements['{$option}'].selectedIndex == 6){"
. " setO(this.form.elements['{$option}'].value); submit();} "
. "this.form.elements['{$option}'].selectedIndex = 0"];
$form->addElement(
'select',
$option,
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change'), 'ms' => _('Enable'), 'mu' => _('Disable'), 'dp' => _('Deploy Service')],
$attrs1
);
$o1 = $form->getElement($option);
$o1->setValue(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchH', $search);
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('Hosts', _('Name'));
$tpl->assign('Poller', _('Poller'));
$tpl->assign('Hostgroup', _('Hostgroup'));
$tpl->assign('HelpServices', _('Display all Services for this host'));
$tpl->assign('Template', _('Template'));
$tpl->assign('listServicesIcon', returnSvg('www/img/icons/all_services.svg', 'var(--icons-fill-color)', 18, 18));
$tpl->display('listHost.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host/host.php | centreon/www/include/configuration/configObject/host/host.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
const HOST_ADD = 'a';
const HOST_WATCH = 'w';
const HOST_MODIFY = 'c';
const HOST_MASSIVE_CHANGE = 'mc';
const HOST_ACTIVATION = 's';
const HOST_MASSIVE_ACTIVATION = 'ms';
const HOST_DEACTIVATION = 'u';
const HOST_MASSIVE_DEACTIVATION = 'mu';
const HOST_DUPLICATION = 'm';
const HOST_DELETION = 'd';
const HOST_SERVICE_DEPLOYMENT = 'dp';
if (isset($_POST['o1'], $_POST['o2'])) {
if ($_POST['o1'] !== '') {
$o = $_POST['o1'];
}
if ($_POST['o2'] !== '') {
$o = $_POST['o2'];
}
}
$host_id = $o === HOST_MASSIVE_CHANGE
? false
: filter_var(
$_GET['host_id'] ?? $_POST['host_id'] ?? null,
FILTER_VALIDATE_INT
);
// Path to the configuration dir
global $path, $isCloudPlatform;
$path = './include/configuration/configObject/host/';
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
$isCloudPlatform = isCloudPlatform();
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (
isset($ret2)
&& is_array($ret2)
&& $ret2['topology_page'] !== ''
&& $p !== $ret2['topology_page']
) {
$p = $ret2['topology_page'];
} elseif (
isset($ret)
&& is_array($ret)
&& $ret['topology_page'] !== ''
&& $p !== $ret['topology_page']
) {
$p = $ret['topology_page'];
}
$acl = $centreon->user->access;
$dbmon = new CentreonDB('centstorage');
$aclDbName = $acl->getNameDBAcl('broker');
$hgs = $acl->getHostGroupAclConf(null, 'broker');
$aclHostString = $acl->getHostsString('ID', $dbmon);
$aclPollerString = $acl->getPollerString();
switch ($o) {
case HOST_ADD:
case HOST_WATCH:
case HOST_MODIFY:
case HOST_MASSIVE_CHANGE:
require_once $path . 'formHost.php';
break;
case HOST_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableHostInDB($host_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listHost.php';
break; // Activate a host
case HOST_MASSIVE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableHostInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHost.php';
break;
case HOST_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableHostInDB($host_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listHost.php';
break; // Desactivate a host
case HOST_MASSIVE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableHostInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHost.php';
break;
case HOST_DUPLICATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleHostInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
$hgs = $acl->getHostGroupAclConf(null, 'broker');
$aclHostString = $acl->getHostsString('ID', $dbmon);
$aclPollerString = $acl->getPollerString();
require_once $path . 'listHost.php';
break;
case HOST_DELETION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteHostInApi(hosts: is_array($select) ? array_keys($select) : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHost.php';
break;
case HOST_SERVICE_DEPLOYMENT:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
applytpl(array_keys($select) ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHost.php';
break; // Deploy service n hosts
default:
require_once $path . 'listHost.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host/help.php | centreon/www/include/configuration/configObject/host/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['mc_update'] = dgettext(
'help',
'Choose the update mode for the below field: incremental adds the selected values,'
. ' replacement overwrites the original values.'
);
// Host Configuration
$help['host_name'] = dgettext(
'help',
'Name of the host or template. The name defined here is used in host group and service definitions to reference this particular host. It must be unique and cannot contain white spaces, '
. "or special characters like ~!$%^&*\"|'<>?,()="
);
$help['alias'] = dgettext('help', 'The alias is used to define a longer name or description for the host.');
$help['address'] = dgettext(
'help',
'Network address. Can be either IP or FQDN. If no DNS service is available, using a FQDN could raise false alarms.'
);
$help['snmp_options'] = dgettext(
'help',
'The SNMP community and version specified here can be referenced in the check command by using'
. ' the $_HOSTSNMPCOMMUNITY$ and $_HOSTSNMPVERSION$ macros.'
);
$help['poller'] = dgettext(
'help',
'Central, remote server or poller that will monitor the host.'
);
$help['host_location'] = dgettext(
'help',
"Timezone corresponding to the host's location. This will impact how the check period is applied to it."
);
$help['use'] = dgettext(
'help',
'A host or host template inherits properties from its templates, unless the properties are defined directly'
. ' on the host or host template itself. A host or host template can inherit from multiple templates. The properties'
. ' of the first template in the list prevail over the properties of the second one, and so on.'
);
$help['create_linked_services'] = dgettext(
'help',
'By enabling this option, the services linked to the template will be created independent of'
. ' the template and attached to this service.'
);
$help['check_period'] = dgettext(
'help',
'This directive is used to specify the time period during which active checks of this host can be executed.'
);
$help['check_command'] = dgettext(
'help',
'Specify the command that should be used to check if the host is up or down. Typically,'
. ' this command would try and ping the host to see if it is "alive". On a non-OK state monitoring engine'
. ' will assume the host is down. A blank argument disables active checks for the host status and Monitoring'
. ' Engine will always assume the host is up. This is useful if you are monitoring printers or other'
. ' devices that are frequently turned off.'
);
$help['check_command_args'] = dgettext(
'help',
'Specify the parameters for the selected check command here. The format is: !ARG1!ARG2!...ARGn'
);
$help['max_check_attempts'] = dgettext(
'help',
'Define the number of times that monitoring engine will retry the host check command if it returns any'
. ' non-OK state. Setting this value to 1 will cause monitoring engine to generate an alert immediately.'
. ' Note: If you do not want to check the status of the host, you must still set this to a minimum value of 1.'
. ' To bypass the host check, just leave the check command option blank.'
);
$help['check_interval'] = dgettext(
'help',
'Define the number of "time units" between regularly scheduled checks of the host. With the default time'
. ' unit of 60s, this number will mean multiples of 1 minute.'
);
$help['retry_interval'] = dgettext(
'help',
'Define the number of "time units" to wait before scheduling a re-check for this host after a'
. ' non-UP state was detected. With the default time unit of 60s, this number will mean multiples of 1 minute.'
. ' Once the host has been retried max_check_attempts times without a change in its status, it will revert'
. ' to being scheduled at its "normal" check interval rate.'
);
$help['active_checks_enabled'] = dgettext(
'help',
'Enable or disable active checks (either regularly scheduled or on-demand) of this host here.'
. ' By default active host checks are enabled.'
);
$help['passive_checks_enabled'] = dgettext(
'help',
'Enable or disable passive checks here. When disabled submitted states will be not accepted.'
);
$help['notifications_enabled'] = dgettext('help', 'Specify whether or not notifications for this host are enabled.');
$help['contact_additive_inheritance'] = dgettext(
'help',
'When enabled, the contact definition will not override the definitions on template levels,'
. ' it will be appended instead.'
);
$help['cg_additive_inheritance'] = dgettext(
'help',
'When enabled, the contactgroup definition will not override the definitions on template levels,'
. ' it will be appended instead.'
);
$help['contacts'] = dgettext(
'help',
'This is a list of contacts that should be notified whenever there are problems (or recoveries) with this host.'
. " Useful if you want notifications to go to just a few people and don't want to configure contact groups."
. ' You must specify at least one contact or contact group in each host definition'
. ' (or indirectly through its template).'
);
$help['cg_additive_inheritance'] = dgettext(
'help',
'When enabled, the contact group definition will not override the definitions on template levels,'
. ' it will be appended instead.'
);
$help['contact_groups'] = dgettext(
'help',
'This is a list of contact groups that should be notified whenever there are problems (or recoveries) with'
. ' this host. You must specify at least one contact or contact group in each host definition.'
);
$help['notification_interval'] = dgettext(
'help',
'Define the number of "time units" to wait before re-notifying a contact that this host is still down or'
. ' unreachable. With the default time unit of 60s, this number will mean multiples of 1 minute. A value of'
. ' 0 disables re-notifications of contacts about problems for this host - only one'
. ' problem notification will be sent out.'
);
$help['notification_period'] = dgettext(
'help',
'Specify the time period during which notifications of events for this host can be sent out to contacts.'
. ' If a state change occurs during a time which is not covered by the time period,'
. ' no notifications will be sent out.'
);
$help['notification_options'] = dgettext(
'help',
'Define the states of the host for which notifications should be sent out. If you specify None as an option,'
. ' no host notifications will be sent out. If you do not specify any notification options, monitoring engine'
. ' will assume that you want notifications to be sent out for all possible states.'
);
$help['first_notification_delay'] = dgettext(
'help',
'Define the number of "time units" to wait before sending out the first problem notification when this '
. 'host enters a non-UP state. '
. 'With the default time unit of 60s, this number will mean multiples of 1 minute. '
. 'If you set this value to 0, monitoring engine will start sending out notifications immediately.'
);
$help['recovery_notification_delay'] = dgettext(
'help',
'Define the number of "time units" to wait before sending out the recovery notification when this '
. 'host enters an UP state. '
. 'With the default time unit of 60s, this number will mean multiples of 1 minute. '
. 'If you set this value to 0, monitoring engine will start sending out notifications immediately.'
);
// Relations
$help['hostgroups'] = dgettext(
'help',
'Host groups linked to the host.'
);
$help['hostcategories'] = dgettext(
'help',
'Host categories linked to the host.'
);
$help['parents'] = dgettext(
'help',
'Parent hosts are typically routers, switches, firewalls, etc. that lie between the monitoring host and a'
. ' remote hosts. A router, switch, etc. which is closest to the remote host is considered to be that'
. " host\'s \"parent\". If this host is on the same network segment as the host doing the monitoring"
. ' (without any intermediate routers, etc.) the host is considered to be on the local network and will not have'
. ' a parent host. Leave this value blank if the host does not have a parent host (i.e. it is on the same'
. ' segment as the Monitoring Engine host). The order in which you specify parent hosts has no effect'
. ' on how things are monitored. Note that notification features based on host inheritance will not work if'
. ' the hosts are not monitored by the same poller.'
);
$help['child_hosts'] = dgettext(
'help',
"Instead of specifying the parent hosts in the child's parent definition, it's possible to do it the other way"
. " round and specify all child hosts in the parent's definition."
);
$help['service_templates'] = dgettext(
'help',
"Specify one or more templates of services that should be linked to this host's template."
. " A host deployed from this host's template will benefit all services themselves based from services'"
. ' templates previously linked.'
);
// Data Processing
$help['obsess_over_host'] = dgettext(
'help',
'This directive determines whether or not checks for this host will be "obsessed" over.'
. ' When enabled the obsess over host command will be executed after every check of this host.'
);
$help['check_freshness'] = dgettext(
'help',
'This directive is used to determine whether or not freshness checks are enabled for this host.'
. ' When enabled monitoring engine will trigger an active check when last passive result is older than the'
. ' value defined in the threshold. By default freshness checks are enabled.'
);
$help['freshness_threshold'] = dgettext(
'help',
'Specify the freshness threshold (in seconds) for this host. If you set this directive to a value of 0,'
. ' monitoring engine will determine a freshness threshold to use automatically.'
);
$help['flap_detection_enabled'] = dgettext(
'help',
'This directive is used to determine whether or not flap detection is enabled for this host.'
);
$help['low_flap_threshold'] = dgettext(
'help',
'This directive is used to specify the low state change threshold used in flap detection for this host.'
. ' If you set this directive to a value of 0, the program-wide value will be used.'
);
$help['high_flap_threshold'] = dgettext(
'help',
'This directive is used to specify the high state change threshold used in flap detection for this host.'
. ' If you set this directive to a value of 0, the program-wide value will be used.'
);
$help['process_perf_data'] = dgettext(
'help',
'This directive is used to determine whether or not the processing of performance data is enabled for this host.'
);
$help['retain_status_information'] = dgettext(
'help',
'This directive is used to determine whether or not status-related information about the host is retained'
. ' across program restarts. This is only useful if you have enabled the global state retention option.'
);
$help['retain_nonstatus_information'] = dgettext(
'help',
'This directive is used to determine whether or not non-status information about the host is'
. ' retained across program restarts. This is only useful if you have enabled state retention using the'
. ' retain_state_information directive.'
);
$help['stalking_options'] = dgettext(
'help',
'This directive determines which host states "stalking" is enabled for.'
);
$help['event_handler_enabled'] = dgettext(
'help',
'This directive is used to determine whether or not the event handler for this host is enabled.'
);
$help['event_handler'] = dgettext(
'help',
'The event handler command is triggered whenever a change in the state of the host is detected,'
. ' i.e. whenever it goes down or recovers.'
);
$help['event_handler_args'] = dgettext(
'help',
'This parameters are passed to the event handler commands in the same way check command parameters are handled.'
. ' The format is: !ARG1!ARG2!...ARGn'
);
$help['host_acknowledgement_timeout'] = dgettext(
'help',
'Specify a duration of acknowledgement for this host or host depending to this template.'
. ' If you leave it blank, no timeout will be set.'
);
// Host extended infos
$help['notes_url'] = dgettext(
'help',
'Clickable URL displayed in the Notes column of the Resources Status page.'
);
$help['notes'] = dgettext(
'help',
'Information note displayed as a tooltip in the Notes column of the Resources Status page.'
);
$help['action_url'] = dgettext(
'help',
'Define an optional URL that can be used to provide more actions to be performed on the host.'
. ' You will see the link to the action URL in the host details.'
);
$help['icon_image'] = dgettext(
'help',
'Define the image that should be associated with this host here.'
. ' This image will be displayed in the various places. The image will look best if it is 40x40 pixels in size.'
);
$help['icon_image_alt'] = dgettext(
'help',
'Define an optional string that is used in the alternative description of the icon image.'
);
$help['statusmap_image'] = dgettext(
'help',
'Define an image that should be associated with this host in the statusmap CGI in monitoring engine.'
. ' You can choose a JPEG, PNG, and GIF image. The GD2 image format is preferred, as other image formats'
. ' must be converted first when the statusmap image is generated. The image will look best if it '
. 'is 40x40 pixels in size.'
);
$help['geo_coords'] = dgettext(
'help',
'Geographic coordinates to allow Centreon MAP to plot the resource on a geographic view. '
. "Format: Latitude,Longitude. For example, Paris' coordinates are 48.51,2.20"
);
$help['2d_coords'] = dgettext(
'help',
'Define the coordinates to use when drawing the host in the statusmap CGI.'
. ' Coordinates should be given in positive integers, as they correspond to physical pixels in the generated image.'
. ' The origin for drawing (0,0) is in the upper left hand corner of the image and extends in the positive'
. ' x direction (to the right) along the top of the image and in the positive y direction (down) along'
. ' the left hand side of the image. For reference, the size of the icons drawn is usually about 40x40 pixels'
. ' (text takes a little extra space). The coordinates you specify here are for the upper left hand corner of'
. " the host icon that is drawn. Note: Don't worry about what the maximum x and y coordinates that you can use are."
. ' The CGI will automatically calculate the maximum dimensions of the image it creates based on the largest'
. ' x and y coordinates you specify.'
);
$help['3d_coords'] = dgettext(
'help',
'Define the coordinates to use when drawing the host in the statuswrl CGI.'
. ' Coordinates can be positive or negative real numbers. The origin for drawing is (0.0,0.0,0.0).'
. ' For reference, the size of the host cubes drawn is 0.5 units on each side (text takes a little more space).'
. ' The coordinates you specify here are used as the center of the host cube.'
);
$help['criticality_id'] = dgettext(
'help',
'Host severity level. Can be used to sort alerts in the monitoring menus, including the Resources Status page.'
);
$help['acl_groups'] = dgettext(
'help',
'This is required so that you can access your host after creation.'
. ' Some selected resource groups may contain filter, thus still preventing you from seeing the new host.'
. ' In this case, make sure to link your Host to a Host Category.'
);
// Macros
$help['macro'] = dgettext(
'help',
'Macros are used as object-specific variables/properties, which can be referenced in commands and extended infos.'
. ' Example: a macro named MACADDRESS can be referenced as $_HOSTMACADDRESS$.'
);
// unsupported in centreon
$help['display_name'] = dgettext(
'help',
'This directive is used to define an alternate name that should be displayed in the web interface for this host.'
. ' If not specified, this defaults to the value you specify as host name.'
);
$help['flap_detection_options'] = dgettext(
'help',
'This directive is used to determine what host states the flap detection logic will use for this host.'
);
$help['initial_state'] = dgettext(
'help',
'By default monitoring engine will assume that all hosts are in UP states when it starts.'
. ' You can override the initial state for a host by using this directive.'
);
$help['host_activate'] = dgettext(
'help',
'This setting determines whether the host and its services must be monitored or not.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host/resolveHostName.php | centreon/www/include/configuration/configObject/host/resolveHostName.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/include/common/common-Func.php';
// Validate the session
session_start();
$db = new CentreonDB();
$sid = session_id();
if (isset($sid)) {
$res = $db->query('SELECT * FROM session WHERE session_id = \'' . CentreonDB::escape($sid) . '\'');
if (! $res->fetchRow()) {
header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized', true, 401);
exit;
}
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized', true, 401);
exit;
}
/**
* return Resolved host name
*/
echo gethostbyname(htmlspecialchars($_GET['hostName']));
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host/formHost.php | centreon/www/include/configuration/configObject/host/formHost.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if (! $centreon->user->admin) {
if (is_numeric($host_id) && ! str_contains($aclHostString, "'" . $host_id . "'")) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this host'));
return;
}
}
const PASSWORD_REPLACEMENT_VALUE = '**********';
const BASE_ROUTE = './include/common/webServices/rest/internal.php';
$datasetRoutes = [
'timeperiods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=list',
'default_check_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=host&field=timeperiod_tp_id&id=' . $host_id,
'default_notification_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=host&field=timeperiod_tp_id2&id=' . $host_id,
'hosts' => BASE_ROUTE . '?object=centreon_configuration_host&action=list',
'default_host_parents' => BASE_ROUTE . '?object=centreon_configuration_host&action=defaultValues&target=host&field=host_parents&id=' . $host_id,
'default_host_child' => BASE_ROUTE . '?object=centreon_configuration_host&action=defaultValues&target=host&field=host_childs&id=' . $host_id,
'host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=list',
'default_host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=defaultValues&target=host&field=host_hgs&id=' . $host_id,
'host_categories' => BASE_ROUTE . '?object=centreon_configuration_hostcategory&action=list&t=c',
'default_host_categories' => BASE_ROUTE . '?object=centreon_configuration_hostcategory&action=defaultValues&target=host&field=host_hcs&id=' . $host_id,
'default_contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=defaultValues&target=host&field=host_cs&id=' . $host_id,
'contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=list',
'default_contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=defaultValues&target=host&field=host_cgs&id=' . $host_id,
'contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=list',
'default_timezones' => BASE_ROUTE . '?object=centreon_configuration_timezone&action=defaultValues&target=host&field=host_location&id=' . $host_id,
'timezones' => BASE_ROUTE . '?object=centreon_configuration_timezone&action=list',
'default_commands' => BASE_ROUTE . '?object=centreon_configuration_comman&action=defaultValues&target=host&field=command_command_id&id=' . $host_id,
'check_commands' => BASE_ROUTE . '?object=centreon_configuration_command&action=list&t=2',
'event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=list',
'default_event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=defaultValues&target=host&field=command_command_id2&id=' . $host_id,
'default_acl_groups' => BASE_ROUTE . '?object=centreon_administration_aclgroup&action=defaultValues&target=host&field=acl_groups&id=' . $host_id,
'acl_groups' => BASE_ROUTE . '?object=centreon_administration_aclgroup&action=list',
];
$attributes = [
'check_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_check_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'notification_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_notification_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'host_parents' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['hosts'],
'defaultDatasetRoute' => $datasetRoutes['default_host_parents'],
'multiple' => true,
'linkedObject' => 'centreonHost',
],
'host_child' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['hosts'],
'defaultDatasetRoute' => $datasetRoutes['default_host_child'],
'multiple' => true,
'linkedObject' => 'centreonHost',
],
'host_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['host_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_host_groups'],
'multiple' => true,
'linkedObject' => 'centreonHostgroups',
],
'host_categories' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['host_categories'],
'defaultDatasetRoute' => $datasetRoutes['default_host_categories'],
'multiple' => true,
'linkedObject' => 'centreonHostcategories',
],
'contacts' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contacts'],
'defaultDatasetRoute' => $datasetRoutes['default_contacts'],
'multiple' => true,
'linkedObject' => 'centreonContact',
],
'contact_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contact_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_contact_groups'],
'multiple' => true,
'linkedObject' => 'centreonContactgroup',
],
'timezones' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timezones'],
'defaultDatasetRoute' => $datasetRoutes['default_timezones'],
'multiple' => false,
'linkedObject' => 'centreonGMT',
],
'check_commands' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_commands'],
'availableDatasetRoute' => $datasetRoutes['check_commands'],
],
'event_handlers' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_event_handlers'],
'availableDatasetRoute' => $datasetRoutes['event_handlers'],
],
'acl_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['acl_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_acl_groups'],
'multiple' => true,
'linkedObject' => 'centreonAclGroup',
],
];
$hostObj = new CentreonHost($pearDB);
$initialValues = [];
// host categories
$hcString = $acl->getHostCategoriesString();
if (! $isCloudPlatform) {
// notification contacts
$notifCs = $acl->getContactAclConf([
'fields' => ['contact_id', 'contact_name'],
'get_row' => 'contact_name',
'keys' => ['contact_id'],
'conditions' => ['contact_register' => '1'],
'order' => ['contact_name'],
]);
// notification contact groups
$notifCgs = $acl->getContactGroupAclConf(
[
'fields' => ['cg_id', 'cg_name'],
'get_row' => 'cg_name',
'keys' => ['cg_id'],
'order' => ['cg_name'],
],
false
);
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
}
// Database retrieve information for Host
$host = [];
// define macros as empty array to avoid null counting
$aMacros = [];
// Used to store all macro passwords
$macroPasswords = [];
if (
($o === HOST_MODIFY || $o === HOST_WATCH)
&& isset($host_id)
) {
$statement = $pearDB->prepare(
'SELECT * FROM host
INNER JOIN extended_host_information ehi
ON ehi.host_host_id = host.host_id
WHERE host_id = :host_id LIMIT 1'
);
$statement->bindValue(':host_id', $host_id, PDO::PARAM_INT);
$statement->execute();
// Set base value
$host_list = $statement->fetch();
$host_list = $host_list === false ? [] : $host_list;
$host = array_map('myDecode', $host_list);
$cmdId = $host['command_command_id'] ?? '';
if (! empty($host['host_snmp_community'])) {
$host['host_snmp_community'] = PASSWORD_REPLACEMENT_VALUE;
}
if (! $isCloudPlatform) {
// Set Host Notification Options
$tmp = explode(',', $host['host_notification_options'] ?? '');
foreach ($tmp as $key => $value) {
$host['host_notifOpts'][trim($value)] = 1;
}
}
// Set Host Category Parents
$statement = $pearDB->prepare(
'SELECT DISTINCT hostcategories_hc_id
FROM hostcategories_relation hcr
INNER JOIN hostcategories hc
ON hcr.hostcategories_hc_id = hc.hc_id
WHERE hc.level IS NULL AND hcr.host_host_id = :host_id'
);
$statement->bindValue(':host_id', $host_id, PDO::PARAM_INT);
$statement->execute();
for ($i = 0; $hc = $statement->fetch(); $i++) {
if (! $centreon->user->admin && ! str_contains($hcString, "'" . $hc['hostcategories_hc_id'] . "'")) {
$initialValues['host_hcs'][] = $hc['hostcategories_hc_id'];
$host['host_hcs'][$i] = $hc['hostcategories_hc_id'];
} else {
$host['host_hcs'][$i] = $hc['hostcategories_hc_id'];
}
}
// Set Host and Nagios Server Relation
$statement = $pearDB->prepare('SELECT `nagios_server_id` FROM `ns_host_relation` WHERE `host_host_id` = :host_id');
$statement->bindValue(':host_id', $host_id, PDO::PARAM_INT);
$statement->execute();
for ($i = ($o !== HOST_MASSIVE_CHANGE) ? 0 : 1; $ns = $statement->fetch(); $i++) {
$host['nagios_server_id'][$i] = $ns['nagios_server_id'];
}
unset($ns);
// Set critically
$statement = $pearDB->prepare(
'SELECT hc.hc_id
FROM hostcategories hc
INNER JOIN hostcategories_relation hcr
ON hcr.hostcategories_hc_id = hc.hc_id
WHERE hc.level IS NOT NULL AND hcr.host_host_id = :host_id
ORDER BY hc.level ASC LIMIT 1'
);
$statement->bindValue(':host_id', $host_id, PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount()) {
$cr = $statement->fetch();
$host['criticality_id'] = $cr['hc_id'];
}
$aTemplates = $hostObj->getTemplateChain($host_id, [], -1, true, 'host_name,host_id,command_command_id');
if (! isset($cmdId)) {
$cmdId = '';
}
if (isset($_REQUEST['macroInput'])) {
/**
* We don't taking into account the POST data sent from the interface in order the retrieve the original value
* of all passwords.
*/
$aMacros = $hostObj->getMacros($host_id, $aTemplates, $cmdId);
/**
* If a password has been modified from the interface, we retrieve the old password existing in the repository
* (giving by the $aMacros variable) to inject it before saving.
* Passwords will be saved using the $_REQUEST variable.
*/
foreach ($_REQUEST['macroInput'] as $index => $macroName) {
if (
! isset($_REQUEST['macroFrom'][$index])
|| ! isset($_REQUEST['macroPassword'][$index])
|| $_REQUEST['macroPassword'][$index] !== '1' // Not a password
|| $_REQUEST['macroValue'][$index] !== PASSWORD_REPLACEMENT_VALUE // The password has not changed
) {
continue;
}
foreach ($aMacros as $macroAlreadyExist) {
if (
$macroAlreadyExist['macroInput_#index#'] === $macroName
&& $_REQUEST['macroFrom'][$index] === $macroAlreadyExist['source']
) {
/**
* if the password has not been changed, we replace the password coming from the interface with
* the original value (from the repository) before saving.
*/
$_REQUEST['macroValue'][$index] = $macroAlreadyExist['macroValue_#index#'];
}
}
}
}
// We taking into account the POST data sent from the interface
$aMacros = $hostObj->getMacros($host_id, $aTemplates, $cmdId, $_POST);
// We hide all passwords in the jsData property to prevent them from appearing in the HTML code.
foreach ($aMacros as $index => $macroValues) {
if ($macroValues['macroPassword_#index#'] === 1) {
$macroPasswords[$index]['password'] = $aMacros[$index]['macroValue_#index#'];
// It's a password macro
$aMacros[$index]['macroOldValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
$aMacros[$index]['macroValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
// Keep the original name of the input field in case its name changes.
$aMacros[$index]['macroOriginalName_#index#'] = $aMacros[$index]['macroInput_#index#'];
}
}
}
// Preset values of macros
$cdata = CentreonData::getInstance();
$cdata->addJsData('clone-values-macro', htmlspecialchars(
json_encode($aMacros),
ENT_QUOTES
));
$cdata->addJsData('clone-count-macro', count($aMacros));
// Preset values of host templates
$tplArray = $hostObj->getTemplates($host_id ?? null);
$cdata->addJsData('clone-values-template', htmlspecialchars(
json_encode($tplArray),
ENT_QUOTES
));
$cdata->addJsData('clone-count-template', count($tplArray));
// Nagios Server comes from DB -> Store in $nsServer Array
$nsServers = [];
if ($o === HOST_MASSIVE_CHANGE) {
$nsServers[null] = null;
}
$statement = $pearDB->query(
'SELECT id, name FROM nagios_server '
. ($aclPollerString !== "''" ? $acl->queryBuilder('WHERE', 'id', $aclPollerString) : '')
. ' ORDER BY name'
);
while ($nsServer = $statement->fetch()) {
$nsServers[$nsServer['id']] = HtmlSanitizer::createFromString($nsServer['name'])->sanitize()->getString();
}
$statement->closeCursor();
$extImg = [];
$extImg = return_image_list(1);
$extImgStatusmap = [];
$extImgStatusmap = return_image_list(2);
// Host multiple templates relations stored in DB
$mTp = $hostObj->getSavedTpl($host_id);
// Var information to format the element
$attrsText = ['size' => '30'];
$attrsAdvSelect = ['style' => 'width: 270px; height: 100px;'];
$attrsText2 = ['size' => '6'];
$attrsAdvSelectsmall = ['style' => 'width: 270px; height: 50px;'];
$attrsAdvSelectbig = ['style' => 'width: 270px; height: 130px;'];
$attrsTextarea = ['rows' => '4', 'cols' => '80'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
// Begin of the FORM
// For a shitty reason, Quickform set checkbox with stal[o] name
unset($_POST['o']);
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$form->registerRule('validate_geo_coords', 'function', 'validateGeoCoords');
if ($o === HOST_ADD) {
$form->addElement('header', 'title', _('Add a Host'));
} elseif ($o === HOST_MODIFY) {
$form->addElement('header', 'title', _('Modify a Host'));
} elseif ($o === HOST_WATCH) {
$form->addElement('header', 'title', _('View a Host'));
} elseif ($o === HOST_MASSIVE_CHANGE) {
$form->addElement('header', 'title', _('Mass Change'));
}
// TAB1 - General information
$form->addElement('header', 'information', _('General Information'));
if ($o !== HOST_MASSIVE_CHANGE) {
$form->addElement('text', 'host_name', _('Name'), $attrsText);
$form->addElement('text', 'host_alias', _('Alias'), $attrsText);
$form->addElement(
'text',
'host_address',
_('Address'),
array_merge(['id' => 'host_address'], $attrsText)
);
if (! $isCloudPlatform) {
$form->addElement(
'button',
'host_resolve',
_('Resolve'),
[
'onClick' => 'resolveHostNameToAddress(document.getElementById(\'host_address\').value,'
. ' function(err, ip){if (!err) document.getElementById(\'host_address\').value = ip});',
'class' => 'btc bt_info',
]
);
}
}
switch ($o) {
case HOST_ADD:
case HOST_MASSIVE_CHANGE:
$form->addElement('text', 'host_snmp_community', _('SNMP Community'), $attrsText);
break;
default:
$snmpAttribute = $attrsText;
$snmpAttribute['onClick'] = 'javascript:change_snmp_community_input_type(this)';
$form->addElement('password', 'host_snmp_community', _('SNMP Community'), $snmpAttribute);
break;
}
$form->addElement('select', 'host_snmp_version', _('Version'), [null => null, 1 => '1', '2c' => '2c', 3 => '3']);
$form->addElement('select2', 'host_location', _('Timezone'), [], $attributes['timezones']);
$form->addElement('select', 'nagios_server_id', _('Monitoring server'), $nsServers);
// Get default poller id
$statement = $pearDB->query("SELECT id FROM nagios_server WHERE is_default = '1'");
$defaultServer = $statement->fetch();
$statement->closeCursor();
if (isset($defaultServer) && $defaultServer && $o !== HOST_MASSIVE_CHANGE) {
$form->setDefaults(['nagios_server_id' => $defaultServer['id']]);
}
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_tplp = [];
$mc_mod_tplp[] = $form->createElement('radio', 'mc_mod_tplp', null, _('Incremental'), '0');
$mc_mod_tplp[] = $form->createElement('radio', 'mc_mod_tplp', null, _('Replacement'), '1');
$form->addGroup($mc_mod_tplp, 'mc_mod_tplp', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_tplp' => '0']);
}
$form->addElement('text', 'host_parallel_template', _('Templates'));
$form->addElement(
'static',
'tplTextParallel',
_('A host or host template can have several templates. See help for more details.')
);
$form->addElement('static', 'tplText', _('Using a Template allows you to have multi-level Template connection'));
$cloneSetMacro = [
$form->addElement(
'hidden',
'macroId[#index#]',
null,
['id' => 'macroId_#index#', 'size' => 25]
),
$form->addElement(
'text',
'macroInput[#index#]',
_('Name'),
['id' => 'macroInput_#index#', 'size' => 25]
),
$form->addElement(
'text',
'macroValue[#index#]',
_('Value'),
['id' => 'macroValue_#index#', 'size' => 25]
),
$form->addElement(
'checkbox',
'macroPassword[#index#]',
_('Password'),
null,
['id' => 'macroPassword_#index#', 'onClick' => 'javascript:change_macro_input_type(this, false)']
),
$form->addElement(
'hidden',
'macroFrom[#index#]',
'direct',
['id' => 'macroFrom_#index#']
),
];
$cloneSetTemplate = [];
$listPpTemplate = $hostObj->getLimitedList();
$listAllTemplate = $hostObj->getList(false, true, null);
$validTemplate = array_diff_key($listAllTemplate, $listPpTemplate);
$listTemplate = [null => null] + $mTp + $validTemplate;
$cloneSetTemplate[] = $form->addElement(
'select',
'tpSelect[#index#]',
'',
$listTemplate,
[
'id' => 'tpSelect_#index#',
'class' => 'select2',
'type' => 'select-one',
]
);
if (! $isCloudPlatform) {
$dupSvTpl[] = $form->createElement('radio', 'dupSvTplAssoc', null, _('Yes'), '1');
$dupSvTpl[] = $form->createElement('radio', 'dupSvTplAssoc', null, _('No'), '0');
$form->addGroup($dupSvTpl, 'dupSvTplAssoc', _('Checks Enabled'), ' ');
if ($o === HOST_MODIFY) {
$form->setDefaults(['dupSvTplAssoc' => '0']);
} elseif ($o !== HOST_MASSIVE_CHANGE) {
$form->setDefaults(['dupSvTplAssoc' => '1']);
}
$form->addElement('static', 'dupSvTplAssocText', _('Create Services linked to the Template too'));
}
//
// # Check information
//
//
$form->addElement('text', 'host_max_check_attempts', _('Max Check Attempts'), $attrsText2);
$form->addElement('text', 'host_check_interval', _('Normal Check Interval'), $attrsText2);
$form->addElement('text', 'host_retry_check_interval', _('Retry Check Interval'), $attrsText2);
$form->addElement('header', 'check', _('Host Check Properties'));
$checkCommandSelect = $form->addElement('select2', 'command_command_id', _('Check Command'), [], $attributes['check_commands']);
$checkCommandSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id","example1");'
);
$form->addElement('text', 'command_command_id_arg1', _('Args'), $attrsText);
$hostEHE[] = $form->createElement('radio', 'host_event_handler_enabled', null, _('Yes'), '1');
$hostEHE[] = $form->createElement('radio', 'host_event_handler_enabled', null, _('No'), '0');
$hostEHE[] = $form->createElement('radio', 'host_event_handler_enabled', null, _('Default'), '2');
$form->addGroup($hostEHE, 'host_event_handler_enabled', _('Event Handler Enabled'), ' ');
if ($o !== HOST_MASSIVE_CHANGE) {
$form->setDefaults(['host_event_handler_enabled' => '2']);
}
$eventHandlerSelect = $form->addElement('select2', 'command_command_id2', _('Event Handler'), [], $attributes['event_handlers']);
$eventHandlerSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id2","example2");'
);
$form->addElement('text', 'command_command_id_arg2', _('Args'), $attrsText);
$hostACE[] = $form->createElement('radio', 'host_active_checks_enabled', null, _('Yes'), '1');
$hostACE[] = $form->createElement('radio', 'host_active_checks_enabled', null, _('No'), '0');
$hostACE[] = $form->createElement('radio', 'host_active_checks_enabled', null, _('Default'), '2');
$form->addGroup($hostACE, 'host_active_checks_enabled', _('Active Checks Enabled'), ' ');
if ($o !== HOST_MASSIVE_CHANGE) {
$form->setDefaults(['host_active_checks_enabled' => '2']);
}
$hostPCE[] = $form->createElement('radio', 'host_passive_checks_enabled', null, _('Yes'), '1');
$hostPCE[] = $form->createElement('radio', 'host_passive_checks_enabled', null, _('No'), '0');
$hostPCE[] = $form->createElement('radio', 'host_passive_checks_enabled', null, _('Default'), '2');
$form->addGroup($hostPCE, 'host_passive_checks_enabled', _('Passive Checks Enabled'), ' ');
if ($o !== HOST_MASSIVE_CHANGE) {
$form->setDefaults(['host_passive_checks_enabled' => '2']);
}
$form->addElement('select2', 'timeperiod_tp_id', _('Check Period'), [], $attributes['check_periods']);
/**
* Acknowledgement timeout.
*/
$form->addElement('text', 'host_acknowledgement_timeout', _('Acknowledgement timeout'), $attrsText2);
// #
// # Notification informations
// #
if (! $isCloudPlatform) {
$form->addElement('header', 'notification', _('Notification'));
$hostNE[] = $form->createElement('radio', 'host_notifications_enabled', null, _('Yes'), '1');
$hostNE[] = $form->createElement('radio', 'host_notifications_enabled', null, _('No'), '0');
$hostNE[] = $form->createElement('radio', 'host_notifications_enabled', null, _('Default'), '2');
$form->addGroup($hostNE, 'host_notifications_enabled', _('Notification Enabled'), ' ');
if ($o !== HOST_MASSIVE_CHANGE) {
$form->setDefaults(['host_notifications_enabled' => '2']);
}
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_notifopt_first_notification_delay = [];
$mc_mod_notifopt_first_notification_delay[] = $form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Incremental'),
'0'
);
$mc_mod_notifopt_first_notification_delay[] = $form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Replacement'),
'1'
);
$form->addGroup(
$mc_mod_notifopt_first_notification_delay,
'mc_mod_notifopt_first_notification_delay',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_first_notification_delay' => '0']);
}
$form->addElement('text', 'host_first_notification_delay', _('First notification delay'), $attrsText2);
$form->addElement('text', 'host_recovery_notification_delay', _('Recovery notification delay'), $attrsText2);
}
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_hcg = [];
$mc_mod_hcg[] = $form->createElement('radio', 'mc_mod_hcg', null, _('Incremental'), '0');
$mc_mod_hcg[] = $form->createElement('radio', 'mc_mod_hcg', null, _('Replacement'), '1');
$form->addGroup($mc_mod_hcg, 'mc_mod_hcg', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_hcg' => '0']);
}
// Additive
$dbResult = $pearDB->query('SELECT `value` FROM options WHERE `key` = "inheritance_mode"');
$inheritanceMode = $dbResult->fetch();
if (! $isCloudPlatform) {
if ($o === HOST_MASSIVE_CHANGE) {
$contactAdditive[] = $form->createElement('radio', 'mc_contact_additive_inheritance', null, _('Yes'), '1');
$contactAdditive[] = $form->createElement('radio', 'mc_contact_additive_inheritance', null, _('No'), '0');
$contactAdditive[] = $form->createElement(
'radio',
'mc_contact_additive_inheritance',
null,
_('Default'),
'2'
);
$form->addGroup(
$contactAdditive,
'mc_contact_additive_inheritance',
_('Contact additive inheritance'),
' '
);
$contactGroupAdditive[] = $form->createElement('radio', 'mc_cg_additive_inheritance', null, _('Yes'), '1');
$contactGroupAdditive[] = $form->createElement('radio', 'mc_cg_additive_inheritance', null, _('No'), '0');
$contactGroupAdditive[] = $form->createElement(
'radio',
'mc_cg_additive_inheritance',
null,
_('Default'),
'2'
);
$form->addGroup(
$contactGroupAdditive,
'mc_cg_additive_inheritance',
_('Contact group additive inheritance'),
' '
);
} else {
$form->addElement('checkbox', 'contact_additive_inheritance', '', _('Contact additive inheritance'));
$form->addElement('checkbox', 'cg_additive_inheritance', '', _('Contact group additive inheritance'));
}
$form->addElement('select2', 'host_cs', _('Linked Contacts'), [], $attributes['contacts']);
$form->addElement('select2', 'host_cgs', _('Linked Contact Groups'), [], $attributes['contact_groups']);
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_notifopt_notification_interval = [];
$mc_mod_notifopt_notification_interval[] = $form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Incremental'),
'0'
);
$mc_mod_notifopt_notification_interval[] = $form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Replacement'),
'1'
);
$form->addGroup(
$mc_mod_notifopt_notification_interval,
'mc_mod_notifopt_notification_interval',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_notification_interval' => '0']);
}
$form->addElement('text', 'host_notification_interval', _('Notification Interval'), $attrsText2);
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_notifopt_timeperiod = [];
$mc_mod_notifopt_timeperiod[] = $form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Incremental'),
'0'
);
$mc_mod_notifopt_timeperiod[] = $form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Replacement'),
'1'
);
$form->addGroup($mc_mod_notifopt_timeperiod, 'mc_mod_notifopt_timeperiod', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopt_timeperiod' => '0']);
}
$form->addElement('select2', 'timeperiod_tp_id2', _('Notification Period'), [], $attributes['notification_periods']);
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_notifopts = [];
$mc_mod_notifopts[] = $form->createElement('radio', 'mc_mod_notifopts', null, _('Incremental'), '0');
$mc_mod_notifopts[] = $form->createElement('radio', 'mc_mod_notifopts', null, _('Replacement'), '1');
$form->addGroup($mc_mod_notifopts, 'mc_mod_notifopts', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopts' => '0']);
}
$hostNotifOpt = [
$form->createElement(
'checkbox',
'd',
' ',
_('Down'),
['id' => 'notifD', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'u',
' ',
_('Unreachable'),
['id' => 'notifU', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'r',
' ',
_('Recovery'),
['id' => 'notifR', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'f',
' ',
_('Flapping'),
['id' => 'notifF', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
's',
' ',
_('Downtime Scheduled'),
['id' => 'notifDS', 'onClick' => 'uncheckNotifOption(this);']
),
$form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'notifN', 'onClick' => 'uncheckNotifOption(this);']
),
];
$form->addGroup($hostNotifOpt, 'host_notifOpts', _('Notification Options'), ' ');
}
//
// # Further informations
//
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$hostActivation[] = $form->createElement('radio', 'host_activate', null, _('Enabled'), '1');
$hostActivation[] = $form->createElement('radio', 'host_activate', null, _('Disabled'), '0');
$form->addGroup($hostActivation, 'host_activate', _('Enable/disable resource'), ' ');
if ($o !== HOST_MASSIVE_CHANGE) {
$form->setDefaults(['host_activate' => '1']);
}
$form->addElement('textarea', 'host_comment', _('Comments'), $attrsTextarea);
$form->addElement('select2', 'host_hgs', _('Host Groups'), [], $attributes['host_groups']);
if ($isCloudPlatform && $o !== HOST_MASSIVE_CHANGE) {
$form->addRule('host_hgs', _('Mandatory field for ACL purpose.'), 'required');
}
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_hhg = [];
$mc_mod_hhg[] = $form->createElement('radio', 'mc_mod_hhg', null, _('Incremental'), '0');
$mc_mod_hhg[] = $form->createElement('radio', 'mc_mod_hhg', null, _('Replacement'), '1');
$form->addGroup($mc_mod_hhg, 'mc_mod_hhg', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_hhg' => '0']);
}
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_hhc = [];
$mc_mod_hhc[] = $form->createElement('radio', 'mc_mod_hhc', null, _('Incremental'), '0');
$mc_mod_hhc[] = $form->createElement('radio', 'mc_mod_hhc', null, _('Replacement'), '1');
$form->addGroup($mc_mod_hhc, 'mc_mod_hhc', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_hhc' => '0']);
}
$form->addElement('select2', 'host_hcs', _('Host Categories'), [], $attributes['host_categories']);
if ($o === HOST_MASSIVE_CHANGE) {
$mc_mod_nsid = [];
$mc_mod_nsid[] = $form->createElement('radio', 'mc_mod_nsid', null, _('Incremental'), '0');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host/refreshMacroAjax.php | centreon/www/include/configuration/configObject/host/refreshMacroAjax.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . '/www/include/common/common-Func.php';
require_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonCommand.class.php';
// Validate the session
session_start();
session_write_close();
$db = new CentreonDB();
try {
if (! CentreonSession::checkSession(session_id(), $db)) {
sendError('bad session id', 401);
}
} catch (Exception $ex) {
sendError('Internal error', 500);
}
$macros = (new CentreonHost($db))->ajaxMacroControl($_POST);
header('Content-Type: application/json');
echo json_encode(['macros' => $macros, 'count' => count($macros)]);
exit;
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host/DB-Func.php | centreon/www/include/configuration/configObject/host/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonACL.class.php';
require_once _CENTREON_PATH_ . 'www/include/common/vault-functions.php';
use App\Kernel;
use Centreon\Domain\Log\Logger;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Host\Application\Converter\HostEventConverter;
use Core\Infrastructure\Common\Api\Router;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Quickform rule that checks whether or not monitoring server can be set
*
* @global CentreonDB $pearDB
* @global HTML_QuickFormCustom $form
* @param int $instanceId
* @return bool
*/
function testPollerDep($instanceId)
{
global $pearDB, $form;
$hostId = $form->getSubmitValue('host_id');
$hostParents = filter_var_array(
$form->getSubmitValue('host_parents'),
FILTER_VALIDATE_INT
);
if (! $hostId || is_null($hostParents)) {
return true;
}
$request = 'SELECT COUNT(*) as total '
. 'FROM host_hostparent_relation hhr, ns_host_relation nhr '
. 'WHERE hhr.host_parent_hp_id = nhr.host_host_id '
. 'AND hhr.host_host_id = :host_id '
. 'AND nhr.nagios_server_id != :server_id';
$fieldsToBind = [];
if (! in_array(false, $hostParents)) {
$counter = count($hostParents);
for ($index = 0; $index < $counter; $index++) {
$fieldsToBind[':parent_' . $index] = $hostParents[$index];
}
$request .= ' AND host_parent_hp_id IN ('
. implode(',', array_keys($fieldsToBind)) . ')';
}
$prepare = $pearDB->prepare($request);
$prepare->bindValue(':host_id', $hostId, PDO::PARAM_INT);
$prepare->bindValue(':server_id', $instanceId, PDO::PARAM_INT);
foreach ($fieldsToBind as $field => $hostParentId) {
$prepare->bindValue($field, $hostParentId, PDO::PARAM_INT);
}
if ($prepare->execute()) {
$result = $prepare->fetch(PDO::FETCH_ASSOC);
return ((int) $result['total']) == 0;
}
return true;
}
/**
* Quickform rule that checks whether or not reserved macro are used
*
* @global CentreonDB $pearDB
* @return bool
*/
function hostMacHandler()
{
global $pearDB;
if (! isset($_REQUEST['macroInput'])) {
return true;
}
$fieldsToBind = [];
foreach ($_POST['macroInput'] as $key => $value) {
$fieldsToBind[':macro_' . $key]
= "'\$_HOST" . strtoupper($value) . "\$'";
}
$request
= 'SELECT count(*) as total FROM nagios_macro WHERE macro_name IN ('
. implode(',', array_keys($fieldsToBind)) . ')';
$prepare = $pearDB->prepare($request);
foreach ($fieldsToBind as $field => $macroName) {
$prepare->bindValue($field, $macroName, PDO::PARAM_STR);
}
if ($prepare->execute()) {
$result = $prepare->fetch(PDO::FETCH_ASSOC);
return ((int) $result['total']) == 0;
}
return true;
}
/**
* Indicates if the host name has already been used
*
* @global CentreonDB $pearDB
* @global HTML_QuickFormCustom $form
* @global Centreon $centreon
* @param string $name Name to check
* @return bool Return false if the host name has already been used
*/
function hasHostNameNeverUsed($name = null)
{
global $pearDB, $form, $centreon;
$id = null;
if (isset($form)) {
$id = (int) $form->getSubmitValue('host_id');
}
$prepare = $pearDB->prepare(
'SELECT host_name, host_id FROM host '
. "WHERE host_name = :host_name AND host_register = '1'"
);
$hostName = CentreonDB::escape($centreon->checkIllegalChar($name));
$prepare->bindValue(':host_name', $hostName, PDO::PARAM_STR);
$prepare->execute();
$result = $prepare->fetch(PDO::FETCH_ASSOC);
$totals = $prepare->rowCount();
if ($totals >= 1 && ($result['host_id'] == $id)) {
/**
* In case of modification
*/
return true;
}
return ! ($totals >= 1 && ($result['host_id'] != $id));
}
function testHostName($name = null)
{
return ! (preg_match('/^_Module_/', $name));
}
/**
* Indicates if the host template has already been used
*
* @global CentreonDB $pearDB
* @global HTML_QuickFormCustom $form
* @param string $name Name to check
* @return bool Return false if the host template has already been used
*/
function hasHostTemplateNeverUsed($name = null)
{
global $pearDB, $form;
$id = null;
if (isset($form)) {
$id = (int) $form->getSubmitValue('host_id');
}
$prepare = $pearDB->prepare(
'SELECT host_name, host_id FROM host '
. "WHERE host_name = :host_name AND host_register = '0'"
);
$prepare->bindValue(':host_name', $name, PDO::PARAM_STR);
$prepare->execute();
$total = $prepare->rowCount();
$result = $prepare->fetch(PDO::FETCH_ASSOC);
if ($total >= 1 && $result['host_id'] == $id) {
/**
* In case of modification
*/
return true;
}
return ! ($total >= 1 && $result['host_id'] != $id);
/**
* In case of duplicate
*/
}
/**
* Checks if the insertion can be made
*
* @param mixed $hostId
* @param mixed $templateId
* @return bool
*/
function hasNoInfiniteLoop($hostId, $templateId)
{
global $pearDB;
static $antiTplLoop = [];
if ($hostId === $templateId) {
return false;
}
if (! count($antiTplLoop)) {
$query = 'SELECT * FROM host_template_relation';
$res = $pearDB->query($query);
while ($row = $res->fetch()) {
if (! isset($antiTplLoop[$row['host_tpl_id']])) {
$antiTplLoop[$row['host_tpl_id']] = [];
}
$antiTplLoop[$row['host_tpl_id']][$row['host_host_id']] = $row['host_host_id'];
}
}
if (isset($antiTplLoop[$hostId])) {
foreach ($antiTplLoop[$hostId] as $hId) {
if ($hId == $templateId) {
return false;
}
if (hasNoInfiniteLoop($hId, $templateId) === false) {
return false;
}
}
}
return true;
}
function enableHostInDB($host_id = null, $host_arr = [])
{
global $pearDB, $centreon;
if (! $host_id && ! count($host_arr)) {
return;
}
if ($host_id) {
$host_arr = [$host_id => '1'];
}
$updateStatement = $pearDB->prepare("UPDATE host SET host_activate = '1' WHERE host_id = :hostId");
$selectStatement = $pearDB->prepare('SELECT host_name FROM `host` WHERE host_id = :hostId');
foreach (array_keys($host_arr) as $hostId) {
$updateStatement->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$updateStatement->execute();
$selectStatement->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$selectStatement->execute();
$hostName = $selectStatement->fetchColumn();
signalConfigurationChange('host', (int) $hostId);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOST,
object_id: $hostId,
object_name: $hostName,
action_type: ActionLog::ACTION_TYPE_ENABLE
);
}
}
function disableHostInDB($host_id = null, $host_arr = [])
{
global $pearDB, $centreon;
if (! $host_id && ! count($host_arr)) {
return;
}
if ($host_id) {
$host_arr = [$host_id => '1'];
}
$updateStatement = $pearDB->prepare("UPDATE host SET host_activate = '0' WHERE host_id = :hostId");
$selectStatement = $pearDB->prepare('SELECT host_name FROM `host` WHERE host_id = :hostId');
foreach (array_keys($host_arr) as $hostId) {
$updateStatement->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$updateStatement->execute();
$selectStatement->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$selectStatement->execute();
$hostName = $selectStatement->fetchColumn();
signalConfigurationChange('host', (int) $hostId, [], false);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOST,
object_id: $hostId,
object_name: $hostName,
action_type: ActionLog::ACTION_TYPE_DISABLE
);
}
}
/**
* @param int $hostId
*/
function removeRelationLastHostDependency(int $hostId): void
{
global $pearDB;
$findQuery = <<<'SQL'
SELECT service_service_id
FROM host_service_relation
WHERE host_host_id = :hostId
SQL;
$findStatement = $pearDB->prepare($findQuery);
$findStatement->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$findStatement->execute();
$countQuery = <<<'SQL'
SELECT COUNT(dependency_dep_id) AS nb_dependency , dependency_dep_id AS id
FROM dependency_serviceParent_relation
WHERE dependency_dep_id IN (SELECT dependency_dep_id FROM dependency_serviceParent_relation
WHERE service_service_id = :service_service_id) GROUP BY dependency_dep_id
SQL;
$countStatement = $pearDB->prepare($countQuery);
$deleteQuery = <<<'SQL'
DELETE FROM dependency WHERE dep_id = :dep_id
SQL;
$deleteStatement = $pearDB->prepare($deleteQuery);
while ($row = $findStatement->fetch()) {
$countStatement->bindValue(':service_service_id', (int) $row['service_service_id'], PDO::PARAM_INT);
$countStatement->execute();
if ($result = $countStatement->fetch(PDO::FETCH_ASSOC)) {
// is last service parent
if ($result['nb_dependency'] === 1) {
$deleteStatement->bindValue(':dep_id', (int) $result['id'], PDO::PARAM_INT);
$deleteStatement->execute();
}
}
}
$countQuery = <<<'SQL'
SELECT COUNT(dependency_dep_id) AS nb_dependency , dependency_dep_id AS id
FROM dependency_hostParent_relation
WHERE dependency_dep_id IN (SELECT dependency_dep_id FROM dependency_hostParent_relation
WHERE host_host_id = :hostId)
GROUP BY dependency_dep_id
SQL;
$countStatement = $pearDB->prepare($countQuery);
$countStatement->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$countStatement->execute();
$deleteQuery = <<<'SQL'
DELETE FROM dependency WHERE dep_id = :dep_id
SQL;
$deleteStatement = $pearDB->prepare($deleteQuery);
if ($result = $countStatement->fetch()) {
// is last parent
if ($result['nb_dependency'] === 1) {
$deleteStatement->bindValue(':dep_id', (int) $result['id'], PDO::PARAM_INT);
$deleteStatement->execute();
}
}
}
// This function is called for duplicating a host
function multipleHostInDB($hosts = [], $nbrDup = [])
{
global $pearDB, $path, $centreon, $is_admin;
$hostAcl = [];
$kernel = Kernel::createForWeb();
/** @var Logger $logger */
$logger = $kernel->getContainer()->get(Logger::class);
$readVaultConfigurationRepository = $kernel->getContainer()->get(
ReadVaultConfigurationRepositoryInterface::class
);
$vaultConfiguration = $readVaultConfigurationRepository->find();
foreach ($hosts as $key => $value) {
$dbResult = $pearDB->query("SELECT * FROM host WHERE host_id = '" . (int) $key . "' LIMIT 1");
$row = $dbResult->fetch();
$row['host_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if ($key2 == 'host_name') {
$hostName = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$val
? $val .= ($value2 != null ? (", '" . CentreonDB::escape($value2) . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . CentreonDB::escape($value2) . "'") : 'NULL');
if ($key2 != 'host_id') {
$fields[$key2] = $value2;
}
if (isset($hostName)) {
$fields['host_name'] = $hostName;
}
}
if (hasHostNameNeverUsed($hostName)) {
$rq = $val ? 'INSERT INTO host VALUES (' . $val . ')' : null;
$dbResult = $pearDB->query($rq);
$dbResult = $pearDB->query('SELECT MAX(host_id) FROM host');
$maxId = $dbResult->fetch();
if (isset($maxId['MAX(host_id)'])) {
$hostAcl[$maxId['MAX(host_id)']] = $key;
$dbResult = $pearDB->query("SELECT DISTINCT host_parent_hp_id
FROM host_hostparent_relation
WHERE host_host_id = '" . (int) $key . "'");
$fields['host_parents'] = '';
$statement = $pearDB->prepare(
'INSERT INTO host_hostparent_relation
VALUES (:host_parent_hp_id, :host_host_id)'
);
while ($host = $dbResult->fetch()) {
$statement->bindValue(':host_parent_hp_id', (int) $host['host_parent_hp_id'], PDO::PARAM_INT);
$statement->bindValue(':host_host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->execute();
$fields['host_parents'] .= $host['host_parent_hp_id'] . ',';
}
$fields['host_parents'] = trim($fields['host_parents'], ',');
$res = $pearDB->query("SELECT DISTINCT host_host_id
FROM host_hostparent_relation
WHERE host_parent_hp_id = '" . (int) $key . "'");
$fields['host_childs'] = '';
$statement = $pearDB->prepare(
'INSERT INTO host_hostparent_relation (host_parent_hp_id, host_host_id)
VALUES (:host_parent_hp_id, :host_host_id)'
);
while ($host = $res->fetch()) {
$statement->bindValue(':host_parent_hp_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->bindValue(':host_host_id', (int) $host['host_host_id'], PDO::PARAM_INT);
$statement->execute();
$fields['host_childs'] .= $host['host_host_id'] . ',';
}
$fields['host_childs'] = trim($fields['host_childs'], ',');
// We need to duplicate the entire Service and not only create a new relation for it in the DB
// /Need Service functions
if (file_exists($path . '../service/DB-Func.php')) {
require_once $path . '../service/DB-Func.php';
} elseif (file_exists($path . '../service/DB-Func.php')) {
require_once $path . '../configObject/service/DB-Func.php';
}
$hostInf = $maxId['MAX(host_id)'];
$serviceArr = [];
$serviceNbr = [];
// Get all Services link to the Host
$dbResult = $pearDB->query("SELECT DISTINCT service_service_id
FROM host_service_relation
WHERE host_host_id = '" . (int) $key . "'");
$countStatement = $pearDB->prepare(
'SELECT COUNT(*)
FROM host_service_relation
WHERE service_service_id = :service_service_id'
);
$insertStatement = $pearDB->prepare(
'INSERT INTO host_service_relation
VALUES (NULL, NULL, :host_id, NULL, :service_service_id)'
);
while ($service = $dbResult->fetch()) {
// If the Service is link with several Host, we keep this property and don't duplicate it,
// just create a new relation with the new Host
$countStatement->bindValue(
':service_service_id',
(int) $service['service_service_id'],
PDO::PARAM_INT
);
$countStatement->execute();
$mulHostSv = $countStatement->fetch(PDO::FETCH_ASSOC);
if ($mulHostSv['COUNT(*)'] > 1) {
$insertStatement->bindValue(':host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$insertStatement->bindValue(
':service_service_id',
(int) $service['service_service_id'],
PDO::PARAM_INT
);
$insertStatement->execute();
} else {
$serviceArr[$service['service_service_id']] = $service['service_service_id'];
$serviceNbr[$service['service_service_id']] = 1;
}
}
// Register Host -> Duplicate the Service list
if ($row['host_register'] == 1) {
multipleServiceInDB($serviceArr, $serviceNbr, $hostInf, 0);
} else {
// Host Template -> Link to the existing Service Template List
$dbResult = $pearDB->query("SELECT DISTINCT service_service_id
FROM host_service_relation
WHERE host_host_id = '" . (int) $key . "'");
$statement = $pearDB->prepare(
'INSERT INTO host_service_relation
VALUES (NULL, NULL, :host_id, NULL, :service_service_id)'
);
while ($svs = $dbResult->fetch()) {
$statement->bindValue(':host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->bindValue(
':service_service_id',
(int) $svs['service_service_id'],
PDO::PARAM_INT
);
$statement->execute();
}
}
// ContactGroup duplication
$dbResult = $pearDB->query("SELECT DISTINCT contactgroup_cg_id
FROM contactgroup_host_relation
WHERE host_host_id = '" . (int) $key . "'");
$fields['host_cgs'] = '';
$statement = $pearDB->prepare(
'INSERT INTO contactgroup_host_relation
VALUES (:host_id, :contactgroup_cg_id)'
);
while ($cg = $dbResult->fetch()) {
$statement->bindValue(':host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->bindValue(':contactgroup_cg_id', (int) $cg['contactgroup_cg_id'], PDO::PARAM_INT);
$statement->execute();
$fields['host_cgs'] .= $cg['contactgroup_cg_id'] . ',';
}
$fields['host_cgs'] = trim($fields['host_cgs'], ',');
// Contact duplication
$dbResult = $pearDB->query("SELECT DISTINCT contact_id
FROM contact_host_relation
WHERE host_host_id = '" . (int) $key . "'");
$fields['host_cs'] = '';
$statement = $pearDB->prepare(
'INSERT INTO contact_host_relation
VALUES (:host_id, :contact_id)'
);
while ($c = $dbResult->fetch()) {
$statement->bindValue(':host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->bindValue(':contact_id', (int) $c['contact_id'], PDO::PARAM_INT);
$statement->execute();
$fields['host_cs'] .= $c['contact_id'] . ',';
}
$fields['host_cs'] = trim($fields['host_cs'], ',');
// Hostgroup duplication
$dbResult = $pearDB->query("SELECT DISTINCT hostgroup_hg_id
FROM hostgroup_relation
WHERE host_host_id = '" . (int) $key . "'");
$statement = $pearDB->prepare(
'INSERT INTO hostgroup_relation
VALUES (NULL, :hostgroup_hg_id, :host_id)'
);
while ($hg = $dbResult->fetch()) {
$statement->bindValue(':hostgroup_hg_id', (int) $hg['hostgroup_hg_id'], PDO::PARAM_INT);
$statement->bindValue(':host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->execute();
}
// Host Extended Informations
$dbResult = $pearDB->query("SELECT *
FROM extended_host_information
WHERE host_host_id = '" . (int) $key . "'");
while ($ehi = $dbResult->fetch()) {
$val = null;
$ehi['host_host_id'] = $maxId['MAX(host_id)'];
$ehi['ehi_id'] = null;
foreach ($ehi as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
$val
? $val .= ($value2 != null ? (", '" . CentreonDB::escape($value2) . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . CentreonDB::escape($value2) . "'") : 'NULL');
if ($key2 != 'ehi_id') {
$fields[$key2] = $value2;
}
}
$rq = $val
? 'INSERT INTO extended_host_information VALUES (' . $val . ')'
: null;
$dbResult2 = $pearDB->query($rq);
}
// Poller link ducplication
$dbResult = $pearDB->query("SELECT DISTINCT nagios_server_id
FROM ns_host_relation
WHERE host_host_id = '" . (int) $key . "'");
$fields['nagios_server_id'] = '';
$statement = $pearDB->prepare(
'INSERT INTO ns_host_relation
VALUES (:nagios_server_id, :host_id)'
);
while ($hg = $dbResult->fetch()) {
$statement->bindValue(':nagios_server_id', (int) $hg['nagios_server_id'], PDO::PARAM_INT);
$statement->bindValue(':host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->execute();
$fields['nagios_server_id'] .= $hg['nagios_server_id'] . ',';
}
$fields['nagios_server_id'] = trim($fields['nagios_server_id'], ',');
// multiple templates & on demand macros
$mTpRq1 = "SELECT *
FROM `host_template_relation`
WHERE `host_host_id` ='" . (int) $key . "'
ORDER BY `order`";
$dbResult3 = $pearDB->query($mTpRq1);
$multiTP_logStr = '';
$mTpRq2 = 'INSERT INTO `host_template_relation` (`host_host_id`, `host_tpl_id`, `order`)
VALUES (:host_host_id, :host_tpl_id, :order)';
$statement = $pearDB->prepare($mTpRq2);
while ($hst = $dbResult3->fetch()) {
if ($hst['host_tpl_id'] != $maxId['MAX(host_id)']) {
$statement->bindValue(':host_host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->bindValue(':host_tpl_id', (int) $hst['host_tpl_id'], PDO::PARAM_INT);
$statement->bindValue(':order', (int) $hst['order'], PDO::PARAM_INT);
$statement->execute();
$multiTP_logStr .= $hst['host_tpl_id'] . ',';
}
}
$multiTP_logStr = trim($multiTP_logStr, ',');
$fields['templates'] = $multiTP_logStr;
// on demand macros
$mTpRq1 = "SELECT * FROM `on_demand_macro_host` WHERE `host_host_id` ='" . (int) $key . "'";
$dbResult3 = $pearDB->query($mTpRq1);
$mTpRq2 = 'INSERT INTO `on_demand_macro_host`
(`host_host_id`, `host_macro_name`, `host_macro_value`,
`is_password`)
VALUES (:host_host_id, :host_macro_name, :host_macro_value,
:is_password)';
$statement = $pearDB->prepare($mTpRq2);
$macroPasswords = [];
while ($hst = $dbResult3->fetch()) {
$macName = str_replace('$', '', $hst['host_macro_name']);
$macVal = $hst['host_macro_value'];
if (! isset($hst['is_password'])) {
$hst['is_password'] = '0';
}
$statement->bindValue(':host_host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->bindValue(':host_macro_name', '$' . $macName . '$', PDO::PARAM_STR);
$statement->bindValue(':host_macro_value', $macVal, PDO::PARAM_STR);
$statement->bindValue(':is_password', (int) $hst['is_password'], PDO::PARAM_INT);
$statement->execute();
$fields['_' . strtoupper($macName) . '_'] = $macVal;
if ($hst['is_password'] === 1) {
$maxIdStatement = $pearDB->query(
'SELECT MAX(host_macro_id) from on_demand_macro_host WHERE is_password = 1'
);
$resultMacro = $maxIdStatement->fetch();
$macroPasswords[$resultMacro['MAX(host_macro_id)']] = [
'macroName' => $macName,
'macroValue' => $macVal,
];
}
}
// Host Categorie Duplication
$request = 'INSERT INTO hostcategories_relation
SELECT hostcategories_hc_id, :max_host_id
FROM hostcategories_relation
WHERE host_host_id = :host_id';
$statement = $pearDB->prepare($request);
$statement->bindValue(':max_host_id', (int) $maxId['MAX(host_id)'], PDO::PARAM_INT);
$statement->bindValue(':host_id', (int) $key, PDO::PARAM_INT);
$statement->execute();
/**
* The value should be duplicated in vault if it's a password and is already in vault
* The pattern secret:: define that the value is store in vault.
*/
if (
! empty($row['host_snmp_community'])
&& str_starts_with(VaultConfiguration::VAULT_PATH_PATTERN, $row['host_snmp_community'])
|| $macroPasswords !== []
) {
if ($vaultConfiguration !== null) {
/** @var ReadVaultRepositoryInterface $readVaultRepository */
$readVaultRepository = $kernel->getContainer()->get(
ReadVaultRepositoryInterface::class
);
/** @var WriteVaultRepositoryInterface $writeVaultRepository */
$writeVaultRepository = $kernel->getContainer()->get(
WriteVaultRepositoryInterface::class
);
$writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH);
try {
duplicateHostSecretsInVault(
$readVaultRepository,
$writeVaultRepository,
$logger,
$row['host_snmp_community'],
$macroPasswords,
$key,
(int) $maxId['MAX(host_id)']
);
} catch (Throwable $ex) {
error_log((string) $ex);
}
}
}
signalConfigurationChange('host', (int) $maxId['MAX(host_id)']);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOST,
object_id: $maxId['MAX(host_id)'],
object_name: $hostName,
action_type: ActionLog::ACTION_TYPE_ADD
);
}
}
// if all duplication names are already used, next value is never set
if (isset($maxId['MAX(host_id)'])) {
$centreon->user->access->updateACL([
'type' => 'HOST',
'id' => $maxId['MAX(host_id)'],
'action' => 'DUP',
'duplicate_host' => (int) $key,
]);
}
}
}
CentreonACL::duplicateHostAcl($hostAcl);
}
/**
* @param int $host_id
*/
function resetHostHostParent(int $host_id): void
{
global $pearDB;
$stmt = $pearDB->prepare('DELETE FROM host_hostparent_relation WHERE host_host_id = :hostId');
$stmt->bindValue(':hostId', $host_id, PDO::PARAM_INT);
$stmt->execute();
}
/**
* @param int $host_id
*/
function resetHostHostChild(int $host_id): void
{
global $pearDB;
$stmt = $pearDB->prepare('DELETE FROM host_hostparent_relation WHERE host_parent_hp_id = :hostId');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_categories/help.php | centreon/www/include/configuration/configObject/host_categories/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['hc_name'] = dgettext(
'help',
'Define a short name for this category. It will be displayed with this name in the ACL configuration.'
);
$help['hc_alias'] = dgettext('help', 'Use this field for a longer description of this category.');
$help['hc_hosts'] = dgettext('help', 'Select the hosts that this category is linked to.');
$help['hc_hostsTemplate'] = dgettext('help', 'Select the host templates that this category is linked to.');
$help['hc_type'] = dgettext(
'help',
'Whether this category is a severity. Severities appear on the monitoring consoles.'
);
$help['hc_severity_level'] = dgettext(
'help',
'Severity level, must be a number. The items displayed will be sorted in ascending order. Thus the '
. 'lowest severity is considered than the highest priority.'
);
$help['hc_severity_icon'] = dgettext('help', 'Icon for this severity.');
$help['hc_activate'] = dgettext('help', 'Whether or not this category is enabled.');
$help['hc_comment'] = dgettext('help', 'Comment regarding this category.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_categories/hostCategories.php | centreon/www/include/configuration/configObject/host_categories/hostCategories.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$hG = $_GET['hc_id'] ?? null;
$hP = $_POST['hc_id'] ?? null;
$hc_id = $hG ?: $hP;
$cG = $_GET['select'] ?? null;
$cP = $_POST['select'] ?? null;
$select = $cG ?: $cP;
$cG = $_GET['dupNbr'] ?? null;
$cP = $_POST['dupNbr'] ?? null;
$dupNbr = $cG ?: $cP;
// Path to the configuration dir
$path = './include/configuration/configObject/host_categories/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
use Core\Common\Domain\Exception\RepositoryException;
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $centreon->user->access;
$dbmon = new CentreonDB('centstorage');
$aclDbName = $acl->getNameDBAcl();
$hcString = $acl->getHostCategoriesString();
$hoststring = $acl->getHostsString('ID', $dbmon);
try {
switch ($o) {
case 'a':
require_once $path . 'formHostCategories.php';
break;
case 'w':
require_once $path . 'formHostCategories.php';
break;
case 'c':
require_once $path . 'formHostCategories.php';
break;
case 's':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableHostCategoriesInDB($hc_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostCategories.php';
break;
case 'ms':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableHostCategoriesInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostCategories.php';
break;
case 'u':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableHostCategoriesInDB($hc_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostCategories.php';
break;
case 'mu':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableHostCategoriesInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostCategories.php';
break;
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleHostCategoriesInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostCategories.php';
break;
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteHostCategoriesInDB($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostCategories.php';
break;
default:
require_once $path . 'listHostCategories.php';
break;
}
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while processing host categories: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while processing host categories');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_categories/formHostCategories.php | centreon/www/include/configuration/configObject/host_categories/formHostCategories.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
if (! isset($centreon)) {
exit();
}
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
// If user isn’t admin, check ACL
if (! $oreon->user->admin) {
if ($hc_id
&& $hcString !== "''"
&& ! str_contains($hcString, "'{$hc_id}'")
) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this host category'));
return;
}
}
// Load initial values if editing or viewing
$initialValues = [];
$hc = [];
if (in_array($o, ['c', 'w'], true) && $hc_id) {
try {
$queryBuilder = $pearDB->createQueryBuilder();
$query = $queryBuilder->select('*')
->from('hostcategories')
->where('hc_id = :hc_id')
->getQuery();
$hc = $pearDB->fetchAssociative(
$query,
QueryParameters::create([
QueryParameter::int('hc_id', (int) $hc_id),
])
) ?: [];
// map old field names for the form
$hc['hc_severity_level'] = $hc['level'] ?? '';
$hc['hc_severity_icon'] = $hc['icon_id'] ?? '';
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error retrieving host category',
['hcId' => $hc_id],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText("Unable to load host category : hcId = {$hc_id}");
}
}
// Fetch image lists
$extImg = return_image_list(1);
$extImgStatusmap = return_image_list(2);
// Define Templatse
$attrsText = ['size' => '30'];
$attrsTextLong = ['size' => '50'];
$attrsAdvSelect = ['style' => 'width: 220px; height: 220px;'];
$attrsTextarea = ['rows' => '4', 'cols' => '60'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$hostRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&action=list';
$attrHosts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $hostRoute, 'multiple' => true, 'linkedObject' => 'centreonHost'];
$hostTplRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_hosttemplate&action=list';
$attrHosttemplates = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $hostTplRoute, 'multiple' => true, 'linkedObject' => 'centreonHosttemplates'];
// Create formulary
$form = new HTML_QuickFormCustom('Form', 'post', "?p={$p}");
switch ($o) {
case 'a':
$form->addElement('header', 'title', _('Add a host category'));
break;
case 'c':
$form->addElement('header', 'title', _('Modify a host category'));
break;
case 'w':
$form->addElement('header', 'title', _('View a host category'));
break;
}
// Catrgorie basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'hc_name', _('Name'), $attrsText);
$form->addElement('text', 'hc_alias', _('Alias'), $attrsText);
// Severity
$form->addElement('header', 'relation', _('Relation'));
$hctype = $form->addElement('checkbox', 'hc_type', _('Severity type'), null, ['id' => 'hc_type']);
if (isset($hc_id, $hc['level']) && $hc['level'] != '') {
$hctype->setValue('1');
}
$form->addElement('text', 'hc_severity_level', _('Level'), ['size' => '10']);
$form->addElement(
'select',
'hc_severity_icon',
_('Icon'),
return_image_list(1),
['id' => 'icon_id', 'onChange' => "showLogo('icon_id_ctn', this.value)"]
);
// Linked hosts / templates
$defHosts = './include/common/webServices/rest/internal.php?object=centreon_configuration_host'
. "&action=defaultValues&target=hostcategories&field=hc_hosts&id={$hc_id}";
$form->addElement('select2', 'hc_hosts', _('Linked Hosts'), [], array_merge($attrHosts, ['defaultDatasetRoute' => $defHosts]));
$defTpls = './include/common/webServices/rest/internal.php?object=centreon_configuration_hosttemplate'
. "&action=defaultValues&target=hostcategories&field=hc_hostsTemplate&id={$hc_id}";
$ams1 = $form->addElement('select2', 'hc_hostsTemplate', _('Linked Host Template'), [], array_merge($attrHosttemplates, ['defaultDatasetRoute' => $defTpls]));
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$form->addElement('textarea', 'hc_comment', _('Comments'), $attrsTextarea);
$hcActivation[] = $form->createElement('radio', 'hc_activate', null, _('Enabled'), '1');
$hcActivation[] = $form->createElement('radio', 'hc_activate', null, _('Disabled'), '0');
$form->addGroup($hcActivation, 'hc_activate', _('Status'), ' ');
$form->setDefaults(['hc_activate' => '1']);
// Hidden fields
$form->addElement('hidden', 'hc_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
// Form Rules
function myReplace()
{
global $form;
$name = $form->getSubmitValues()['hc_name'] ?? '';
return str_replace(' ', '_', $name);
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('hc_name', 'myReplace');
$form->addRule('hc_name', _('Compulsory Name'), 'required');
$form->addRule('hc_alias', _('Compulsory Alias'), 'required');
$form->registerRule('exist', 'callback', 'testHostCategorieExistence');
$form->addRule('hc_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font color='red;'>*</font>" . _('Required fields'));
$form->addRule('hc_severity_level', _('Must be a number'), 'numeric');
$form->registerRule('shouldNotBeEqTo0', 'callback', 'shouldNotBeEqTo0');
$form->addRule('hc_severity_level', _("Can't be equal to 0"), 'shouldNotBeEqTo0');
$form->addFormRule('checkSeverity');
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", '
. 'BORDERCOLOR, "orange", TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", '
. 'CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"'
);
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= "<span style=\"display:none\" id=\"help:{$key}\">{$text}</span>\n";
}
$tpl->assign('helptext', $helptext);
if ($o === 'w') {
// Just watch a HostCategorie information
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "window.location.href='?p={$p}&o=c&hc_id={$hc_id}'"]
);
}
$form->setDefaults($hc);
$form->freeze();
} elseif ($o === 'c') {
// Modify a HostCategorie information
$form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($hc);
} elseif ($o === 'a') {
$form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$tpl->assign('p', $p);
$valid = false;
if ($form->validate()) {
$hcObj = $form->getElement('hc_id');
if ($form->getSubmitValue('submitA')) {
try {
// Insert and capture new ID
$newId = insertHostCategoriesInDB();
$hcObj->setValue($newId);
$valid = true;
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while inserting host category: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while inserting host category');
}
} elseif ($form->getSubmitValue('submitC')) {
try {
// Update existing record
updateHostCategoriesInDB((int) $hcObj->getValue());
$valid = true;
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while updating host category: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while updating host category');
}
}
}
if ($valid) {
require_once $path . 'listHostCategories.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign('topdoc', _('Documentation'));
$tpl->display('formHostCategories.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_categories/listHostCategories.php | centreon/www/include/configuration/configObject/host_categories/listHostCategories.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
if (! isset($centreon)) {
exit();
}
require_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
require_once _CENTREON_PATH_ . '/www/include/common/sqlCommonFunction.php';
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\ValueObjectException;
// Sanitize and persist/restore search input
$rawSearch = $_POST['searchH'] ?? $_GET['searchH'] ?? null;
if ($rawSearch !== null) {
$search = HtmlSanitizer::createFromString($rawSearch)
->removeTags()
->sanitize()
->getString();
$centreon->historySearch[$url]['search'] = $search;
} else {
$search = $centreon->historySearch[$url]['search'] ?? null;
}
// Calculate offset
$offset = $num * $limit;
try {
// Build main query
$queryBuilder = $pearDB->createQueryBuilder()
->select('hc.hc_id', 'hc.hc_name', 'hc.hc_alias', 'hc.level', 'hc.hc_activate')
->from('hostcategories', 'hc');
$parameters = [];
if ($search !== '') {
$queryBuilder->andWhere(
$queryBuilder->expr()->or(
$queryBuilder->expr()->like('hc.hc_name', ':search'),
$queryBuilder->expr()->like('hc.hc_alias', ':search')
)
);
$parameters[] = QueryParameter::string('search', "%{$search}%");
}
if (! $centreon->user->admin && $hcString !== "''") {
$hcIds = array_map(
fn (string $s) => (int) trim($s, "'\" \t\n\r\0\x0B"),
explode(',', $hcString)
);
$bindparams = createMultipleBindParameters($hcIds, 'hcId', QueryParameterTypeEnum::INTEGER);
if (count($bindparams['parameters']) > 0) {
$queryBuilder->andWhere("hc.hc_id IN ( {$bindparams['placeholderList']} )");
$parameters = array_merge($parameters, $bindparams['parameters']);
}
}
$queryForCount = $queryBuilder->getQuery();
$queryBuilder->orderBy('hc.hc_name')
->offset($offset)
->limit($limit);
$mainQuery = $queryBuilder->getQuery();
$queryParams = QueryParameters::create($parameters);
// Execute fetch
$hostCategories = $pearDB->fetchAllAssociative($mainQuery, $queryParams);
// build count query
// remove the select part of the query
$fromPos = stripos($queryForCount, ' FROM ');
$fromClause = substr($queryForCount, $fromPos);
$countSql = 'SELECT COUNT(*) AS total' . $fromClause;
$countRow = $pearDB->fetchAssociative($countSql, $queryParams);
$totalRows = (int) ($countRow['total'] ?? 0);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error fetching host categories list',
[
'hcString' => $hcString,
'search' => $search,
'limit' => $limit,
'num' => $num,
],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error fetching host categories list');
}
// Prepare pagination and template
$rows = $totalRows;
$search = tidySearchKey($search, $advanced_search);
include_once './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// Header menu definitions
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('Alias'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_hc_type', _('Type'));
$tpl->assign('headerMenu_hostAct', _('Enabled Hosts'));
$tpl->assign('headerMenu_hostDeact', _('Disabled Hosts'));
$tpl->assign('headerMenu_options', _('Options'));
// Build search form
$form = new HTML_QuickFormCustom('select_form', 'POST', "?p={$p}");
// Different style between each lines
$style = 'one';
$attrBtn = [
'class' => 'btc bt_success',
'onClick' => "window.history.replaceState('', '', '?p={$p}');",
];
$form->addElement('submit', 'Search', _('Search'), $attrBtn);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
// count enabled/disabled hosts per category
try {
$countsQuerybuilder = $pearDB->createQueryBuilder()
->select('hcr.hostcategories_hc_id AS hc_id')
->addSelect('SUM(CASE WHEN h.host_activate = "1" THEN 1 ELSE 0 END) AS enabled')
->addSelect('SUM(CASE WHEN h.host_activate = "0" THEN 1 ELSE 0 END) AS disabled')
->from('hostcategories_relation', 'hcr')
->join('hcr', 'host', 'h', 'h.host_id = hcr.host_host_id')
->where('h.host_register = "1"');
if (! $centreon->user->admin) {
$subQuerybuilder = $pearDB->createQueryBuilder();
$subQuerybuilder->select('1')
->from("{$aclDbName}.centreon_acl", 'acl')
->where(
$countsQuerybuilder->expr()->equal('acl.host_id', 'h.host_id')
)
->andWhere(
$countsQuerybuilder->expr()->in('acl.group_id', "{$acl->getAccessGroupsString()}")
);
$countsQuerybuilder->andWhere(
"EXISTS( {$subQuerybuilder->getQuery()} )"
);
}
$countsQuerybuilder->groupBy('hcr.hostcategories_hc_id');
$countsSql = $countsQuerybuilder->getQuery();
$countsRows = $pearDB->fetchAllAssociative($countsSql);
$countsByCategory = [];
foreach ($countsRows as $rowHc) {
$countsByCategory[$rowHc['hc_id']] = [
'enabled' => (int) $rowHc['enabled'],
'disabled' => (int) $rowHc['disabled'],
];
}
} catch (ConnectionException|CollectionException|ValueObjectException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error fetching host categories counts',
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error fetching host categories counts');
}
// Populate rows
foreach ($hostCategories as $hc) {
// selection checkbox + action links
$selectedElements = $form->addElement('checkbox', "select[{$hc['hc_id']}]");
$moptions = '';
if ($hc['hc_activate']) {
$moptions .= "<a href='main.php?p={$p}&hc_id={$hc['hc_id']}&o=u"
. "&limit={$limit}&num={$num}&search={$search}¢reon_token={$centreonToken}'>"
. "<img src='img/icons/disabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Disabled') . "'></a>";
} else {
$moptions .= "<a href='main.php?p={$p}&hc_id={$hc['hc_id']}&o=s"
. "&limit={$limit}&num={$num}&search={$search}¢reon_token={$centreonToken}'>"
. "<img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Enabled') . "'></a>";
}
$moptions .= "<input maxlength='3' size='3' value='1' style='margin-bottom:0px;' "
. "name='dupNbr[{$hc['hc_id']}]' "
. 'onKeypress="if(event.keyCode>31&&(event.keyCode<45||event.keyCode>57))'
. 'event.returnValue=false;" />';
$elemArr[] = [
'MenuClass' => "list_{$style}",
'RowMenu_select' => $selectedElements->toHtml(),
'RowMenu_name' => CentreonUtils::escapeSecure($hc['hc_name']),
'RowMenu_link' => "main.php?p={$p}&o=c&hc_id={$hc['hc_id']}",
'RowMenu_desc' => CentreonUtils::escapeSecure($hc['hc_alias']),
'RowMenu_hc_type' => $hc['level']
? _('Severity') . " ({$hc['level']})"
: _('Regular'),
'RowMenu_status' => $hc['hc_activate'] ? _('Enabled') : _('Disabled'),
'RowMenu_badge' => $hc['hc_activate'] ? 'service_ok' : 'service_critical',
'RowMenu_hostAct' => $countsByCategory[$hc['hc_id']]['enabled'] ?? 0,
'RowMenu_hostDeact' => $countsByCategory[$hc['hc_id']]['disabled'] ?? 0,
'RowMenu_options' => $moptions,
];
$style = ($style === 'one') ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
$tpl->assign('limit', $limit);
$tpl->assign('searchHC', $search);
$tpl->assign(
'msg',
[
'addL' => "main.php?p={$p}&o=a",
'addT' => _('Add'),
'delConfirm' => _('Do you confirm the deletion ?'),
]
);
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'var bChecked=isChecked();'
. "if(this.form.elements['{$option}'].selectedIndex!=0&&!bChecked){alert('"
. _('Please select one or more items') . "');return false;}"
. "if(this.form.elements['{$option}'].selectedIndex==1&&confirm('"
. _('Do you confirm the duplication ?') . "')){setO(this.value);submit();}"
. "else if(this.form.elements['{$option}'].selectedIndex==2&&confirm('"
. _('Do you confirm the deletion ?') . "')){setO(this.value);submit();}"
. "else if(this.form.elements['{$option}'].selectedIndex==3){setO(this.value);submit();}"
. "else if(this.form.elements['{$option}'].selectedIndex==4){setO(this.value);submit();}"
. "this.form.elements['{$option}'].selectedIndex=0",
];
$form->addElement(
'select',
$option,
null,
[
null => _('More actions...'),
'm' => _('Duplicate'),
'd' => _('Delete'),
'ms' => _('Enable'),
'mu' => _('Disable'),
],
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listHostCategories.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_categories/DB-Func.php | centreon/www/include/configuration/configObject/host_categories/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\ActionLog\Domain\Model\ActionLog;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
// Only these fields are permitted from user input
const ALLOWED_FIELDS = [
'hc_name', 'hc_alias', 'hc_type',
'hc_severity_level', 'hc_severity_icon',
'hc_comment', 'hc_activate',
'hc_hosts', 'hc_hostsTemplate',
];
/**
* Retrieve only the allowed host-category form fields and sanitize them.
*/
function getHostCategoryValues(): array
{
global $form;
$raw = $form ? $form->getSubmitValues() : [];
$ret = [];
foreach (ALLOWED_FIELDS as $field) {
if (! array_key_exists($field, $raw)) {
continue;
}
$value = $raw[$field];
// Sanitize strings
if (is_string($value)) {
$value = HtmlSanitizer::createFromString($value)
->removeTags()
->sanitize()
->getString();
}
$ret[$field] = $value;
}
return $ret;
}
/**
* Rule that checks whether severity data is set
*/
function checkSeverity(array $fields)
{
$errors = [];
if (! empty($fields['hc_type']) && ($fields['hc_severity_level'] ?? '') === '') {
$errors['hc_severity_level'] = 'Severity level is required';
}
if (! empty($fields['hc_type']) && ($fields['hc_severity_icon'] ?? '') === '') {
$errors['hc_severity_icon'] = 'Severity icon is required';
}
return $errors ?: true;
}
/**
* Check existence of a host category name
*
* @throws RepositoryException
*/
function testHostCategorieExistence(?string $name = null): bool
{
global $pearDB, $form;
if (empty($name)) {
throw new RepositoryException('Host category name is required for existence check');
}
$currentId = $form ? $form->getSubmitValue('hc_id') : null;
$qb = $pearDB->createQueryBuilder();
$query = $qb->select('hc_id')
->from('hostcategories')
->where('hc_name = :hc_name')
->getQuery();
try {
$cleanName = HtmlSanitizer::createFromString($name)
->removeTags()
->sanitize()
->getString();
$result = $pearDB->fetchAssociative(
$query,
QueryParameters::create([
QueryParameter::string('hc_name', $cleanName),
])
);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException('Unable to check host category existence', ['hcName' => $name], $exception);
}
return ! ($result && isset($result['hc_id']) && $result['hc_id'] != $currentId);
}
/**
* Simple boolean check (legacy)
* @param mixed $value
*/
function shouldNotBeEqTo0($value)
{
return (bool) $value;
}
/**
* Enable one or multiple host categories
*
* @throws RepositoryException
*/
function enableHostCategoriesInDB(?int $hcId = null, array $hcArr = []): void
{
global $pearDB, $centreon;
if (! $hcId && $hcArr === []) {
return;
}
if ($hcId) {
$hcArr = [$hcId => '1'];
}
$updQuery = $pearDB->createQueryBuilder()
->update('hostcategories')
->set('hc_activate', "'1'")
->where('hc_id = :hc_id')
->getQuery();
$selQuery = $pearDB->createQueryBuilder()
->select('hc_name')
->from('hostcategories')
->where('hc_id = :hc_id')
->getQuery();
try {
foreach (array_keys($hcArr) as $key) {
$id = filter_var($key, FILTER_VALIDATE_INT);
$pearDB->update(
$updQuery,
QueryParameters::create([QueryParameter::int('hc_id', $id)])
);
$row = $pearDB->fetchAssociative(
$selQuery,
QueryParameters::create([QueryParameter::int('hc_id', $id)])
);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOSTCATEGORIES,
object_id: $id,
object_name: $row['hc_name'] ?? '',
action_type: ActionLog::ACTION_TYPE_ENABLE
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Unable to enable host categories',
[
'hcId' => $hcId,
'hcArr' => $hcArr,
],
$exception
);
}
}
/**
* Disable one or multiple host categories
*
* @throws RepositoryException
*/
function disableHostCategoriesInDB(?int $hcId = null, array $hcArr = []): void
{
global $pearDB, $centreon;
if (! $hcId && $hcArr === []) {
return;
}
if ($hcId) {
$hcArr = [$hcId => '1'];
}
$updQuery = $pearDB->createQueryBuilder()
->update('hostcategories')
->set('hc_activate', "'0'")
->where('hc_id = :hc_id')
->getQuery();
$selQuery = $pearDB->createQueryBuilder()
->select('hc_name')
->from('hostcategories')
->where('hc_id = :hc_id')
->getQuery();
try {
foreach (array_keys($hcArr) as $key) {
$id = filter_var($key, FILTER_VALIDATE_INT);
$pearDB->update(
$updQuery,
QueryParameters::create([QueryParameter::int('hc_id', (int) $id)])
);
$row = $pearDB->fetchAssociative(
$selQuery,
QueryParameters::create([QueryParameter::int('hc_id', (int) $id)])
);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOSTCATEGORIES,
object_id: $id,
object_name: $row['hc_name'] ?? '',
action_type: ActionLog::ACTION_TYPE_DISABLE
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Unable to disable host categories',
[
'hcId' => $hcId,
'hcArr' => $hcArr,
],
$exception
);
}
}
/**
* Delete one or multiple host categories
*
* @throws RepositoryException
*/
function deleteHostCategoriesInDB(array $hostCategories = []): void
{
global $pearDB, $centreon;
if ($hostCategories === []) {
return;
}
$selQuery = $pearDB->createQueryBuilder()
->select('hc_name')
->from('hostcategories')
->where('hc_id = :hc_id')
->getQuery();
$delQuery = $pearDB->createQueryBuilder()
->delete('hostcategories')
->where('hc_id = :hc_id')
->getQuery();
try {
foreach (array_keys($hostCategories) as $key) {
$id = filter_var($key, FILTER_VALIDATE_INT);
$row = $pearDB->fetchAssociative(
$selQuery,
QueryParameters::create([QueryParameter::int('hc_id', (int) $id)])
);
$pearDB->delete(
$delQuery,
QueryParameters::create([QueryParameter::int('hc_id', (int) $id)])
);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOSTCATEGORIES,
object_id: $id,
object_name: $row['hc_name'] ?? '',
action_type: ActionLog::ACTION_TYPE_DELETE
);
}
$centreon->user->access->updateACL();
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Unable to delete host categories',
[
'hostCategories' => $hostCategories,
],
$exception
);
}
}
/**
* Duplicate host categories N times
*
* @throws RepositoryException
*/
function multipleHostCategoriesInDB(array $hostCategories = [], array $nbrDup = []): void
{
global $pearDB, $centreon;
$aclMap = [];
try {
foreach (array_keys($hostCategories) as $key) {
$hcId = (int) filter_var($key, FILTER_VALIDATE_INT);
$selectQ = $pearDB->createQueryBuilder()
->select('*')
->from('hostcategories')
->where('hc_id = :hc_id')
->limit(1)
->getQuery();
$row = $pearDB->fetchAssociative(
$selectQ,
QueryParameters::create([QueryParameter::int('hc_id', $hcId)])
);
if (! $row) {
continue;
}
for ($i = 1; $i <= ($nbrDup[$key] ?? 0); $i++) {
$newName = HtmlSanitizer::createFromString($row['hc_name'])
->removeTags()
->sanitize()
->getString() . "_{$i}";
if (! testHostCategorieExistence($newName)) {
continue;
}
$qbInsert = $pearDB->createQueryBuilder()
->insert('hostcategories')
->values([
'hc_name' => ':hc_name',
'hc_alias' => ':hc_alias',
'level' => ':level',
'icon_id' => ':icon_id',
'hc_comment' => ':hc_comment',
'hc_activate' => ':hc_activate',
]);
$insQuery = $qbInsert->getQuery();
$params = [
QueryParameter::string('hc_name', $newName),
QueryParameter::string('hc_alias', HtmlSanitizer::createFromString($row['hc_alias'])
->removeTags()->sanitize()->getString()),
QueryParameter::int('level', $row['level'] !== null ? (int) $row['level'] : null),
QueryParameter::int('icon_id', $row['icon_id'] !== null ? (int) $row['icon_id'] : null),
$row['hc_comment']
? QueryParameter::string('hc_comment', HtmlSanitizer::createFromString($row['hc_comment'])
->removeTags()->sanitize()->getString())
: QueryParameter::string('hc_comment', null),
QueryParameter::string('hc_activate', preg_match('/^[01]$/', $row['hc_activate'] ?? '') ? $row['hc_activate'] : '0'),
];
$pearDB->insert($insQuery, QueryParameters::create($params));
$newId = (int) $pearDB->getLastInsertId();
$aclMap[$newId] = $hcId;
if (empty($row['level'])) {
$relSelect = $pearDB->createQueryBuilder()
->select('host_host_id')
->from('hostcategories_relation')
->where('hostcategories_hc_id = :hc_id')
->getQuery();
$hostRows = $pearDB->fetchAllAssociative(
$relSelect,
QueryParameters::create([QueryParameter::int('hc_id', $hcId)])
);
foreach ($hostRows as $host) {
$pearDB->insert(
$pearDB->createQueryBuilder()
->insert('hostcategories_relation')
->values([
'hostcategories_hc_id' => ':new',
'host_host_id' => ':host',
])
->getQuery(),
QueryParameters::create([
QueryParameter::int('new', $newId),
QueryParameter::int('host', $host['host_host_id']),
])
);
}
}
$fields = [
'hc_name' => $newName,
'hc_hosts' => ! empty($hostRows)
? implode(',', array_column($hostRows, 'host_host_id'))
: '',
];
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOSTCATEGORIES,
object_id: $newId,
object_name: $newName,
action_type: ActionLog::ACTION_TYPE_ADD,
fields: $fields
);
}
}
CentreonACL::duplicateHcAcl($aclMap);
$centreon->user->access->updateACL();
} catch (ValueObjectException|CollectionException|ConnectionException|RepositoryException $exception) {
throw new RepositoryException('Unable to duplicate host categories', ['map' => $aclMap], $exception);
}
}
/**
* Insert host categories
*
* @throws RepositoryException
*/
function insertHostCategories(array $ret = []): int
{
global $pearDB, $centreon;
if ($ret === []) {
$ret = getHostCategoryValues();
}
$qb = $pearDB->createQueryBuilder()
->insert('hostcategories')
->values([
'hc_name' => ':hc_name',
'hc_alias' => ':hc_alias',
'level' => ':level',
'icon_id' => ':icon_id',
'hc_comment' => ':hc_comment',
'hc_activate' => ':hc_activate',
]);
$insQuery = $qb->getQuery();
// Enforce '0' or '1' on activation
$rawAct = $ret['hc_activate']['hc_activate'] ?? '';
$activate = preg_match('/^[01]$/', $rawAct) ? $rawAct : '0';
$params = [
QueryParameter::string('hc_name', $ret['hc_name'] ?? ''),
QueryParameter::string('hc_alias', $ret['hc_alias'] ?? ''),
QueryParameter::int('level', ! empty($ret['hc_severity_level']) ? (int) $ret['hc_severity_level'] : null),
QueryParameter::int('icon_id', isset($ret['hc_severity_icon']) ? (int) $ret['hc_severity_icon'] : null),
QueryParameter::string('hc_comment', $ret['hc_comment'] ?? null),
QueryParameter::string('hc_activate', $activate),
];
try {
$pearDB->insert($insQuery, QueryParameters::create($params));
$hcId = (int) $pearDB->getLastInsertId();
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOSTCATEGORIES,
object_id: $hcId,
object_name: $ret['hc_name'] ?? '',
action_type: ActionLog::ACTION_TYPE_ADD,
fields: $fields
);
return $hcId;
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Unable to insert host category',
[
'hcName' => $ret['hc_name'] ?? '',
'params' => $params,
'ret' => $ret,
'hcId' => $hcId ?? null,
],
$exception
);
}
}
/**
* Legacy wrapper: calls insertHostCategories(), then updates relations & ACL.
*
* @throws RepositoryException
*/
function insertHostCategoriesInDB(array $ret = []): int
{
global $centreon;
try {
$hcId = insertHostCategories($ret);
updateHostCategoriesHosts($hcId, $ret);
$centreon->user->access->updateACL();
return $hcId;
} catch (RepositoryException $exception) {
throw $exception;
}
}
/**
* Update host categories (master entry + relations + ACL)
*
* @throws RepositoryException
*/
function updateHostCategoriesInDB(?int $hcId = null): void
{
global $centreon;
if (! $hcId) {
throw new RepositoryException('Host category ID is required for update');
}
try {
updateHostCategories($hcId);
updateHostCategoriesHosts($hcId);
$centreon->user->access->updateACL();
} catch (RepositoryException $exception) {
throw $exception;
}
}
/**
* Perform the UPDATE query on hostcategories.
*
* @throws RepositoryException
*/
function updateHostCategories(int $hcId): void
{
global $pearDB, $centreon;
// Whitelist & sanitize incoming values
$ret = getHostCategoryValues();
$qb = $pearDB->createQueryBuilder();
$query = $qb->update('hostcategories')
->set('hc_name', ':hc_name')
->set('hc_alias', ':hc_alias')
->set('level', ':level')
->set('icon_id', ':icon_id')
->set('hc_comment', ':hc_comment')
->set('hc_activate', ':hc_activate')
->where('hc_id = :hc_id')
->getQuery();
// Prepare params with conditional binding
$rawAct = $ret['hc_activate']['hc_activate'] ?? '';
$activate = preg_match('/^[01]$/', $rawAct) ? $rawAct : '0';
$params = [
QueryParameter::string('hc_name', $ret['hc_name'] ?? ''),
QueryParameter::string('hc_alias', $ret['hc_alias'] ?? ''),
! empty($ret['hc_type']) && isset($ret['hc_severity_level'])
? QueryParameter::int('level', (int) $ret['hc_severity_level'])
: QueryParameter::string('level', null),
! empty($ret['hc_type']) && isset($ret['hc_severity_icon'])
? QueryParameter::int('icon_id', (int) $ret['hc_severity_icon'])
: QueryParameter::string('icon_id', null),
QueryParameter::string('hc_comment', $ret['hc_comment'] ?? null),
QueryParameter::string('hc_activate', $activate),
QueryParameter::int('hc_id', $hcId),
];
try {
// Execute update
$pearDB->update($query, QueryParameters::create($params));
// Log change
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOSTCATEGORIES,
object_id: $hcId,
object_name: $ret['hc_name'] ?? '',
action_type: ActionLog::ACTION_TYPE_CHANGE,
fields: $fields
);
if (array_key_exists('hc_activate', $ret)) {
$centreon->CentreonLogAction->insertLog(
object_type: ActionLog::OBJECT_TYPE_HOSTCATEGORIES,
object_id: $hcId,
object_name: $ret['hc_name'] ?? '',
action_type: $activate === '1'
? ActionLog::ACTION_TYPE_ENABLE
: ActionLog::ACTION_TYPE_DISABLE,
fields: $fields
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException('Unable to update host category', ['hcId' => $hcId], $exception);
}
}
/**
* Update host relations: deletes old relations and inserts new ones.
*
* @throws RepositoryException
*/
function updateHostCategoriesHosts(?int $hcId, array $ret = []): void
{
global $pearDB, $form;
if (! $hcId) {
throw new RepositoryException('Host category ID is required for relation update');
}
try {
// Delete old relations
$pearDB->delete(
$pearDB->createQueryBuilder()
->delete('hostcategories_relation')
->where('hostcategories_hc_id = :hc_id')
->getQuery(),
QueryParameters::create([QueryParameter::int('hc_id', $hcId)])
);
// Merge hosts
$hosts = array_merge(
$ret['hc_hosts'] ?? CentreonUtils::mergeWithInitialValues($form, 'hc_hosts'),
$ret['hc_hostsTemplate'] ?? CentreonUtils::mergeWithInitialValues($form, 'hc_hostsTemplate')
);
if ($hosts === []) {
return;
}
$insertBuilder = $pearDB->createQueryBuilder()
->insert('hostcategories_relation')
->values([
'hostcategories_hc_id' => ':hc_id',
'host_host_id' => ':host',
]);
$insQuery = $insertBuilder->getQuery();
foreach ($hosts as $hostId) {
$pearDB->insert(
$insQuery,
QueryParameters::create([
QueryParameter::int('hc_id', $hcId),
QueryParameter::int('host', (int) $hostId),
])
);
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException('Unable to update host relations', ['hcId' => $hcId], $exception);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-mibs/formMibs.php | centreon/www/include/configuration/configObject/traps-mibs/formMibs.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
// Debug Flag
$debug = 0;
$max_characters = 20000;
// Database retrieve information for Manufacturer
function myDecodeMib($arg)
{
return html_entity_decode($arg ?? '', ENT_QUOTES, 'UTF-8');
}
// Init Formulary
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$form->addElement('header', 'title', _('Import SNMP traps from MIB file'));
// Manufacturer information
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_manufacturer&action=list';
$attrManufacturer = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => false, 'linkedObject' => 'centreonManufacturer'];
$form->addElement('select2', 'mnftr', _('Vendor Name'), [], $attrManufacturer);
$form->addElement('file', 'filename', _('File (.mib)'));
// Formulary Rules
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('mnftr', _('Compulsory Name'), 'required');
$form->addRule('filename', _('Compulsory Name'), 'required');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", '
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, -300, '
. 'SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
// Just watch a Command information
$subA = $form->addElement('submit', 'submit', _('Import'), ['class' => 'btc bt_success']);
$form->addElement('header', 'status', _('Status'));
$msg = null;
$stdout = null;
if ($form->validate()) {
$ret = $form->getSubmitValues();
$fileObj = $form->getElement('filename');
$manufacturerId = filter_var($ret['mnftr'], FILTER_VALIDATE_INT);
if ($manufacturerId === false) {
$tpl->assign('msg', 'Wrong manufacturer given.');
} elseif ($fileObj->isUploadedFile()) {
// Upload File
$values = $fileObj->getValue();
$msg .= str_replace("\n", '<br />', $stdout);
$msg .= '<br />Moving traps in database...';
$command = "@CENTREONTRAPD_BINDIR@/centFillTrapDB -f '" . $values['tmp_name']
. "' -m " . $manufacturerId . ' --severity=info 2>&1';
if ($debug) {
echo $command;
}
$stdout = shell_exec($command);
unlink($values['tmp_name']);
if ($stdout === null) {
$msg .= '<br />An error occured during generation.';
} else {
$msg .= '<br />' . str_replace('\n', '<br />', $stdout)
. '<br />Generate Traps configuration files from Monitoring Engine configuration form!';
}
if (strlen($msg) > $max_characters) {
$msg = substr($msg, 0, $max_characters) . '...'
. sprintf(_('Message truncated (exceeded %s characters)'), $max_characters);
}
$tpl->assign('msg', $msg);
}
}
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('formMibs.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-mibs/help.php | centreon/www/include/configuration/configObject/traps-mibs/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['vendor'] = dgettext('help', 'Choose a vendor from the list. The vendor must have been created beforehand.');
$help['filename'] = dgettext(
'help',
'Choose a local MIB file containing SNMP trap definitions to upload and import. '
. 'The file will be parsed with snmpttconvertmib.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-mibs/mibs.php | centreon/www/include/configuration/configObject/traps-mibs/mibs.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$mnftrG = $_GET['id'] ?? null;
$mnftrP = $_POST['id'] ?? null;
$id = $mnftrG ?: $mnftrP;
// Path to the configuration dir
$path = './include/configuration/configObject/traps-mibs/';
// PHP functions
require_once './include/common/common-Func.php';
switch ($o) {
case 'a':
require_once $path . 'formMibs.php';
break; // Show command execution
default:
require_once $path . 'formMibs.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-groups/listGroups.php | centreon/www/include/configuration/configObject/traps-groups/listGroups.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include './include/common/autoNumLimit.php';
$mnftr_id = null;
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchTM'] ?? $_GET['searchTM'] ?? null
);
if (isset($_POST['searchTM']) || isset($_GET['searchTM'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$searchTool = null;
if ($search) {
$searchTool = ' WHERE (traps_group_name LIKE :search )';
}
$statement = $pearDB->prepare('SELECT SQL_CALC_FOUND_ROWS * FROM traps_group ' . $searchTool
. ' ORDER BY traps_group_name LIMIT :offset, :limit');
if ($search) {
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
}
$statement->bindValue(':offset', (int) $num * (int) $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', $limit, PDO::PARAM_INT);
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Group Name'));
$tpl->assign('headerMenu_options', _('Options'));
// List of elements - Depends on different criteria
$form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
for ($i = 0; $group = $statement->fetch(PDO::FETCH_ASSOC); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $group['traps_group_id'] . ']');
$moptions = ' <input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;" '
. "maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr["
. $group['traps_group_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => myDecode($group['traps_group_name']), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&id=' . $group['traps_group_id'], 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchTM', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listGroups.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-groups/formGroups.php | centreon/www/include/configuration/configObject/traps-groups/formGroups.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
//
// # Database retrieve information for Manufacturer
//
function myDecodeGroup(?string $arg): string
{
return html_entity_decode($arg ?? '', ENT_QUOTES, 'UTF-8');
}
$group = [];
try {
if (($o === 'c' || $o === 'w') && $id) {
$sql = <<<'SQL'
SELECT traps_group_name AS name, traps_group_id AS id
FROM traps_group
WHERE traps_group_id = :id
LIMIT 1
SQL;
$params = QueryParameters::create([
QueryParameter::create('id', (int) $id, QueryParameterTypeEnum::INTEGER),
]);
$result = $pearDB->fetchAssociative($sql, $params);
if ($result !== false) {
$group = array_map('myDecodeGroup', $result);
}
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while retrieving trap group data: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while retrieving trap group data');
}
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '50'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o === 'a') {
$form->addElement('header', 'title', _('Add Group'));
} elseif ($o === 'c') {
$form->addElement('header', 'title', _('Modify Group'));
} elseif ($o === 'w') {
$form->addElement('header', 'title', _('View Group'));
}
//
// # Group information
//
$form->addElement('text', 'name', _('Name'), $attrsText);
$avRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_trap&action=list';
$deRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_trap'
. '&action=defaultValues&target=Traps&field=groups&id=' . $id;
$attrTraps = [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $avRoute,
'multiple' => true,
'linkedObject' => 'centreonTraps',
'defaultDatasetRoute' => $deRoute,
];
$form->addElement('select2', 'traps', _('Traps'), [], $attrTraps);
//
// # Further informations
//
$form->addElement('hidden', 'id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
//
// # Form Rules
//
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('name', _('Compulsory Name'), 'required');
$form->registerRule('exist', 'callback', function ($name) {
try {
return ! testTrapGroupExistence($name);
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while validating traps group uniqueness: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while validating traps group uniqueness');
return false;
}
});
$form->addRule('name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
//
// # Smarty template initialization
//
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", '
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, '
. '-300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
if ($o === 'w') {
if ($centreon->user->access->page($p) !== 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&id=' . $id . "'"]
);
}
$form->setDefaults($group);
$form->freeze();
} elseif ($o === 'c') {
$form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($group);
} elseif ($o === 'a') {
$form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if ($form->validate()) {
$trapGroupObj = $form->getElement('id');
if ($form->getSubmitValue('submitA')) {
try {
$trapGroupObj->setValue(insertTrapGroupInDB());
$valid = true;
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while inserting traps group: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while inserting traps group');
}
} elseif ($form->getSubmitValue('submitC')) {
try {
updateTrapGroupInDB($trapGroupObj->getValue());
$valid = true;
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while updating traps group: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while updating traps group');
}
}
$o = null;
}
if ($valid) {
require_once $path . 'listGroups.php';
} else {
// #Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formGroups.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-groups/help.php | centreon/www/include/configuration/configObject/traps-groups/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['name'] = dgettext('help', 'The name is used to identify the group with a short name.');
$help['traps'] = dgettext('help', 'Select traps to be grouped. Execution will be sequential.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-groups/groups.php | centreon/www/include/configuration/configObject/traps-groups/groups.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Core\Common\Domain\Exception\RepositoryException;
if (! isset($centreon)) {
exit();
}
$id = filter_var(
$_GET['id'] ?? $_POST['id'] ?? null,
FILTER_VALIDATE_INT
);
// Normalize select input
$selectInput = $_GET['select'] ?? $_POST['select'] ?? [];
if (! is_array($selectInput)) {
$selectInput = [$selectInput];
}
$select = filter_var_array($selectInput, FILTER_VALIDATE_INT) ?: [];
$select = array_filter($select, fn ($value) => $value !== false);
// Normalize dupNbr input
$dupNbrInput = $_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [];
if (! is_array($dupNbrInput)) {
$dupNbrInput = [$dupNbrInput];
}
$dupNbr = filter_var_array($dupNbrInput, FILTER_VALIDATE_INT) ?: [];
$dupNbr = array_filter($dupNbr, fn ($value) => $value !== false);
$dupNbr = array_intersect_key($dupNbr, $select);
// Path to the configuration dir
$path = './include/configuration/configObject/traps-groups/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
try {
switch ($o) {
case 'a':
require_once $path . 'formGroups.php';
break; // Add a Trap
case 'w':
require_once $path . 'formGroups.php';
break; // Watch a Trap
case 'c':
require_once $path . 'formGroups.php';
break; // Modify a Trap
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleTrapGroupInDB($select, $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroups.php';
break; // Duplicate n Traps
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteTrapGroupInDB($select);
} else {
unvalidFormMessage();
}
require_once $path . 'listGroups.php';
break; // Delete n Traps
default:
require_once $path . 'listGroups.php';
break;
}
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while processing traps groups: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while processing traps groups');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-groups/DB-Func.php | centreon/www/include/configuration/configObject/traps-groups/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
/**
* Check if a trap group name already exists in DB
*
* @param string|null $name
* @throws RepositoryException
* @return bool true if duplicate exists with different id, false if name is available or belongs to current record
*/
function testTrapGroupExistence(?string $name = null): bool
{
global $pearDB, $form;
$currentId = null;
if (isset($form)) {
$currentId = $form->getSubmitValue('id');
}
try {
$sql = <<<'SQL'
SELECT traps_group_id AS id
FROM traps_group
WHERE traps_group_name = :name
LIMIT 1
SQL;
$params = QueryParameters::create([
QueryParameter::create('name', (string) $name, QueryParameterTypeEnum::STRING),
]);
$trapGroup = $pearDB->fetchAssociative($sql, $params);
return $trapGroup !== false && ((int) $trapGroup['id'] !== (int) $currentId);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error while executing testTrapGroupExistence',
[
'name' => $name,
'currentId' => $currentId,
],
$exception,
);
}
}
/**
* Delete one or many trap groups
*
* @param array<int|string,mixed> $trapGroups Keys are trap_group_id
* @throws RepositoryException
* @return void
*/
function deleteTrapGroupInDB(array $trapGroups = []): void
{
global $pearDB, $oreon;
try {
if (! $pearDB->isTransactionActive()) {
$pearDB->startTransaction();
}
foreach (array_keys($trapGroups) as $trapGroupId) {
$selectQuery = <<<'SQL'
SELECT traps_group_name AS name
FROM traps_group
WHERE traps_group_id = :id
LIMIT 1
SQL;
$params = QueryParameters::create([
QueryParameter::create('id', (int) $trapGroupId, QueryParameterTypeEnum::INTEGER),
]);
$row = $pearDB->fetchAssociative($selectQuery, $params);
$groupName = $row['name'] ?? '';
$pearDB->delete(
<<<'SQL'
DELETE FROM traps_group
WHERE traps_group_id = :id
SQL,
$params,
);
$pearDB->delete(
<<<'SQL'
DELETE FROM traps_group_relation
WHERE traps_group_id = :id
SQL,
$params,
);
$oreon->CentreonLogAction->insertLog(
'traps_group',
$trapGroupId,
$groupName,
'd',
);
}
$pearDB->commitTransaction();
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
try {
if ($pearDB->isTransactionActive()) {
$pearDB->rollBackTransaction();
}
} catch (ConnectionException $rollbackException) {
throw new RepositoryException(
'Failed to roll back transaction in deleteTrapGroupInDB: ' . $rollbackException->getMessage(),
[
'trapGroups' => array_keys($trapGroups),
],
$rollbackException,
);
}
throw new RepositoryException(
'Error while executing deleteTrapGroupInDB',
[
'trapGroups' => array_keys($trapGroups),
],
$exception
);
}
}
/**
* Duplicate one or more trap groups $nbrDup[$id] times
*
* @param array<int|string,mixed> $trapGroups
* @param array<int|string,int> $nbrDup
* @throws RepositoryException
* @return void
*/
function multipleTrapGroupInDB(array $trapGroups = [], array $nbrDup = []): void
{
global $pearDB, $oreon;
try {
if (! $pearDB->isTransactionActive()) {
$pearDB->startTransaction();
}
foreach (array_keys($trapGroups) as $trapGroupId) {
// Fetch original row
$paramsId = QueryParameters::create([
QueryParameter::create('id', (int) $trapGroupId, QueryParameterTypeEnum::INTEGER),
]);
$originalGroup = $pearDB->fetchAssociative(
<<<'SQL'
SELECT *
FROM traps_group
WHERE traps_group_id = :id
LIMIT 1
SQL,
$paramsId
);
if (! $originalGroup) {
// nothing to duplicate for this id
continue;
}
$baseName = $originalGroup['traps_group_name'];
$dupCount = (int) ($nbrDup[$trapGroupId] ?? 0);
$parameters = [];
$valuePlaceholders = [];
$insertLogsInfo = [];
for ($i = 1; $i <= $dupCount; $i++) {
$newName = $baseName . '_' . $i;
if (testTrapGroupExistence($newName)) {
continue;
}
$paramName = 'name_' . $i;
$parameters[] = QueryParameter::create(
$paramName,
$newName,
QueryParameterTypeEnum::STRING,
);
$valuePlaceholders[] = '(:' . $paramName . ')';
$insertLogsInfo[] = [$trapGroupId, $newName];
}
if ($parameters === []) {
continue;
}
$insertSql = sprintf(
'INSERT INTO traps_group (traps_group_name) VALUES %s',
implode(', ', $valuePlaceholders),
);
$pearDB->insert($insertSql, QueryParameters::create($parameters));
$firstInsertedId = (int) $pearDB->getLastInsertId();
$totalInserted = count($parameters);
$newIds = range($firstInsertedId, $firstInsertedId + $totalInserted - 1);
// Map new IDs to their names
$newGroups = [];
foreach ($parameters as $index => $param) {
$newGroups[$newIds[$index]] = $param->getValue();
}
// Copy relations
foreach ($newGroups as $newGroupId => $newName) {
$copyParams = QueryParameters::create([
QueryParameter::create('new_group_id', $newGroupId, QueryParameterTypeEnum::INTEGER),
QueryParameter::create('old_group_id', (int) $trapGroupId, QueryParameterTypeEnum::INTEGER),
]);
$pearDB->insert(
<<<'SQL'
INSERT INTO traps_group_relation (traps_group_id, traps_id)
SELECT :new_group_id, traps_id
FROM traps_group_relation
WHERE traps_group_id = :old_group_id
SQL,
$copyParams,
);
}
// Log insertions after successful creation
foreach ($newGroups as $newGroupId => $newName) {
$oreon->CentreonLogAction->insertLog(
'traps_group',
$newGroupId,
$newName,
'a',
[
'traps_group_name' => $newName,
'name' => $newName,
]
);
}
}
$pearDB->commitTransaction();
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
try {
if ($pearDB->isTransactionActive()) {
$pearDB->rollBackTransaction();
}
} catch (ConnectionException $rollbackException) {
throw new RepositoryException(
'Failed to roll back transaction in multipleTrapGroupInDB: ' . $rollbackException->getMessage(),
[
'trapGroups' => array_keys($trapGroups),
'nbrDup' => $nbrDup,
],
$rollbackException,
);
}
throw new RepositoryException(
'Error while executing multipleTrapGroupInDB',
[
'trapGroups' => array_keys($trapGroups),
'nbrDup' => $nbrDup,
],
$exception,
);
}
}
/**
* Public wrapper kept for BC.
*
* @param int|null $id
* @throws RepositoryException
* @return void
*/
function updateTrapGroupInDB(?int $id = null): void
{
if ($id === null) {
return;
}
updateTrapGroup($id);
}
/**
* Update trap group main data + its relations.
*
* @param int|null $id
* @throws RepositoryException
* @return void
*/
function updateTrapGroup(?int $id = null): void
{
global $form, $pearDB, $oreon;
if ($id === null) {
return;
}
$ret = $form->getSubmitValues();
$name = $ret['name'] ?? '';
if ($name === '') {
throw new RepositoryException(
'Trap group name cannot be empty',
['ret' => $ret],
);
}
try {
$updateParams = QueryParameters::create([
QueryParameter::create('name', $name, QueryParameterTypeEnum::STRING),
QueryParameter::create('id', (int) $id, QueryParameterTypeEnum::INTEGER),
]);
if (! $pearDB->isTransactionActive()) {
$pearDB->startTransaction();
}
$pearDB->update(
<<<'SQL'
UPDATE traps_group
SET traps_group_name = :name
WHERE traps_group_id = :id
SQL,
$updateParams,
);
$deleteRelParams = QueryParameters::create([
QueryParameter::create('id', (int) $id, QueryParameterTypeEnum::INTEGER),
]);
$pearDB->delete(
<<<'SQL'
DELETE FROM traps_group_relation
WHERE traps_group_id = :id
SQL,
$deleteRelParams,
);
if (! empty($ret['traps']) && is_array($ret['traps'])) {
foreach ($ret['traps'] as $trapId) {
$relParams = QueryParameters::create([
QueryParameter::create('group_id', (int) $id, QueryParameterTypeEnum::INTEGER),
QueryParameter::create('trap_id', (int) $trapId, QueryParameterTypeEnum::INTEGER),
]);
$pearDB->insert(
<<<'SQL'
INSERT INTO traps_group_relation (traps_group_id, traps_id)
VALUES (:group_id, :trap_id)
SQL,
$relParams,
);
}
}
$fields = CentreonLogAction::prepareChanges($ret);
$oreon->CentreonLogAction->insertLog(
'traps_group',
$id,
$fields['name'],
'c',
$fields,
);
$pearDB->commitTransaction();
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
try {
if ($pearDB->isTransactionActive()) {
$pearDB->rollBackTransaction();
}
} catch (ConnectionException $rollbackException) {
throw new RepositoryException(
'Failed to roll back transaction in updateTrapGroup: ' . $rollbackException->getMessage(),
[
'id' => $id,
'name' => $name,
],
$rollbackException,
);
}
throw new RepositoryException(
'Error while executing updateTrapGroup',
[
'id' => $id,
'name' => $name,
],
$exception,
);
}
}
/**
* Public wrapper kept for BC with legacy calls.
*
* @param array<string,mixed> $ret
* @throws RepositoryException
* @return int|null
*/
function insertTrapGroupInDB(array $ret = []): ?int
{
return insertTrapGroup($ret);
}
/**
* Insert a new trap group and its relations.
*
* @param array<string,mixed> $ret
* @throws RepositoryException
* @return int|null Newly created traps_group_id or null if failed
*/
function insertTrapGroup(array $ret = []): ?int
{
global $form, $pearDB, $oreon;
if ($ret === []) {
$ret = $form->getSubmitValues();
}
$name = $ret['name'] ?? '';
if ($name === '') {
throw new RepositoryException(
'Trap group name cannot be empty',
['ret' => $ret],
);
}
try {
if (! $pearDB->isTransactionActive()) {
$pearDB->startTransaction();
}
$pearDB->insert(
<<<'SQL'
INSERT INTO traps_group (traps_group_name)
VALUES (:name)
SQL,
QueryParameters::create([
QueryParameter::create('name', $name, QueryParameterTypeEnum::STRING),
])
);
$newGroupId = (int) $pearDB->getLastInsertId();
if (! empty($ret['traps']) && is_array($ret['traps'])) {
foreach ($ret['traps'] as $trapId) {
$relParams = QueryParameters::create([
QueryParameter::create('group_id', $newGroupId, QueryParameterTypeEnum::INTEGER),
QueryParameter::create('trap_id', (int) $trapId, QueryParameterTypeEnum::INTEGER),
]);
$pearDB->insert(
<<<'SQL'
INSERT INTO traps_group_relation (traps_group_id, traps_id)
VALUES (:group_id, :trap_id)
SQL,
$relParams
);
}
}
$fields = CentreonLogAction::prepareChanges($ret);
$oreon->CentreonLogAction->insertLog(
'traps_group',
$newGroupId,
$fields['name'],
'a',
$fields
);
$pearDB->commitTransaction();
return $newGroupId;
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
try {
if ($pearDB->isTransactionActive()) {
$pearDB->rollBackTransaction();
}
} catch (ConnectionException $rollbackException) {
throw new RepositoryException(
'Failed to roll back transaction in insertTrapGroup: ' . $rollbackException->getMessage(),
[
'name' => $name,
],
$rollbackException,
);
}
throw new RepositoryException(
'Error while executing insertTrapGroup',
[
'name' => $name,
],
$exception
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-manufacturer/formMnftr.php | centreon/www/include/configuration/configObject/traps-manufacturer/formMnftr.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
//
// # Database retrieve information for Manufacturer
//
function myDecodeMnftr($arg)
{
return html_entity_decode($arg ?? '', ENT_QUOTES, 'UTF-8');
}
$mnftr = [];
if (($o === 'c' || $o === 'w') && $id) {
$statement = $pearDB->prepare('SELECT * FROM traps_vendor WHERE id = :id LIMIT 1');
// Set base value
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
$mnftr = array_map('myDecodeMnftr', $statement->fetchRow());
$statement->closeCursor();
}
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '50'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add Vendor'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify Vendor'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View Vendor'));
}
//
// # Manufacturer information
//
$form->addElement('text', 'name', _('Vendor Name'), $attrsText);
$form->addElement('text', 'alias', _('Alias'), $attrsText);
$form->addElement('textarea', 'description', _('Description'), $attrsTextarea);
//
// # Further informations
//
$form->addElement('hidden', 'id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
//
// # Form Rules
//
function myReplace()
{
global $form;
return str_replace(' ', '_', $form->getSubmitValue('name'));
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('name', 'myReplace');
$form->addRule('name', _('Compulsory Name'), 'required');
$form->addRule('alias', _('Compulsory Name'), 'required');
$form->registerRule('exist', 'callback', 'testMnftrExistence');
$form->addRule('name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
//
// #End of form definition
//
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate(__DIR__);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", '
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, -300, '
. 'SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
// Just watch a Command information
if ($o == 'w') {
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&id=' . $id . "'"]
);
}
$form->setDefaults($mnftr);
$form->freeze();
} // Modify a Command information
elseif ($o == 'c') {
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($mnftr);
} // Add a Command information
elseif ($o == 'a') {
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if ($form->validate()) {
$mnftrObj = $form->getElement('id');
if ($form->getSubmitValue('submitA')) {
$mnftrObj->setValue(insertMnftrInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateMnftrInDB($mnftrObj->getValue());
}
$o = null;
$valid = true;
}
if ($valid) {
require_once __DIR__ . '/listMnftr.php';
} else {
// #Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formMnftr.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-manufacturer/listMnftr.php | centreon/www/include/configuration/configObject/traps-manufacturer/listMnftr.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
$mnftr_id = null;
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchTM'] ?? $_GET['searchTM'] ?? null
);
if (isset($_POST['searchTM']) || isset($_GET['searchTM'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$searchTool = '';
if ($search) {
$searchTool .= ' WHERE (alias LIKE :search) OR (name LIKE :search) ';
}
// List of elements - Depends on different criteria
$statement = $pearDB->prepare(
'SELECT SQL_CALC_FOUND_ROWS * FROM traps_vendor ' . $searchTool
. 'ORDER BY name, alias LIMIT ' . $num * $limit . ', ' . $limit
);
if (! empty($searchTool)) {
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
}
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate(__DIR__);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Vendor Name'));
$tpl->assign('headerMenu_alias', _('Alias'));
$tpl->assign('headerMenu_options', _('Options'));
$form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
for ($i = 0; $mnftr = $statement->fetch(); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $mnftr['id'] . ']');
$moptions = ' <input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;" '
. "maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $mnftr['id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure(myDecode($mnftr['name'])), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&id=' . $mnftr['id'], 'RowMenu_alias' => CentreonUtils::escapeSecure(myDecode($mnftr['alias'])), 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchTM', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listMnftr.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-manufacturer/help.php | centreon/www/include/configuration/configObject/traps-manufacturer/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['alias'] = dgettext('help', 'The alias is a longer name or description for the vendor/manufacturer.');
$help['name'] = dgettext('help', 'The name is used to identify the vendor/manufacturer with a short name.');
$help['description'] = dgettext(
'help',
'Use this for an optional description or comments about the vendor/manufacturer.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-manufacturer/mnftr.php | centreon/www/include/configuration/configObject/traps-manufacturer/mnftr.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$id = filter_var(
$_GET['id'] ?? $_POST['id'] ?? null,
FILTER_VALIDATE_INT
) ?: null;
$select = filter_var_array(
$_GET['select'] ?? $_POST['select'] ?? [],
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
$_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [],
FILTER_VALIDATE_INT
);
// PHP functions
require_once __DIR__ . '/DB-Func.php';
require_once './include/common/common-Func.php';
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
switch ($o) {
case 'a':
require_once __DIR__ . '/formMnftr.php';
break; // Add a Trap
case 'w':
require_once __DIR__ . '/formMnftr.php';
break; // Watch a Trap
case 'c':
require_once __DIR__ . '/formMnftr.php';
break; // Modify a Trap
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleMnftrInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listMnftr.php';
break; // Duplicate n Traps
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteMnftrInDB($select ?? []);
} else {
unvalidFormMessage();
}
require_once __DIR__ . '/listMnftr.php';
break; // Delete n Traps
default:
require_once __DIR__ . '/listMnftr.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps-manufacturer/DB-Func.php | centreon/www/include/configuration/configObject/traps-manufacturer/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
function testMnftrExistence($name = null)
{
global $pearDB;
global $form;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('id');
}
$query = "SELECT name, id FROM traps_vendor WHERE name = '" . htmlentities($name, ENT_QUOTES, 'UTF-8') . "'";
$dbResult = $pearDB->query($query);
$mnftr = $dbResult->fetch();
// Modif case
if ($dbResult->rowCount() >= 1 && $mnftr['id'] == $id) {
return true;
} // Duplicate entry
return ! ($dbResult->rowCount() >= 1 && $mnftr['id'] != $id);
}
function deleteMnftrInDB($mnftr = [])
{
global $pearDB, $oreon;
foreach ($mnftr as $key => $value) {
$dbResult2 = $pearDB->query("SELECT name FROM `traps_vendor` WHERE `id` = '" . $key . "' LIMIT 1");
$row = $dbResult2->fetch();
$pearDB->query("DELETE FROM traps_vendor WHERE id = '" . htmlentities($key, ENT_QUOTES, 'UTF-8') . "'");
$oreon->CentreonLogAction->insertLog('manufacturer', $key, $row['name'], 'd');
}
}
function multipleMnftrInDB($mnftr = [], $nbrDup = [])
{
foreach ($mnftr as $key => $value) {
global $pearDB, $oreon;
$query = "SELECT * FROM traps_vendor WHERE id = '" . htmlentities($key, ENT_QUOTES, 'UTF-8') . "' LIMIT 1";
$dbResult = $pearDB->query($query);
$row = $dbResult->fetch();
$row['id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
$name = '';
if ($key2 == 'name') {
$name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$val
? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL');
if ($key2 != 'id') {
$fields[$key2] = $value2;
}
$fields['name'] = $name;
}
if (testMnftrExistence($name)) {
$rq = $val ? 'INSERT INTO traps_vendor VALUES (' . $val . ')' : null;
$pearDB->query($rq);
$oreon->CentreonLogAction->insertLog(
'manufacturer',
htmlentities($key, ENT_QUOTES, 'UTF-8'),
$name,
'a',
$fields
);
}
}
}
}
function updateMnftrInDB($id = null)
{
if (! $id) {
return;
}
updateMnftr($id);
}
function updateMnftr($id = null)
{
global $form, $pearDB, $oreon;
if (! $id) {
return;
}
$ret = [];
$ret = $form->getSubmitValues();
$rq = 'UPDATE traps_vendor ';
$rq .= "SET name = '" . htmlentities($ret['name'], ENT_QUOTES, 'UTF-8') . "', ";
$rq .= "alias = '" . htmlentities($ret['alias'], ENT_QUOTES, 'UTF-8') . "', ";
$rq .= "description = '" . htmlentities($ret['description'], ENT_QUOTES, 'UTF-8') . "' ";
$rq .= "WHERE id = '" . $id . "'";
$dbResult = $pearDB->query($rq);
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$oreon->CentreonLogAction->insertLog('manufacturer', $id, $fields['name'], 'c', $fields);
}
function insertMnftrInDB($ret = [])
{
return insertMnftr($ret);
}
function insertMnftr($ret = [])
{
global $form, $pearDB, $oreon;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$rq = 'INSERT INTO traps_vendor ';
$rq .= '(name, alias, description) ';
$rq .= 'VALUES ';
$rq .= "('" . htmlentities($ret['name'], ENT_QUOTES, 'UTF-8') . "', ";
$rq .= "'" . htmlentities($ret['alias'], ENT_QUOTES, 'UTF-8') . "', ";
$rq .= "'" . htmlentities($ret['description'], ENT_QUOTES, 'UTF-8') . "')";
$dbResult = $pearDB->query($rq);
$dbResult = $pearDB->query('SELECT MAX(id) FROM traps_vendor');
$mnftr_id = $dbResult->fetch();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$oreon->CentreonLogAction->insertLog('manufacturer', $mnftr_id['MAX(id)'], $fields['name'], 'a', $fields);
return $mnftr_id['MAX(id)'];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/meta_service/listMetaService.php | centreon/www/include/configuration/configObject/meta_service/listMetaService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchMS'] ?? $_GET['searchMS'] ?? null
);
if (isset($_POST['searchMS']) || isset($_GET['searchMS'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
// Meta Service list
$rq = 'SELECT SQL_CALC_FOUND_ROWS * FROM meta_service ';
if ($search) {
$rq .= "WHERE meta_name LIKE '%" . $search . "%' "
. $acl->queryBuilder('AND', 'meta_id', $metaStr);
} else {
$rq .= $acl->queryBuilder('WHERE', 'meta_id', $metaStr);
}
$rq .= ' ORDER BY meta_name LIMIT ' . $num * $limit . ', ' . $limit;
$dbResult = $pearDB->query($rq);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_type', _('Calculation Type'));
$tpl->assign('headerMenu_levelw', _('Warning Level'));
$tpl->assign('headerMenu_levelc', _('Critical Level'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
$calcType = ['AVE' => _('Average'), 'SOM' => _('Sum'), 'MIN' => _('Min'), 'MAX' => _('Max')];
// Meta Service list
$conditionStr = '';
$metaStrParams = [];
// binding query params for non admin acl rules
$searchIsNull = $search === null || $search === '';
// the metaStr are the metas linked to the user's ACL
if ($acl->admin === '0' || $acl->admin === false) {
if ($metaStr === "''" || $metaStr === '') {
$queryParams = '0';
} else {
$metaStrList = explode(',', $metaStr);
foreach ($metaStrList as $index => $metaId) {
$metaStrParams[':meta_' . $index] = (int) str_replace("'", '', $metaId);
}
$queryParams = implode(',', array_keys($metaStrParams));
}
$conditionStr = ! $searchIsNull ? 'AND meta_id IN (' . $queryParams . ')' : 'WHERE meta_id IN (' . $queryParams . ')';
}
if (! $searchIsNull) {
$statement = $pearDB->prepare('SELECT * FROM meta_service '
. 'WHERE meta_name LIKE :search ' . $conditionStr
. ' ORDER BY meta_name LIMIT :offset, :limit');
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
} else {
$statement = $pearDB->prepare('SELECT * FROM meta_service ' . $conditionStr
. ' ORDER BY meta_name LIMIT :offset, :limit');
}
foreach ($metaStrParams as $key => $metaId) {
$statement->bindValue($key, $metaId, PDO::PARAM_INT);
}
$statement->bindValue(':offset', (int) $num * (int) $limit, PDO::PARAM_INT);
$statement->bindValue(':limit', $limit, PDO::PARAM_INT);
$statement->execute();
$form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
for ($i = 0; $ms = $statement->fetch(PDO::FETCH_ASSOC); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $ms['meta_id'] . ']');
if ($ms['meta_select_mode'] == 1) {
$moptions = "<a href='main.php?p=" . $p . '&meta_id=' . $ms['meta_id'] . '&o=ci&search='
. $search . "'><img src='img/icons/redirect.png' class='ico-16' border='0' alt='"
. _('View') . "'></a> ";
} else {
$moptions = '';
}
if ($ms['meta_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&meta_id=' . $ms['meta_id'] . '&o=u&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Disabled') . "'></a> ";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&meta_id=' . $ms['meta_id'] . '&o=s&limit=' . $limit
. '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' "
. "border='0' alt='" . _('Enabled') . "'></a> ";
}
$moptions .= ' ';
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) '
. "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" "
. "name='dupNbr[" . $ms['meta_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure($ms['meta_name']), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&meta_id=' . $ms['meta_id'], 'RowMenu_type' => CentreonUtils::escapeSecure($calcType[$ms['calcul_type']]), 'RowMenu_levelw' => isset($ms['warning']) && $ms['warning'] ? $ms['warning'] : '-', 'RowMenu_levelc' => isset($ms['critical']) && $ms['critical'] ? $ms['critical'] : '-', 'RowMenu_status' => $ms['meta_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $ms['meta_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchMS', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listMetaService.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/meta_service/metric.php | centreon/www/include/configuration/configObject/meta_service/metric.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
// Database retrieve information
require_once './class/centreonDB.class.php';
$pearDBO = new CentreonDB('centstorage');
$metric = [];
if (($o == 'cs') && $msr_id) {
// Set base value
$DBRESULT = $pearDB->prepare('SELECT * FROM meta_service_relation WHERE msr_id = :msr_id');
$DBRESULT->bindValue(':msr_id', $msr_id, PDO::PARAM_INT);
$DBRESULT->execute();
// Set base value
$metric1 = array_map('myDecode', $DBRESULT->fetchRow());
if ($host_id === false || $metric1['host_id'] == $host_id) {
$DBRESULT = $pearDBO->prepare(
'SELECT * FROM metrics, index_data
WHERE metric_id = :metric_id and metrics.index_id = index_data.id'
);
$DBRESULT->bindValue(':metric_id', $metric1['metric_id'], PDO::PARAM_INT);
$DBRESULT->execute();
$metric2 = array_map('myDecode', $DBRESULT->fetchRow());
$metric = array_merge($metric1, $metric2);
$host_id = (int) $metric1['host_id'];
$metric['metric_sel'][0] = getMyServiceID($metric['service_description'], $metric['host_id']);
$metric['metric_sel'][1] = $metric['metric_id'];
}
}
//
// # Database retrieve information for differents elements list we need on the page
//
// Host comes from DB -> Store in $hosts Array
$hosts
= [null => null] + $acl->getHostAclConf(
null,
'broker',
['fields' => ['host.host_id', 'host.host_name'], 'keys' => ['host_id'], 'get_row' => 'host_name', 'order' => ['host.host_name']]
);
$services1 = [null => null];
$services2 = [null => null];
if ($host_id !== false) {
$services
= [null => null] + $acl->getHostServiceAclConf(
$host_id,
'broker',
['fields' => ['s.service_id', 's.service_description'], 'keys' => ['service_id'], 'get_row' => 'service_description', 'order' => ['service_description']]
);
foreach ($services as $key => $value) {
$DBRESULT = $pearDBO->query("SELECT DISTINCT metric_name, metric_id, unit_name
FROM metrics m, index_data i
WHERE i.host_name = '" . $pearDBO->escape(getMyHostName($host_id)) . "'
AND i.service_description = '" . $pearDBO->escape($value) . "'
AND i.id = m.index_id
ORDER BY metric_name, unit_name");
while ($metricSV = $DBRESULT->fetchRow()) {
$services1[$key] = $value;
$metricSV['metric_name'] = str_replace('#S#', '/', $metricSV['metric_name']);
$metricSV['metric_name'] = str_replace('#BS#', '\\', $metricSV['metric_name']);
$services2[$key][$metricSV['metric_id']] = $metricSV['metric_name'] . ' (' . $metricSV['unit_name'] . ')';
}
}
$DBRESULT->closeCursor();
}
$debug = 0;
$attrsTextI = ['size' => '3'];
$attrsText = ['size' => '30'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == 'as') {
$form->addElement('header', 'title', _('Add a Meta Service indicator'));
} elseif ($o == 'cs') {
$form->addElement('header', 'title', _('Modify a Meta Service indicator'));
}
// Indicator basic information
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$formMsrId = $form->addElement('hidden', 'msr_id');
$formMsrId->setValue($msr_id);
$formMetaId = $form->addElement('hidden', 'meta_id');
$formMetaId->setValue($meta_id);
$formMetricId = $form->addElement('hidden', 'metric_id');
$formMetricId->setValue($metric_id);
$hn = $form->addElement('select', 'host_id', _('Host'), $hosts, ['onChange' => 'this.form.submit()']);
$sel = $form->addElement('hierselect', 'metric_sel', _('Service'));
$sel->setOptions([$services1, $services2]);
$tab = [];
$tab[] = $form->createElement('radio', 'activate', null, _('Enabled'), '1');
$tab[] = $form->createElement('radio', 'activate', null, _('Disabled'), '0');
$form->addGroup($tab, 'activate', _('Status'), ' ');
$form->setDefaults(['activate' => '1']);
$form->addElement('textarea', 'msr_comment', _('Comments'), $attrsTextarea);
$form->addRule('host_id', _('Compulsory Field'), 'required');
function checkMetric()
{
global $form;
$tab = $form->getSubmitValue('metric_sel');
if (isset($tab[0]) & isset($tab[1])) {
return 1;
}
return 0;
}
$form->registerRule('checkMetric', 'callback', 'checkMetric');
$form->addRule('metric_sel', _('Compulsory Field'), 'checkMetric');
// Just watch
if ($o == 'cs') {
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($metric);
} elseif ($o == 'as') {
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if (
((isset($_POST['submitA']) && $_POST['submitA']) || (isset($_POST['submitC']) && $_POST['submitC']))
&& $form->validate()
) {
$msrObj = $form->getElement('msr_id');
if ($form->getSubmitValue('submitA')) {
$msrObj->setValue(insertMetric($meta_id));
} elseif ($form->getSubmitValue('submitC')) {
updateMetric($msrObj->getValue());
}
$valid = true;
}
if ($valid) {
require_once $path . 'listMetric.php';
} else {
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign('valid', $valid);
$tpl->display('metric.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/meta_service/help.php | centreon/www/include/configuration/configObject/meta_service/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['name'] = dgettext('help', 'Name used for identification of this meta service.');
$help['display'] = dgettext(
'help',
"Optional format string used for displaying the status of this meta service. The variable '%d' may be "
. 'used and will be replaced by the calculated value.'
);
$help['warning'] = dgettext('help', 'Absolute value for warning level (low threshold).');
$help['critical'] = dgettext('help', 'Absolute value for critical level (low threshold).');
$help['calcul_type'] = dgettext('help', 'Function to be applied to calculate the meta service status.');
$help['data_source_type'] = dgettext('help', 'Data source type of the meta service.');
$help['select_mode'] = dgettext(
'help',
'Selection mode for services to be considered for this meta service. In service list mode, mark selected '
. 'services in the options on meta service list. In SQL matching mode, specify a search string to '
. 'be used in an SQL query.'
);
$help['regexp'] = dgettext('help', 'Search string to be used in a SQL LIKE query for service selection.');
$help['metric'] = dgettext('help', 'Select the metric to measure for meta service status.');
$help['check_period'] = dgettext('help', 'Specify the time period during which the meta service status is measured.');
$help['max_check_attempts'] = dgettext(
'help',
'Define the number of times that Centreon will retry the service check command if it returns any state other '
. 'than an OK state. Setting this value to 1 will cause Centreon to generate an alert without '
. 'retrying the service check again.'
);
$help['check_interval'] = dgettext(
'help',
'Define the number of minutes between regularly scheduled checks of the meta service. "Regular" checks are '
. 'those that occur when the service is in an OK state or when the service is in a non-OK state, '
. 'but has already been rechecked max check attempts number of times.'
);
$help['retry_interval'] = dgettext(
'help',
'Define the number of minutes to wait before scheduling a re-check for this service after a non-OK '
. 'state was detected. Once the service has been retried max check attempts times without a change in its status, '
. 'it will revert to being scheduled at its "normal" check interval rate.'
);
if (! isCloudPlatform()) {
$help['notifications_enabled'] = dgettext(
'help',
'Specify whether or not notifications for this meta service are enabled.'
);
$help['contact_groups'] = dgettext(
'help',
'This is a list of contact groups that should be notified whenever there are '
. 'problems (or recoveries) with this service.'
);
$help['notification_interval'] = dgettext(
'help',
'Define the number of minutes to wait before re-notifying a contact that this service is still in a '
. 'non-OK condition. A value of 0 disables re-notifications of contacts about problems for this service - '
. 'only one problem notification will be sent out.'
);
$help['notification_period'] = dgettext(
'help',
'Specify the time period during which notifications of events for this service can be sent out to contacts. '
. 'If a state change occurs during a time which is not covered by the time period, no notifications will be sent out.'
);
$help['notification_options'] = dgettext(
'help',
'Define the states of the service for which notifications should be sent out. If you do not specify any '
. 'notification options, Centreon will assume that you want notifications to be sent out for all possible states.'
);
}
$help['graph_template'] = dgettext(
'help',
'The optional definition of a graph template will be used as default graph template for this service.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/meta_service/listMetric.php | centreon/www/include/configuration/configObject/meta_service/listMetric.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$calcType = ['AVE' => _('Average'), 'SOM' => _('Sum'), 'MIN' => _('Min'), 'MAX' => _('Max')];
if (! isset($oreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
require_once './class/centreonDB.class.php';
$pearDBO = new CentreonDB('centstorage');
$DBRESULT = $pearDB->prepare('SELECT * FROM meta_service WHERE meta_id = :meta_id');
$DBRESULT->bindValue(':meta_id', $meta_id, PDO::PARAM_INT);
$DBRESULT->execute();
$meta = $DBRESULT->fetchRow();
$tpl->assign('meta', ['meta' => _('Meta Service'), 'name' => $meta['meta_name'], 'calc_type' => $calcType[$meta['calcul_type']]]);
$DBRESULT->closeCursor();
// start header menu
$tpl->assign('headerMenu_host', _('Host'));
$tpl->assign('headerMenu_service', _('Services'));
$tpl->assign('headerMenu_metric', _('Metrics'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
$aclFrom = '';
$aclCond = '';
if (! $oreon->user->admin) {
$aclFrom = ", `{$aclDbName}`.centreon_acl acl ";
$aclCond = ' AND acl.host_id = msr.host_id
AND acl.group_id IN (' . $acl->getAccessGroupsString() . ') ';
}
$statement = $pearDB->prepare(
"SELECT DISTINCT msr.*
FROM `meta_service_relation` msr {$aclFrom}
WHERE msr.meta_id = :meta_id
{$aclCond}
ORDER BY host_id"
);
$statement->bindValue(':meta_id', $meta_id, PDO::PARAM_INT);
$statement->execute();
$ar_relations = [];
$form = new HTML_QuickFormCustom('Form', 'POST', '?p=' . $p);
// Construct request
$metrics = [];
while ($row = $statement->fetchRow()) {
$ar_relations[$row['metric_id']][] = ['activate' => $row['activate'], 'msr_id' => $row['msr_id']];
$metrics[] = $row['metric_id'];
}
$in_statement = implode(',', $metrics);
if ($in_statement != '') {
$query = 'SELECT * FROM metrics m, index_data i '
. "WHERE m.metric_id IN ({$in_statement}) "
. 'AND m.index_id=i.id ORDER BY i.host_name, i.service_description, m.metric_name';
$DBRESULTO = $pearDBO->query($query);
// Different style between each lines
$style = 'one';
// Fill a tab with a mutlidimensionnal Array we put in $tpl
$elemArr1 = [];
$i = 0;
$centreonToken = createCSRFToken();
while ($metric = $DBRESULTO->fetchRow()) {
foreach ($ar_relations[$metric['metric_id']] as $relation) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $relation['msr_id'] . ']');
if ($relation['activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&msr_id=' . $relation['msr_id']
. '&o=us&meta_id=' . $meta_id . '&metric_id=' . $metric['metric_id']
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Disabled') . "'></a> ";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&msr_id=' . $relation['msr_id']
. '&o=ss&meta_id=' . $meta_id . '&metric_id=' . $metric['metric_id']
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Enabled') . "'></a> ";
}
$metric['service_description'] = str_replace('#S#', '/', $metric['service_description']);
$metric['service_description'] = str_replace('#BS#', '\\', $metric['service_description']);
$elemArr1[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_host' => htmlentities($metric['host_name'], ENT_QUOTES, 'UTF-8'), 'RowMenu_link' => 'main.php?p=' . $p . '&o=cs&msr_id=' . $relation['msr_id'], 'RowMenu_service' => htmlentities($metric['service_description'], ENT_QUOTES, 'UTF-8'), 'RowMenu_metric' => CentreonUtils::escapeSecure($metric['metric_name'] . ' (' . $metric['unit_name'] . ')'), 'RowMenu_status' => $relation['activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $relation['activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
$i++;
}
}
}
if (isset($elemArr1)) {
$tpl->assign('elemArr1', $elemArr1);
} else {
$tpl->assign('elemArr1', []);
}
// Different messages we put in the template
$tpl->assign('msg', ['addL1' => 'main.php?p=' . $p . '&o=as&meta_id=' . $meta_id, 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]);
// Element we need when we reload the page
$form->addElement('hidden', 'p');
$form->addElement('hidden', 'meta_id');
$tab = ['p' => $p, 'meta_id' => $meta_id];
$form->setDefaults($tab);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</SCRIPT>
<?php
$attrs1 = ['onchange' => 'javascript: '
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('" . _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "];
$form->addElement('select', 'o1', null, [null => _('More actions...'), 'ds' => _('Delete')], $attrs1);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('" . _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "];
$form->addElement('select', 'o2', null, [null => _('More actions...'), 'ds' => _('Delete')], $attrs2);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listMetric.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/meta_service/metaService.php | centreon/www/include/configuration/configObject/meta_service/metaService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
if (isset($_POST['o']) && $_POST['o']) {
$o = $_POST['o'];
}
// Path to the configuration dir
$path = './include/configuration/configObject/meta_service/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
$meta_id = filter_var(
$_GET['meta_id'] ?? $_POST['meta_id'] ?? null,
FILTER_VALIDATE_INT
);
$host_id = filter_var(
$_GET['host_id'] ?? $_POST['host_id'] ?? null,
FILTER_VALIDATE_INT
);
$metric_id = filter_var(
$_GET['metric_id'] ?? $_POST['metric_id'] ?? null,
FILTER_VALIDATE_INT
);
$msr_id = filter_var(
$_GET['msr_id'] ?? $_POST['msr_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = new CentreonACL($oreon->user->get_id(), $oreon->user->admin);
$aclDbName = $acl->getNameDBAcl();
$metaStr = $acl->getMetaServiceString();
if (! $oreon->user->admin && $meta_id && ! str_contains($metaStr, "'" . $meta_id . "'")) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this meta service'));
return null;
}
switch ($o) {
case 'a': // Add an Meta Service
case 'w': // Watch an Meta Service
case 'c': // Modify an Meta Service
require_once $path . 'formMetaService.php';
break;
case 's': // Activate a Meta Service
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableMetaServiceInDB($meta_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetaService.php';
break;
case 'u': // Desactivate a Meta Service
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableMetaServiceInDB($meta_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetaService.php';
break;
case 'd': // Delete n Meta Servive
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteMetaServiceInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetaService.php';
break;
case 'm': // Duplicate n Meta Service
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleMetaServiceInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
// Update ACL and meta service string for the next listing
$acl = new CentreonACL($centreon->user->get_id(), $centreon->user->admin === '1');
$aclDbName = $acl->getNameDBAcl();
$metaStr = $acl->getMetaServiceString();
} else {
unvalidFormMessage();
}
require_once $path . 'listMetaService.php';
break;
case 'ci': // Manage Service of the MS
require_once $path . 'listMetric.php';
break;
case 'as': // Add Service to a MS
require_once $path . 'metric.php';
break;
case 'cs': // Change Service to a MS
require_once $path . 'metric.php';
break;
case 'ss': // Activate a Metric
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableMetricInDB($msr_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetric.php';
break;
case 'us': // Desactivate a Metric
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableMetricInDB($msr_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetric.php';
break;
case 'ws': // View Service to a MS
require_once $path . 'metric.php';
break;
case 'ds': // Delete n Metric
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteMetricInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetric.php';
break;
default:
require_once $path . 'listMetaService.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/meta_service/DB-Func.php | centreon/www/include/configuration/configObject/meta_service/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonMeta.class.php';
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\ValueObjectException;
/**
* Check if a meta service exists for a given name
*
* @param string|null $name
* @return bool
*/
function testExistence($name = null)
{
global $pearDB, $form;
$metaIdFromForm = $form ? $form->getSubmitValue('meta_id') : null;
$qb = $pearDB->createQueryBuilder();
$query = $qb->select('meta_id')
->from('meta_service')
->where('meta_name = :meta_name')
->getQuery();
try {
$meta = $pearDB->fetchAssociative($query, QueryParameters::create([
QueryParameter::string('meta_name', getParamValue($name, sanitize: true)),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while executing testExistence',
[
'metaName' => $name,
],
$exception
);
$meta = false;
}
if ($meta && isset($meta['meta_id'])) {
return $meta['meta_id'] == $metaIdFromForm;
}
return true;
}
/**
* Enable a meta service in the DB
*
* @param int|null $metaId
* @return void
*/
function enableMetaServiceInDB($metaId = null)
{
if (! $metaId) {
return;
}
global $pearDB;
$qb = $pearDB->createQueryBuilder();
$query = $qb->update('meta_service')
->set('meta_activate', "'1'")
->where('meta_id = :meta_id')
->getQuery();
try {
$pearDB->update($query, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while enabling meta_service',
[
'metaId' => $metaId,
],
$exception
);
}
}
/**
* Disable a meta service in the DB
*
* @param int|null $metaId
* @return void
*/
function disableMetaServiceInDB($metaId = null)
{
if (! $metaId) {
return;
}
global $pearDB;
$qb = $pearDB->createQueryBuilder();
$query = $qb->update('meta_service')
->set('meta_activate', "'0'")
->where('meta_id = :meta_id')
->getQuery();
try {
$pearDB->update($query, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while disabling meta_service',
[
'metaId' => $metaId,
],
$exception
);
}
}
/**
* Remove dependency relation if it is the last one
*
* @param int $serviceId
* @return void
*/
function removeRelationLastMetaServiceDependency(int $serviceId): void
{
global $pearDB;
$subQb = $pearDB->createQueryBuilder();
$subQuery = $subQb->select('dependency_dep_id')
->from('dependency_metaserviceParent_relation')
->where('meta_service_meta_id = :serviceId')
->getQuery();
$qb = $pearDB->createQueryBuilder();
$query = $qb->select('COUNT(dependency_dep_id) AS nb_dependency, dependency_dep_id AS id')
->from('dependency_metaserviceParent_relation')
->where('dependency_dep_id = (' . $subQuery . ')')
->groupBy('dependency_dep_id')
->getQuery();
try {
$result = $pearDB->fetchAssociative($query, QueryParameters::create([
QueryParameter::int('serviceId', $serviceId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error in removeRelationLastMetaServiceDependency',
[
'serviceId' => $serviceId,
],
$exception
);
return;
}
if (isset($result['nb_dependency']) && $result['nb_dependency'] == 1) {
$qbDel = $pearDB->createQueryBuilder();
$queryDel = $qbDel->delete('dependency')
->where('dep_id = :dep_id')
->getQuery();
try {
$pearDB->delete($queryDel, QueryParameters::create([
QueryParameter::int('dep_id', (int) $result['id']),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error deleting dependency',
[
'depId' => $result['id'],
],
$exception
);
}
}
}
/**
* Delete meta service(s) and corresponding service entries
*
* @param array<mixed> $metas
* @return void
*/
function deleteMetaServiceInDB($metas = [])
{
global $pearDB;
foreach ($metas as $metaId => $value) {
removeRelationLastMetaServiceDependency((int) $metaId);
$qb = $pearDB->createQueryBuilder();
$query = $qb->delete('meta_service')
->where('meta_id = :meta_id')
->getQuery();
try {
$pearDB->delete($query, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error deleting meta_service',
[
'meta_id' => $metaId,
],
$exception
);
}
$qb2 = $pearDB->createQueryBuilder();
$query2 = $qb2->delete('service')
->where('service_description = :service_description')
->andWhere("service_register = '2'")
->getQuery();
try {
$pearDB->delete($query2, QueryParameters::create([
QueryParameter::string('service_description', 'meta_' . $metaId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error deleting service for meta_service',
[
'serviceDescription' => 'meta_' . $metaId,
],
$exception
);
}
}
}
/**
* Enable a metric in the DB
*
* @param int|null $msrId
* @return void
*/
function enableMetricInDB($msrId = null)
{
if (! $msrId) {
return;
}
global $pearDB;
$qb = $pearDB->createQueryBuilder();
$query = $qb->update('meta_service_relation')
->set('activate', "'1'")
->where('msr_id = :msr_id')
->getQuery();
try {
$pearDB->update($query, QueryParameters::create([
QueryParameter::int('msr_id', (int) $msrId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error enabling metric',
[
'msrId' => $msrId,
],
$exception
);
}
}
/**
* Disable a metric in the DB
*
* @param int|null $msrId
* @return void
*/
function disableMetricInDB($msrId = null)
{
if (! $msrId) {
return;
}
global $pearDB;
$qb = $pearDB->createQueryBuilder();
$query = $qb->update('meta_service_relation')
->set('activate', "'0'")
->where('msr_id = :msr_id')
->getQuery();
try {
$pearDB->update($query, QueryParameters::create([
QueryParameter::int('msr_id', (int) $msrId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error disabling metric',
[
'msrId' => $msrId,
],
$exception
);
}
}
/**
* Delete metric(s) from the DB
*
* @param array<mixed> $metrics
* @return void
*/
function deleteMetricInDB($metrics = [])
{
global $pearDB;
foreach ($metrics as $msrId => $value) {
$qb = $pearDB->createQueryBuilder();
$query = $qb->delete('meta_service_relation')
->where('msr_id = :msr_id')
->getQuery();
try {
$pearDB->delete($query, QueryParameters::create([
QueryParameter::int('msr_id', (int) $msrId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error deleting metric',
[
'msrId' => $msrId,
],
$exception
);
}
}
}
/**
* Duplicate meta services
*
* @param array<int> $metas Array of meta_ids to duplicate
* @param array<int> $nbrDup Array of duplication counts indexed by meta_id
* @return void
*/
function multipleMetaServiceInDB($metas = [], $nbrDup = [])
{
global $pearDB;
foreach ($metas as $metaId => $value) {
$qbSelect = $pearDB->createQueryBuilder();
$query = $qbSelect->select('*')
->from('meta_service')
->where('meta_id = :meta_id')
->limit(1)
->getQuery();
try {
$row = $pearDB->fetchAssociative($query, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error fetching meta_service for duplication',
[
'metaId' => $metaId,
],
$exception
);
continue;
}
if (! $row) {
continue;
}
$row['meta_id'] = null;
for ($i = 1; $i <= $nbrDup[$metaId]; $i++) {
$metaName = $row['meta_name'] . '_' . $i;
$row['meta_name'] = $metaName;
$columns = array_keys($row);
$qbInsert = $pearDB->createQueryBuilder();
$insertQuery = $qbInsert->insert('meta_service')
->values(array_combine($columns, array_map(fn ($col) => ':' . $col, $columns)))
->getQuery();
try {
if (! testExistence($metaName)) {
continue;
}
$params = [];
foreach ($row as $column => $value) {
$params[] = QueryParameter::string($column, $value);
}
$pearDB->insert($insertQuery, QueryParameters::create($params));
$newMetaId = $pearDB->getLastInsertId();
if ($newMetaId) {
$metaObj = new CentreonMeta($pearDB);
$metaObj->insertVirtualService($newMetaId, addslashes($metaName));
// Duplicate contacts
$qbContacts = $pearDB->createQueryBuilder();
$queryContacts = $qbContacts->select('DISTINCT contact_id')
->from('meta_contact')
->where('meta_id = :meta_id')
->getQuery();
$contacts = $pearDB->fetchAllAssociative($queryContacts, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
foreach ($contacts as $contact) {
$qbInsertContact = $pearDB->createQueryBuilder();
$queryInsertContact = $qbInsertContact->insert('meta_contact')
->values([
'meta_id' => ':meta_id',
'contact_id' => ':contact_id',
])
->getQuery();
$pearDB->insert($queryInsertContact, QueryParameters::create([
QueryParameter::int('meta_id', (int) $newMetaId),
QueryParameter::int('contact_id', (int) $contact['contact_id']),
]));
}
// Duplicate contactgroups
$qbCG = $pearDB->createQueryBuilder();
$queryCG = $qbCG->select('DISTINCT cg_cg_id')
->from('meta_contactgroup_relation')
->where('meta_id = :meta_id')
->getQuery();
$cgroups = $pearDB->fetchAllAssociative($queryCG, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
foreach ($cgroups as $cg) {
$qbInsertCG = $pearDB->createQueryBuilder();
$queryInsertCG = $qbInsertCG->insert('meta_contactgroup_relation')
->values([
'meta_id' => ':meta_id',
'cg_cg_id' => ':cg_cg_id',
])
->getQuery();
$pearDB->insert($queryInsertCG, QueryParameters::create([
QueryParameter::int('meta_id', (int) $newMetaId),
QueryParameter::int('cg_cg_id', (int) $cg['cg_cg_id']),
]));
}
// Duplicate metrics
$qbMetric = $pearDB->createQueryBuilder();
$queryMetric = $qbMetric->select('*')
->from('meta_service_relation')
->where('meta_id = :meta_id')
->getQuery();
$metricsRows = $pearDB->fetchAllAssociative($queryMetric, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
foreach ($metricsRows as $metric) {
$metric['msr_id'] = null;
$metric['meta_id'] = $newMetaId;
$columns = array_keys($metric);
$qbInsertMetric = $pearDB->createQueryBuilder();
$insertMetricQuery = $qbInsertMetric->insert('meta_service_relation')
->values(array_combine($columns, array_map(fn ($col) => ':' . $col, $columns)))
->getQuery();
// Build parameters for the metric row.
$paramsMetric = [];
foreach ($metric as $column => $value) {
$paramsMetric[] = QueryParameter::string($column, $value);
}
$pearDB->insert($insertMetricQuery, QueryParameters::create($paramsMetric));
}
updateAclResourcesMetaRelations($newMetaId);
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error duplicating meta_service',
[
'metaId' => $metaId,
'metaName' => $metaName,
],
$exception
);
}
}
}
}
/**
* Update an existing meta service using bound parameters
*
* @param int|null $metaId
* @return void
*/
function updateMetaServiceInDB($metaId = null)
{
global $isCloudPlatform;
if (! $metaId) {
return;
}
updateMetaService($metaId);
if (! $isCloudPlatform) {
updateMetaServiceContact($metaId);
updateMetaServiceContactGroup($metaId);
}
updateAclResourcesMetaRelations($metaId);
}
/**
* Insert a new meta service in the DB
*
* @return int
*/
function insertMetaServiceInDB()
{
global $isCloudPlatform;
$metaId = insertMetaService();
if (! $isCloudPlatform) {
updateMetaServiceContact($metaId);
updateMetaServiceContactGroup($metaId);
}
updateAclResourcesMetaRelations($metaId);
return $metaId;
}
/**
* Duplicate metrics: for each metric to duplicate, fetch its row and insert duplicates
*
* @param array<int> $metrics
* @param array<int> $nbrDup
* @return void
*/
function multipleMetricInDB($metrics = [], $nbrDup = [])
{
global $pearDB;
foreach ($metrics as $msrId => $value) {
$qbSelect = $pearDB->createQueryBuilder();
$query = $qbSelect->select('*')
->from('meta_service_relation')
->where('msr_id = :msr_id')
->limit(1)
->getQuery();
try {
$row = $pearDB->fetchAssociative($query, QueryParameters::create([
QueryParameter::int('msr_id', (int) $msrId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error fetching metric for duplication',
[
'msrId' => $msrId,
],
$exception
);
continue;
}
if (! $row) {
continue;
}
$row['msr_id'] = null;
for ($i = 1; $i <= $nbrDup[$msrId]; $i++) {
$columns = array_keys($row);
$qbInsert = $pearDB->createQueryBuilder();
$insertQuery = $qbInsert->insert('meta_service_relation')
->values(array_combine($columns, array_map(fn ($col) => ':' . $col, $columns)))
->getQuery();
try {
$params = [];
foreach ($row as $column => $val) {
$params[] = QueryParameter::string($column, $val);
}
$pearDB->insert($insertQuery, QueryParameters::create($params));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error inserting duplicated metric',
[
'originalMsrId' => $msrId,
'duplicationIndex' => $i,
],
$exception
);
}
}
}
}
/**
* Check if the virtual meta host exists and create it if not
*
* @return void
*/
function checkMetaHost()
{
global $pearDB;
$qbSelect = $pearDB->createQueryBuilder();
$query = $qbSelect->select('host_id')
->from('host')
->where("host_register = '2'")
->andWhere("host_name = '_Module_Meta'")
->getQuery();
try {
$host = $pearDB->fetchAssociative($query);
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error fetching _Module_Meta host',
[
],
$exception
);
$host = false;
}
if (! $host) {
$qbInsert = $pearDB->createQueryBuilder();
$queryInsert = $qbInsert->insert('host')
->values([
'host_name' => "'_Module_Meta'",
'host_register' => "'2'",
])
->getQuery();
try {
$pearDB->insert($queryInsert);
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error inserting _Module_Meta host',
[
],
$exception
);
}
// For linking, the subqueries are left as raw SQL for clarity.
$queryLink = <<<'SQL'
INSERT INTO ns_host_relation (nagios_server_id, host_host_id)
VALUES (
(SELECT id FROM nagios_server WHERE localhost = '1'),
(SELECT host_id FROM host WHERE host_name = '_Module_Meta')
)
ON DUPLICATE KEY UPDATE nagios_server_id = (SELECT id FROM nagios_server WHERE localhost = '1')
SQL;
try {
$pearDB->insert($queryLink);
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error linking _Module_Meta host to Nagios server',
[
],
$exception
);
}
}
}
/**
* Insert meta service
*
* @param array<mixed> $ret
* @return int
*/
function insertMetaService($ret = [])
{
global $form, $pearDB, $centreon;
checkMetaHost();
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$qbInsert = $pearDB->createQueryBuilder();
$query = $qbInsert->insert('meta_service')
->values([
'meta_name' => ':meta_name',
'meta_display' => ':meta_display',
'check_period' => ':check_period',
'max_check_attempts' => ':max_check_attempts',
'normal_check_interval' => ':normal_check_interval',
'retry_check_interval' => ':retry_check_interval',
'notification_interval' => ':notification_interval',
'notification_period' => ':notification_period',
'notification_options' => ':notification_options',
'notifications_enabled' => ':notifications_enabled',
'calcul_type' => ':calcul_type',
'data_source_type' => ':data_source_type',
'meta_select_mode' => ':meta_select_mode',
'regexp_str' => ':regexp_str',
'metric' => ':metric',
'warning' => ':warning',
'critical' => ':critical',
'graph_id' => ':graph_id',
'meta_comment' => ':meta_comment',
'geo_coords' => ':geo_coords',
'meta_activate' => ':meta_activate',
])
->getQuery();
try {
$params = [
QueryParameter::string('meta_name', getParamValue($ret, 'meta_name', sanitize: true)),
QueryParameter::string('meta_display', getParamValue($ret, 'meta_display', sanitize: true)),
QueryParameter::string('check_period', getParamValue($ret, 'check_period')),
QueryParameter::int('max_check_attempts', (int) getParamValue($ret, 'max_check_attempts')),
QueryParameter::string('normal_check_interval', getParamValue($ret, 'normal_check_interval')),
QueryParameter::string('retry_check_interval', getParamValue($ret, 'retry_check_interval')),
QueryParameter::string('notification_interval', getParamValue($ret, 'notification_interval')),
QueryParameter::string('notification_period', getParamValue($ret, 'notification_period')),
QueryParameter::string('notification_options', isset($ret['ms_notifOpts']) ? implode(',', array_keys($ret['ms_notifOpts'])) : null),
QueryParameter::string('notifications_enabled', getParamValue($ret, 'notifications_enabled', 'notifications_enabled', default: '2')),
QueryParameter::string('calcul_type', $ret['calcul_type'] ?? null),
QueryParameter::int('data_source_type', (int) getParamValue($ret, 'data_source_type', default: 0)),
QueryParameter::string('meta_select_mode', getParamValue($ret, 'meta_select_mode', 'meta_select_mode')),
QueryParameter::string('regexp_str', getParamValue($ret, 'regexp_str', sanitize: true)),
QueryParameter::string('metric', getParamValue($ret, 'metric', sanitize: true)),
QueryParameter::string('warning', getParamValue($ret, 'warning', sanitize: true)),
QueryParameter::string('critical', getParamValue($ret, 'critical', sanitize: true)),
QueryParameter::string('graph_id', getParamValue($ret, 'graph_id')),
QueryParameter::string('meta_comment', getParamValue($ret, 'meta_comment', sanitize: true)),
QueryParameter::string('geo_coords', getParamValue($ret, 'geo_coords', sanitize: true)),
QueryParameter::string('meta_activate', getParamValue($ret, 'meta_activate', 'meta_activate')),
];
$pearDB->insert($query, QueryParameters::create($params));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error inserting meta_service',
[
'metaName' => $ret['meta_name'] ?? null,
'params' => $params,
],
$exception
);
}
$metaId = $pearDB->getLastInsertId();
if (! $metaId) {
return 0;
}
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog('meta', $metaId, addslashes($ret['meta_name']), 'a', $fields);
$metaObj = new CentreonMeta($pearDB);
$metaObj->insertVirtualService($metaId, addslashes($ret['meta_name']));
return $metaId;
}
/**
* Update meta service
*
* @param int|null $metaId
* @return void
*/
function updateMetaService($metaId = null)
{
if (! $metaId) {
return;
}
global $form, $pearDB, $centreon;
checkMetaHost();
$ret = $form->getSubmitValues();
$qb = $pearDB->createQueryBuilder();
$qb->update('meta_service')
->set('meta_name', ':meta_name')
->set('meta_display', ':meta_display')
->set('check_period', ':check_period')
->set('max_check_attempts', ':max_check_attempts')
->set('normal_check_interval', ':normal_check_interval')
->set('retry_check_interval', ':retry_check_interval')
->set('notification_interval', ':notification_interval')
->set('notification_period', ':notification_period')
->set('notification_options', ':notification_options')
->set('notifications_enabled', ':notifications_enabled')
->set('calcul_type', ':calcul_type')
->set('data_source_type', ':data_source_type')
->set('meta_select_mode', ':meta_select_mode')
->set('regexp_str', ':regexp_str')
->set('metric', ':metric')
->set('warning', ':warning')
->set('critical', ':critical')
->set('graph_id', ':graph_id')
->set('meta_comment', ':meta_comment')
->set('geo_coords', ':geo_coords')
->set('meta_activate', ':meta_activate')
->where('meta_id = :meta_id');
$query = $qb->getQuery();
$params = [];
try {
$params = [
QueryParameter::string('meta_name', getParamValue($ret, 'meta_name', sanitize: true)),
QueryParameter::string('meta_display', getParamValue($ret, 'meta_display', sanitize: true)),
QueryParameter::string('check_period', getParamValue($ret, 'check_period')),
QueryParameter::int('max_check_attempts', (int) getParamValue($ret, 'max_check_attempts')),
QueryParameter::string('normal_check_interval', getParamValue($ret, 'normal_check_interval')),
QueryParameter::string('retry_check_interval', getParamValue($ret, 'retry_check_interval')),
QueryParameter::string('notification_interval', getParamValue($ret, 'notification_interval')),
QueryParameter::string('notification_period', getParamValue($ret, 'notification_period')),
QueryParameter::string('notification_options', isset($ret['ms_notifOpts']) ? implode(',', array_keys($ret['ms_notifOpts'])) : null),
QueryParameter::string('notifications_enabled', getParamValue($ret, 'notifications_enabled', 'notifications_enabled', false, '2')),
QueryParameter::string('calcul_type', $ret['calcul_type'] ?? null),
QueryParameter::int('data_source_type', (int) getParamValue($ret, 'data_source_type', null, false, 0)),
QueryParameter::string('meta_select_mode', getParamValue($ret, 'meta_select_mode', 'meta_select_mode')),
QueryParameter::string('regexp_str', getParamValue($ret, 'regexp_str', sanitize: true)),
QueryParameter::string('metric', getParamValue($ret, 'metric', sanitize: true)),
QueryParameter::string('warning', getParamValue($ret, 'warning', sanitize: true)),
QueryParameter::string('critical', getParamValue($ret, 'critical', sanitize: true)),
QueryParameter::string('graph_id', getParamValue($ret, 'graph_id')),
QueryParameter::string('meta_comment', getParamValue($ret, 'meta_comment', sanitize: true)),
QueryParameter::string('geo_coords', getParamValue($ret, 'geo_coords', sanitize: true)),
QueryParameter::string('meta_activate', getParamValue($ret, 'meta_activate', 'meta_activate')),
QueryParameter::int('meta_id', (int) $metaId),
];
$pearDB->update($query, QueryParameters::create($params));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error updating meta_service (updateMetaService)',
[
'metaId' => $metaId,
'params' => $params,
],
$exception
);
}
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog('meta', $metaId, addslashes($ret['meta_name']), 'c', $fields);
$metaObj = new CentreonMeta($pearDB);
$metaObj->insertVirtualService($metaId, addslashes($ret['meta_name']));
}
/**
* Update meta service contact relations
*
* @param int $metaId
* @return void
*/
function updateMetaServiceContact($metaId)
{
if (! $metaId || ! is_numeric($metaId)) {
return;
}
global $form, $pearDB, $centreon;
$qbDelete = $pearDB->createQueryBuilder();
$queryPurge = $qbDelete->delete('meta_contact')
->where('meta_id = :meta_id')
->getQuery();
try {
$pearDB->delete($queryPurge, QueryParameters::create([
QueryParameter::int('meta_id', (int) $metaId),
]));
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error purging meta_contact',
[
'metaId' => $metaId,
],
$exception
);
}
$ret = CentreonUtils::mergeWithInitialValues($form, 'ms_cs');
$userId = $centreon->user->get_id();
if (! in_array($userId, $ret) && $centreon->user->admin !== '1') {
$ret[] = $userId;
}
$values = [];
$params = [];
try {
foreach ($ret as $key => $contactId) {
$values[] = " (:metaId_{$key}, :contactId_{$key})";
$params["metaId_{$key}"] = QueryParameter::int("metaId_{$key}", (int) $metaId);
$params["contactId_{$key}"] = QueryParameter::int("contactId_{$key}", (int) $contactId);
}
$valuesString = implode(',', $values);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/meta_service/formMetaService.php | centreon/www/include/configuration/configObject/meta_service/formMetaService.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
// Get the list of contact
// notification contacts
$notifCs = $acl->getContactAclConf(['fields' => ['contact_id', 'contact_name'], 'get_row' => 'contact_name', 'keys' => ['contact_id'], 'conditions' => ['contact_register' => '1'], 'order' => ['contact_name']]);
// notification contact groups
$notifCgs = [];
$cg = new CentreonContactgroup($pearDB);
if ($oreon->user->admin) {
$notifCgs = $cg->getListContactgroup(true);
} else {
$cgAcl = $acl->getContactGroupAclConf(['fields' => ['cg_id', 'cg_name'], 'get_row' => 'cg_name', 'keys' => ['cg_id'], 'order' => ['cg_name']]);
$cgLdap = $cg->getListContactgroup(true, true);
$notifCgs = array_intersect_key($cgLdap, $cgAcl);
}
$initialValues = [];
$ms = [];
try {
if (($o == 'c' || $o == 'w') && $meta_id) {
$params = QueryParameters::create([
QueryParameter::int('meta_id', (int) $meta_id),
]);
$DBRESULT = $pearDB->fetchAssociative('SELECT * FROM meta_service WHERE meta_id = :meta_id LIMIT 1', $params);
// Set base value
$ms = array_map('myDecode', $DBRESULT);
$ms['metric'] = [$ms['metric'] => $ms['metric']];
if (! isCloudPlatform()) {
// Set Service Notification Options
$tmp = explode(',', $ms['notification_options']);
foreach ($tmp as $key => $value) {
$ms['ms_notifOpts'][trim($value)] = 1;
}
}
}
} catch (ValueObjectException|CollectionException|ConnectionException|RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while preparing initial values for meta_service',
[
'meta_id' => $meta_id,
],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while processing meta_service data');
}
// Calc Type
$calType = ['AVE' => _('Average'), 'SOM' => _('Sum'), 'MIN' => _('Min'), 'MAX' => _('Max')];
// Data source type
$dsType = [0 => 'GAUGE', 1 => 'COUNTER', 2 => 'DERIVE', 3 => 'ABSOLUTE'];
// Graphs Template comes from DB -> Store in $graphTpls Array
$graphTpls = [null => null];
$DBRESULT = $pearDB->query('SELECT graph_id, name FROM giv_graphs_template ORDER BY name');
while ($graphTpl = $DBRESULT->fetchRow()) {
$graphTpls[$graphTpl['graph_id']] = $graphTpl['name'];
}
$DBRESULT->closeCursor();
// Init Styles
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '6'];
$attrsAdvSelect = ['style' => 'width: 200px; height: 100px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$timeAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod&action=list';
$attrTimeperiods = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $timeAvRoute, 'multiple' => false, 'linkedObject' => 'centreonTimeperiod'];
$attrMetric = [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => './api/internal.php?object=centreon_monitoring_metric&action=list',
'multiple' => false,
];
$contactAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contact&action=list';
$attrContacts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $contactAvRoute, 'multiple' => true, 'linkedObject' => 'centreonContact'];
$contactGrAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup'
. '&action=list';
$attrContactgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $contactGrAvRoute, 'multiple' => true, 'linkedObject' => 'centreonContactgroup'];
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add a Meta Service'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify a Meta Service'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View a Meta Service'));
}
// Service basic information
$form->addElement('header', 'information', _('General Information'));
$form->addElement('text', 'meta_name', _('Name'), $attrsText);
$form->addElement('text', 'meta_display', _('Output format string (printf-style)'), $attrsText);
$form->addElement('text', 'warning', _('Warning Level'), $attrsText2);
$form->addElement('text', 'critical', _('Critical Level'), $attrsText2);
$form->addElement('select', 'calcul_type', _('Calculation Type'), $calType);
$form->addElement('select', 'data_source_type', _('Data Source Type'), $dsType);
$tab = [];
$tab[] = $form->createElement('radio', 'meta_select_mode', null, _('Service List'), '1');
$tab[] = $form->createElement('radio', 'meta_select_mode', null, _('SQL matching'), '2');
$form->addGroup($tab, 'meta_select_mode', _('Selection Mode'), '<br />');
$form->setDefaults(['meta_select_mode' => ['meta_select_mode' => '1']]);
$form->addElement('text', 'regexp_str', _('SQL LIKE-clause expression'), $attrsText);
$form->addElement('select2', 'metric', _('Metric'), [], $attrMetric);
// Check information
$form->addElement('header', 'check', _('Meta Service State'));
$timeDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod'
. '&action=defaultValues&target=meta&field=check_period&id=' . $meta_id;
$attrTimeperiod1 = array_merge(
$attrTimeperiods,
['defaultDatasetRoute' => $timeDeRoute]
);
$form->addElement('select2', 'check_period', _('Check Period'), [], $attrTimeperiod1);
$form->addElement('text', 'max_check_attempts', _('Max Check Attempts'), $attrsText2);
$form->addElement('text', 'normal_check_interval', _('Normal Check Interval'), $attrsText2);
$form->addElement('text', 'retry_check_interval', _('Retry Check Interval'), $attrsText2);
$isCloudPlatform = isCloudPlatform();
if (! $isCloudPlatform) {
// Notification informations
$form->addElement('header', 'notification', _('Notification'));
$tab = [];
$tab[] = $form->createElement('radio', 'notifications_enabled', null, _('Yes'), '1');
$tab[] = $form->createElement('radio', 'notifications_enabled', null, _('No'), '0');
$tab[] = $form->createElement('radio', 'notifications_enabled', null, _('Default'), '2');
$form->addGroup($tab, 'notifications_enabled', _('Notification Enabled'), ' ');
$form->setDefaults(['notifications_enabled' => '2']);
// Contacts
$contactDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contact'
. '&action=defaultValues&target=meta&field=ms_cs&id=' . $meta_id;
$attrContact1 = array_merge(
$attrContacts,
['defaultDatasetRoute' => $contactDeRoute]
);
$form->addElement('select2', 'ms_cs', _('Implied Contacts'), [], $attrContact1);
$contactGrDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup'
. '&action=defaultValues&target=meta&field=ms_cgs&id=' . $meta_id;
$attrContactgroup1 = array_merge(
$attrContactgroups,
['defaultDatasetRoute' => $contactGrDeRoute]
);
$form->addElement('select2', 'ms_cgs', _('Linked Contact Groups'), [], $attrContactgroup1);
$form->addElement('text', 'notification_interval', _('Notification Interval'), $attrsText2);
$timeDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod'
. '&action=defaultValues&target=meta&field=notification_period&id=' . $meta_id;
$attrTimeperiod2 = array_merge(
$attrTimeperiods,
['defaultDatasetRoute' => $timeDeRoute]
);
$form->addElement('select2', 'notification_period', _('Notification Period'), [], $attrTimeperiod2);
$msNotifOpt[] = $form->createElement('checkbox', 'w', ' ', _('Warning'));
$msNotifOpt[] = $form->createElement('checkbox', 'u', ' ', _('Unknown'));
$msNotifOpt[] = $form->createElement('checkbox', 'c', ' ', _('Critical'));
$msNotifOpt[] = $form->createElement('checkbox', 'r', ' ', _('Recovery'));
$msNotifOpt[] = $form->createElement('checkbox', 'f', ' ', _('Flapping'));
$form->addGroup($msNotifOpt, 'ms_notifOpts', _('Notification Type'), ' ');
}
// Further informations
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$form->addElement('select', 'graph_id', _('Graph Template'), $graphTpls);
$msActivation[] = $form->createElement('radio', 'meta_activate', null, _('Enabled'), '1');
$msActivation[] = $form->createElement('radio', 'meta_activate', null, _('Disabled'), '0');
$form->addGroup($msActivation, 'meta_activate', _('Status'), ' ');
$form->setDefaults(['meta_activate' => '1']);
$form->addElement('textarea', 'meta_comment', _('Comments'), $attrsTextarea);
$form->registerRule('validate_geo_coords', 'function', 'validateGeoCoords');
$form->addElement('text', 'geo_coords', _('Geo coordinates'), $attrsText);
$form->addRule('geo_coords', _('geo coords are not valid'), 'validate_geo_coords');
$form->applyFilter('geo_coords', 'truncateGeoCoords');
$form->addElement('hidden', 'meta_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
// Form Rules
function myReplace()
{
global $form;
return str_replace(' ', '_', $form->getSubmitValue('meta_name'));
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('meta_name', 'myReplace');
$form->addRule('meta_name', _('Compulsory Name'), 'required');
$form->addRule('max_check_attempts', _('Required Field'), 'required');
$form->addRule('calcul_type', _('Required Field'), 'required');
$form->addRule('meta_select_mode', _('Required Field'), 'required');
$form->registerRule('exist', 'callback', 'testExistence');
$form->addRule('meta_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR,'
. ' "orange", TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"],'
. ' WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
// Prepare toggle fields based on the selection mode
$toggleScript = <<<'JS'
<script type="text/javascript" defer>
document.addEventListener("DOMContentLoaded", function() {
function toggleFields() {
var selectedRadio = document.querySelector('input[name="meta_select_mode[meta_select_mode]"]:checked');
console.log(selectedRadio);
if (!selectedRadio) {
// No radio button is selected, so exit or set a default behavior.
return;
}
var selected = selectedRadio.value;
if(selected === "1") { // Service List selected
document.getElementById("row_regexp_str").style.display = "none";
document.getElementById("row_metric").style.display = "none";
} else { // SQL matching
document.getElementById("row_regexp_str").style.display = "";
document.getElementById("row_metric").style.display = "";
}
}
var radios = document.getElementsByName("meta_select_mode[meta_select_mode]");
console.log(radios);
if (radios.length > 0) {
for (var i = 0; i < radios.length; i++){
radios[i].addEventListener("change", toggleFields);
}
}
toggleFields(); // initial toggle on page load
});
</script>
JS;
$tpl->assign('toggleScript', $toggleScript);
if ($o == 'w') {
// Just watch a host information
if (! $min && $centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&meta_id=' . $meta_id . "'"]
);
}
$form->setDefaults($ms);
$form->freeze();
} elseif ($o == 'c') {
// Modify a service information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($ms);
} elseif ($o == 'a') {
// Add a service information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$tpl->assign('msg', ['nagios' => $oreon->user->get_version()]);
$tpl->assign('time_unit', ' * ' . $oreon->optGen['interval_length'] . ' ' . _('seconds'));
$tpl->assign('isCloudPlatform', $isCloudPlatform);
$valid = false;
if ($form->validate()) {
$msObj = $form->getElement('meta_id');
if ($form->getSubmitValue('submitA')) {
$msObj->setValue(insertMetaServiceInDB());
// Update ACL and meta service string for the next listing
$acl = new CentreonACL($centreon->user->get_id(), $centreon->user->admin === '1');
$aclDbName = $acl->getNameDBAcl();
$metaStr = $acl->getMetaServiceString();
} elseif ($form->getSubmitValue('submitC')) {
updateMetaServiceInDB($msObj->getValue());
}
$o = null;
$valid = true;
}
if ($valid) {
require_once $path . 'listMetaService.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formMetaService.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php | centreon/www/include/configuration/configObject/service_template_model/listServiceTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
// Object init
$mediaObj = new CentreonMedia($pearDB);
include './include/common/autoNumLimit.php';
$o = '';
$search = htmlspecialchars($_POST['searchST'] ?? $_GET['searchST'] ?? $centreon->historySearch[$url]['search'] ?? '');
$displayLocked = filter_var(
$_POST['displayLocked'] ?? $_GET['displayLocked'] ?? 'off',
FILTER_VALIDATE_BOOLEAN
);
// keep checkbox state if navigating in pagination
// this trick is mandatory cause unchecked checkboxes do not post any data
if (
isset($centreon->historyPage[$url])
&& ($centreon->historyPage[$url] > 0 || $num !== 0)
&& isset($centreon->historySearch[$url]['displayLocked'])
) {
$displayLocked = $centreon->historySearch[$url]['displayLocked'];
}
// store filters in session
$centreon->historySearch[$url] = [
'search' => $search,
'displayLocked' => $displayLocked,
];
// Locked filter
$lockedFilter = $displayLocked ? '' : 'AND sv.service_locked = 0 ';
// Service Template Model list
if ($search) {
$statement = $pearDB->prepare('SELECT SQL_CALC_FOUND_ROWS sv.service_id, sv.service_description,'
. ' sv.service_alias, sv.service_template_model_stm_id FROM service sv '
. 'WHERE (sv.service_description LIKE :search OR sv.service_alias LIKE :search) '
. "AND sv.service_register = '0' "
. $lockedFilter
. 'ORDER BY service_description LIMIT :scope, :limit');
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
} else {
$statement = $pearDB->prepare('SELECT SQL_CALC_FOUND_ROWS sv.service_id, sv.service_description,'
. ' sv.service_alias, sv.service_template_model_stm_id FROM service sv '
. "WHERE sv.service_register = '0' " . $lockedFilter
. 'ORDER BY service_description LIMIT :scope, :limit');
}
$statement->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
$statement->bindValue(':scope', (int) $num * (int) $limit, PDO::PARAM_INT);
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_desc', _('Name'));
$tpl->assign('headerMenu_alias', _('Alias'));
$tpl->assign('headerMenu_retry', _('Scheduling'));
$tpl->assign('headerMenu_parent', _('Templates'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_options', _('Options'));
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$interval_length = $oreon->optGen['interval_length'];
$search = str_replace('#S#', '/', $search);
$search = str_replace('#BS#', '\\', $search);
$centreonToken = createCSRFToken();
for ($i = 0; $service = $statement->fetch(); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $service['service_id'] . ']');
if (isset($lockedElements[$service['service_id']])) {
$selectedElements->setAttribute('disabled', 'disabled');
} else {
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr["
. $service['service_id'] . "]' />";
}
/*If the description of our Service Model is in the Template definition,
we have to catch it, whatever the level of it :-) */
if (! $service['service_description']) {
$service['service_description'] = getMyServiceName($service['service_template_model_stm_id']);
}
// TPL List
$tplArr = [];
$tplStr = '';
$tplArr = getMyServiceTemplateModels($service['service_template_model_stm_id']);
if ((is_countable($tplArr)) && count($tplArr)) {
foreach ($tplArr as $key => $value) {
$value = str_replace('#S#', '/', $value);
$value = str_replace('#BS#', '\\', $value);
$tplStr .= " -> <a href='main.php?p=60206&o=c&service_id=" . $key . "'>"
. htmlentities($value) . '</a>';
}
}
$service['service_description'] = str_replace('#BR#', "\n", $service['service_description']);
$service['service_description'] = str_replace('#T#', "\t", $service['service_description']);
$service['service_description'] = str_replace('#R#', "\r", $service['service_description']);
$service['service_description'] = str_replace('#S#', '/', $service['service_description']);
$service['service_description'] = str_replace('#BS#', '\\', $service['service_description']);
$service['service_alias'] = str_replace('#BR#', "\n", $service['service_alias']);
$service['service_alias'] = str_replace('#T#', "\t", $service['service_alias']);
$service['service_alias'] = str_replace('#R#', "\r", $service['service_alias']);
$service['service_alias'] = str_replace('#S#', '/', $service['service_alias']);
$service['service_alias'] = str_replace('#BS#', '\\', $service['service_alias']);
// Get service intervals in seconds
$normal_check_interval
= getMyServiceField($service['service_id'], 'service_normal_check_interval') * $interval_length;
$retry_check_interval
= getMyServiceField($service['service_id'], 'service_retry_check_interval') * $interval_length;
if ($normal_check_interval % 60 == 0) {
$normal_units = 'min';
$normal_check_interval = $normal_check_interval / 60;
} else {
$normal_units = 'sec';
}
if ($retry_check_interval % 60 == 0) {
$retry_units = 'min';
$retry_check_interval = $retry_check_interval / 60;
} else {
$retry_units = 'sec';
}
if (isset($service['esi_icon_image']) && $service['esi_icon_image']) {
$svc_icon = './img/media/' . $mediaObj->getFilename($service['esi_icon_image']);
} elseif (
$icone = $mediaObj->getFilename(
getMyServiceExtendedInfoField(
$service['service_id'],
'esi_icon_image'
)
)
) {
$svc_icon = './img/media/' . $icone;
} else {
$svc_icon = './img/icons/service.png';
}
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_desc' => htmlentities($service['service_description']), 'RowMenu_alias' => htmlentities($service['service_alias']), 'RowMenu_parent' => $tplStr, 'RowMenu_icon' => $svc_icon, 'RowMenu_retry' => htmlentities(
"{$normal_check_interval} {$normal_units} / {$retry_check_interval} {$retry_units}"
), 'RowMenu_attempts' => getMyServiceField($service['service_id'], 'service_max_check_attempts'), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&service_id=' . $service['service_id'], 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select lgd_more_actions
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3 || this.form.elements['o1'].selectedIndex == 4 "
. "||this.form.elements['o1'].selectedIndex == 5){"
. " setO(this.form.elements['o1'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3 || this.form.elements['o2'].selectedIndex == 4 "
. "||this.form.elements['o2'].selectedIndex == 5){"
. " setO(this.form.elements['o2'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchST', $search);
$tpl->assign('displayLocked', $displayLocked);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listServiceTemplateModel.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_template_model/formServiceTemplateModel.php | centreon/www/include/configuration/configObject/service_template_model/formServiceTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
function myDecodeSvTP($arg)
{
$arg = str_replace('#BR#', '\\n', $arg ?? '');
$arg = str_replace('#T#', '\\t', $arg);
$arg = str_replace('#R#', '\\r', $arg);
$arg = str_replace('#S#', '/', $arg);
$arg = str_replace('#BS#', '\\', $arg);
return html_entity_decode($arg, ENT_QUOTES, 'UTF-8');
}
const PASSWORD_REPLACEMENT_VALUE = '**********';
const BASE_ROUTE = './include/common/webServices/rest/internal.php';
$datasetRoutes = [
'timeperiods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=list',
'contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=list',
'default_contacts' => BASE_ROUTE . '?object=centreon_configuration_contact&action=defaultValues&target=service&field=service_cs&id=' . $service_id,
'contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=list',
'default_contact_groups' => BASE_ROUTE . '?object=centreon_configuration_contactgroup&action=defaultValues&target=service&field=service_cgs&id=' . $service_id,
'hosts' => BASE_ROUTE . '?object=centreon_configuration_host&action=list',
'default_hosts' => BASE_ROUTE . '?object=centreon_configuration_host&action=defaultValues&target=service&field=service_hPars&id=' . $service_id,
'host_templates' => BASE_ROUTE . '?object=centreon_configuration_hosttemplate&action=list',
'host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=list',
'service_templates' => BASE_ROUTE . '?object=centreon_configuration_servicetemplate&action=list',
'service_groups' => BASE_ROUTE . '?object=centreon_configuration_servicegroup&action=list',
'service_categories' => BASE_ROUTE . '?object=centreon_configuration_servicecategory&action=list&t=c',
'traps' => BASE_ROUTE . '?object=centreon_configuration_trap&action=list',
'check_commands' => BASE_ROUTE . '?object=centreon_configuration_command&action=list&t=2',
'event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=list',
'default_check_commands' => BASE_ROUTE . '?object=centreon_configuration_command&action=defaultValues&target=service&field=command_command_id&id=' . $service_id,
'graph_templates' => BASE_ROUTE . '?object=centreon_configuration_graphtemplate&action=list',
'default_service_templates' => BASE_ROUTE . '?object=centreon_configuration_servicetemplate&action=defaultValues&target=service&field=service_template_model_stm_id&id=' . $service_id,
'default_event_handlers' => BASE_ROUTE . '?object=centreon_configuration_command&action=defaultValues&target=service&field=command_command_id2&id=' . $service_id,
'default_check_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=service&field=timeperiod_tp_id&id=' . $service_id,
'default_notification_periods' => BASE_ROUTE . '?object=centreon_configuration_timeperiod&action=defaultValues&target=service&field=timeperiod_tp_id2&id=' . $service_id,
'default_host_groups' => BASE_ROUTE . '?object=centreon_configuration_hostgroup&action=defaultValues&target=service&field=service_hgPars&id=' . $service_id,
'default_service_groups' => BASE_ROUTE . '?object=centreon_configuration_servicegroup&action=defaultValues&target=service&field=service_sgs&id=' . $service_id,
'default_traps' => BASE_ROUTE . '?object=centreon_configuration_trap&action=defaultValues&target=service&field=service_traps&id=' . $service_id,
'default_graph_templates' => BASE_ROUTE . '?object=centreon_configuration_graphtemplate&action=defaultValues&target=service&field=graph_id&id=' . $service_id,
'default_service_categories' => BASE_ROUTE . '?object=centreon_configuration_servicecategory&action=defaultValues&target=service&field=service_categories&id=' . $service_id,
'default_host_templates' => BASE_ROUTE . '?object=centreon_configuration_hosttemplate&action=defaultValues&target=servicetemplates&field=service_hPars&id=' . $service_id,
];
$attributes = [
'timeperiods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'contacts' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contacts'],
'defaultDatasetRoute' => $datasetRoutes['default_contacts'],
'multiple' => true,
'linkedObject' => 'centreonContact',
],
'contact_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['contact_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_contact_groups'],
'multiple' => true,
'linkedObject' => 'centreonContactgroup',
],
'check_commands' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_check_commands'],
'availableDatasetRoute' => $datasetRoutes['check_commands'],
],
'hosts' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['hosts'],
'defaultDatasetRoute' => $datasetRoutes['default_hosts'],
'multiple' => true,
'linkedObject' => 'centreonHost',
],
'host_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['host_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_host_groups'],
'multiple' => true,
'linkedObject' => 'centreonHostgroups',
],
'templates' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['service_templates'],
'defaultDatasetRoute' => $datasetRoutes['default_service_templates'],
'multiple' => false,
'linkedObject' => 'centreonServicetemplates',
],
'service_groups' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['service_groups'],
'defaultDatasetRoute' => $datasetRoutes['default_service_groups'],
'multiple' => true,
'linkedObject' => 'centreonServicegroups',
],
'service_categories' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['service_categories'],
'defaultDatasetRoute' => $datasetRoutes['default_service_categories'],
'multiple' => true,
'linkedObject' => 'centreonServicecategories',
],
'traps' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['traps'],
'defaultDatasetRoute' => $datasetRoutes['default_traps'],
'multiple' => true,
'linkedObject' => 'centreonTraps',
],
'graph_templates' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['graph_templates'],
'defaultDatasetRoute' => $datasetRoutes['default_graph_templates'],
'multiple' => false,
'linkedObject' => 'centreonGraphTemplate',
],
'event_handlers' => [
'datasourceOrigin' => 'ajax',
'multiple' => false,
'linkedObject' => 'centreonCommand',
'defaultDatasetRoute' => $datasetRoutes['default_event_handlers'],
'availableDatasetRoute' => $datasetRoutes['event_handlers'],
],
'check_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_check_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'notification_periods' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['timeperiods'],
'defaultDatasetRoute' => $datasetRoutes['default_notification_periods'],
'multiple' => false,
'linkedObject' => 'centreonTimeperiod',
],
'host_templates' => [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $datasetRoutes['host_templates'],
'defaultDatasetRoute' => $datasetRoutes['default_host_templates'],
'multiple' => true,
'linkedObject' => 'centreonHosttemplates',
],
];
global $isCloudPlatform;
$cmdId = 0;
$serviceTplId = null;
$service = [];
$serviceObj = new CentreonService($pearDB);
// Used to store all macro passwords
$macroPasswords = [];
if (($o === SERVICE_TEMPLATE_MODIFY || $o === SERVICE_TEMPLATE_WATCH) && isset($service_id)) {
if (isset($lockedElements[$service_id])) {
$o = SERVICE_TEMPLATE_WATCH;
}
$statement = $pearDB->prepare(
'SELECT *
FROM service srv
LEFT JOIN extended_service_information esi
ON esi.service_service_id = srv.service_id
WHERE srv.service_id = :service_id LIMIT 1'
);
$statement->bindValue(':service_id', $service_id, PDO::PARAM_INT);
$statement->execute();
// Set base value
$service_list = $statement->fetch() ?: [];
$service = array_map('myDecodeSvTP', $service_list);
$serviceTplId = $service['service_template_model_stm_id'];
$cmdId = $service['command_command_id'];
// Set Service Notification Options
$tmp = explode(',', $service['service_notification_options']);
foreach ($tmp as $key => $value) {
$service['service_notifOpts'][trim($value)] = 1;
}
// Set Stalking Options
$tmp = explode(',', $service['service_stalking_options']);
foreach ($tmp as $key => $value) {
$service['service_stalOpts'][trim($value)] = 1;
}
// Set criticality
$statement = $pearDB->prepare(
'SELECT sc.sc_id
FROM service_categories sc
INNER JOIN service_categories_relation scr
ON scr.sc_id = sc.sc_id
WHERE scr.service_service_id = :service_id AND sc.level IS NOT NULL
ORDER BY sc.level ASC LIMIT 1'
);
$statement->bindValue(':service_id', $service_id, PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount()) {
$cr = $statement->fetch();
$service['criticality_id'] = $cr['sc_id'];
}
$aListTemplate = getListTemplates($pearDB, $service_id);
if (isset($_REQUEST['macroInput'])) {
/**
* We don't taking into account the POST data sent from the interface in order the retrieve the original value
* of all passwords.
*/
$aMacros = $serviceObj->getMacros($service_id, $aListTemplate, $cmdId);
/**
* If a password has been modified from the interface, we retrieve the old password existing in the repository
* (giving by the $aMacros variable) to inject it before saving.
* Passwords will be saved using the $_REQUEST variable.
*/
foreach ($_REQUEST['macroInput'] as $index => $macroName) {
if (
! isset($_REQUEST['macroFrom'][$index])
|| ! isset($_REQUEST['macroPassword'][$index])
|| $_REQUEST['macroPassword'][$index] !== '1' // Not a password
|| $_REQUEST['macroValue'][$index] !== PASSWORD_REPLACEMENT_VALUE // The password has not changed
) {
continue;
}
foreach ($aMacros as $macroAlreadyExist) {
if (
$macroAlreadyExist['macroInput_#index#'] === $macroName
&& $_REQUEST['macroFrom'][$index] === $macroAlreadyExist['source']
) {
/**
* if the password has not been changed, we replace the password coming from the interface with
* the original value (from the repository) before saving.
*/
$_REQUEST['macroValue'][$index] = $macroAlreadyExist['macroValue_#index#'];
}
}
}
}
// We taking into account the POST data sent from the interface
$aMacros = $serviceObj->getMacros($service_id, $aListTemplate, $cmdId);
// We hide all passwords in the jsData property to prevent them from appearing in the HTML code.
foreach ($aMacros as $index => $macroValues) {
if ($macroValues['macroPassword_#index#'] === 1) {
$macroPasswords[$index]['password'] = $aMacros[$index]['macroValue_#index#'];
// It's a password macro
$aMacros[$index]['macroOldValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
$aMacros[$index]['macroValue_#index#'] = PASSWORD_REPLACEMENT_VALUE;
// Keep the original name of the input field in case its name changes.
$aMacros[$index]['macroOriginalName_#index#'] = $aMacros[$index]['macroInput_#index#'];
}
}
}
// Preset values of macros
$cdata = CentreonData::getInstance();
$aMacros ??= [];
$cdata->addJsData('clone-values-macro', htmlspecialchars(
json_encode($aMacros),
ENT_QUOTES
));
$cdata->addJsData('clone-count-macro', count($aMacros));
// IMG comes from DB -> Store in $extImg Array
$extImg = [];
$extImg = return_image_list(1);
//
// End of "database-retrieved" information
// #########################################################
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '6'];
$attrsTextLong = ['size' => '60'];
$attrsAdvSelect_small = ['style' => 'width: 300px; height: 70px;'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 100px;'];
$attrsAdvSelect_big = ['style' => 'width: 300px; height: 200px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '40'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
// For a shitty reason, Quickform set checkbox with stal[o] name
unset($_POST['o']);
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o === SERVICE_TEMPLATE_ADD) {
$form->addElement('header', 'title', _('Add a Service Template Model'));
} elseif ($o === SERVICE_TEMPLATE_MODIFY) {
$form->addElement('header', 'title', _('Modify a Service Template Model'));
} elseif ($o === SERVICE_TEMPLATE_WATCH) {
$form->addElement('header', 'title', _('View a Service Template Model'));
} elseif ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->addElement('header', 'title', _('Mass Change'));
}
//
// # Service basic information
//
$form->addElement('header', 'information', _('General Information'));
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->addElement('text', 'service_description', _('Name'), $attrsText);
}
$form->addElement('text', 'service_alias', _('Alias'), $attrsText);
$serviceTplSelect = $form->addElement(
'select2',
'service_template_model_stm_id',
_('Template'),
[],
$attributes['templates']
);
$serviceTplSelect->addJsCallback('change', 'changeServiceTemplate(this.value)');
$form->addElement('static', 'tplText', _('Using a Template Model allows you to have multi-level Template connections'));
$form->addElement('select2', 'service_hPars', _('Host Templates'), [], $attributes['host_templates']);
//
// # Check information
//
$form->addElement('header', 'check', _('Service State'));
$checkCommandSelect = $form->addElement('select2', 'command_command_id', _('Check Command'), [], $attributes['check_commands']);
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$checkCommandSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id","example1");'
);
} else {
$checkCommandSelect->addJsCallback('change', 'changeCommand(this.value);');
}
$serviceEHE = [
$form->createElement('radio', 'service_event_handler_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_event_handler_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_event_handler_enabled', null, _('Default'), '2'),
];
$form->addGroup($serviceEHE, 'service_event_handler_enabled', _('Event Handler Enabled'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_event_handler_enabled' => '2']);
}
$eventHandlerSelect = $form->addElement('select2', 'command_command_id2', _('Event Handler'), [], $attributes['event_handlers']);
$eventHandlerSelect->addJsCallback(
'change',
'setArgument(jQuery(this).closest("form").get(0),"command_command_id2","example2");'
);
$form->addElement('text', 'command_command_id_arg2', _('Args'), $attrsTextLong);
if (! $isCloudPlatform) {
$serviceIV = [
$form->createElement('radio', 'service_is_volatile', null, _('Yes'), '1'),
$form->createElement('radio', 'service_is_volatile', null, _('No'), '0'),
$form->createElement('radio', 'service_is_volatile', null, _('Default'), '2'),
];
$form->addGroup($serviceIV, 'service_is_volatile', _('Is volatile'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_is_volatile' => '2']);
}
$serviceACE = [
$form->createElement('radio', 'service_active_checks_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_active_checks_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_active_checks_enabled', null, _('Default'), '2'),
];
$form->addGroup($serviceACE, 'service_active_checks_enabled', _('Active Checks Enabled'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_active_checks_enabled' => '2']);
}
$servicePCE = [
$form->createElement('radio', 'service_passive_checks_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_passive_checks_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_passive_checks_enabled', null, _('Default'), '2'),
];
$form->addGroup($servicePCE, 'service_passive_checks_enabled', _('Passive Checks Enabled'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_passive_checks_enabled' => '2']);
}
// Notification informations
$form->addElement('header', 'notification', _('Notification'));
$serviceNE = [
$form->createElement('radio', 'service_notifications_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_notifications_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_notifications_enabled', null, _('Default'), '2'),
];
$form->addGroup($serviceNE, 'service_notifications_enabled', _('Notification Enabled'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_notifications_enabled' => '2']);
}
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_cgs = [
$form->createElement('radio', 'mc_mod_cgs', null, _('Incremental'), '0'),
$form->createElement('radio', 'mc_mod_cgs', null, _('Replacement'), '1'),
];
$form->addGroup($mc_mod_cgs, 'mc_mod_cgs', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_cgs' => '0']);
}
// Additive
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$contactAdditive = [
$form->createElement('radio', 'mc_contact_additive_inheritance', null, _('Yes'), '1'),
$form->createElement('radio', 'mc_contact_additive_inheritance', null, _('No'), '0'),
$form->createElement(
'radio',
'mc_contact_additive_inheritance',
null,
_('Default'),
'2'
),
];
$form->addGroup($contactAdditive, 'mc_contact_additive_inheritance', _('Contact additive inheritance'), ' ');
$contactGroupAdditive = [
$form->createElement('radio', 'mc_cg_additive_inheritance', null, _('Yes'), '1'),
$form->createElement('radio', 'mc_cg_additive_inheritance', null, _('No'), '0'),
$form->createElement(
'radio',
'mc_cg_additive_inheritance',
null,
_('Default'),
'2'
),
];
$form->addGroup(
$contactGroupAdditive,
'mc_cg_additive_inheritance',
_('Contact group additive inheritance'),
' '
);
} else {
$form->addElement('checkbox', 'contact_additive_inheritance', '', _('Contact additive inheritance'));
$form->addElement('checkbox', 'cg_additive_inheritance', '', _('Contact group additive inheritance'));
}
$form->addElement('select2', 'service_cs', _('Implied Contacts'), [], $attributes['contacts']);
$form->addElement('select2', 'service_cgs', _('Implied Contact Groups'), [], $attributes['contact_groups']);
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopt_first_notification_delay = [
$form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_first_notification_delay',
null,
_('Replacement'),
'1'
),
];
$form->addGroup(
$mc_mod_notifopt_first_notification_delay,
'mc_mod_notifopt_first_notification_delay',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_first_notification_delay' => '0']);
}
$form->addElement('text', 'service_first_notification_delay', _('First notification delay'), $attrsText2);
$form->addElement('text', 'service_recovery_notification_delay', _('Recovery notification delay'), $attrsText2);
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopt_notification_interval = [
$form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_notification_interval',
null,
_('Replacement'),
'1'
),
];
$form->addGroup(
$mc_mod_notifopt_notification_interval,
'mc_mod_notifopt_notification_interval',
_('Update mode'),
' '
);
$form->setDefaults(['mc_mod_notifopt_notification_interval' => '0']);
}
$form->addElement('text', 'service_notification_interval', _('Notification Interval'), $attrsText2);
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopt_timeperiod = [
$form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Incremental'),
'0'
),
$form->createElement(
'radio',
'mc_mod_notifopt_timeperiod',
null,
_('Replacement'),
'1'
),
];
$form->addGroup($mc_mod_notifopt_timeperiod, 'mc_mod_notifopt_timeperiod', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopt_timeperiod' => '0']);
}
$form->addElement('select2', 'timeperiod_tp_id2', _('Notification Period'), [], $attributes['notification_periods']);
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_notifopts = [
$form->createElement('radio', 'mc_mod_notifopts', null, _('Incremental'), '0'),
$form->createElement('radio', 'mc_mod_notifopts', null, _('Replacement'), '1'),
];
$form->addGroup($mc_mod_notifopts, 'mc_mod_notifopts', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_notifopts' => '0']);
}
$serviceNotifOpt = [
$form->createElement(
'checkbox',
'w',
' ,',
_('Warning'),
['id' => 'notifW', 'onClick' => 'uncheckNotifOption(this),']
),
$form->createElement(
'checkbox',
'u',
' ,',
_('Unknown'),
['id' => 'notifU', 'onClick' => 'uncheckNotifOption(this),']
),
$form->createElement(
'checkbox',
'c',
' ,',
_('Critical'),
['id' => 'notifC', 'onClick' => 'uncheckNotifOption(this),']
),
$form->createElement(
'checkbox',
'r',
' ,',
_('Recovery'),
['id' => 'notifR', 'onClick' => 'uncheckNotifOption(this),']
),
$form->createElement(
'checkbox',
'f',
' ,',
_('Flapping'),
['id' => 'notifF', 'onClick' => 'uncheckNotifOption(this),']
),
$form->createElement(
'checkbox',
's',
' ,',
_('Downtime Scheduled'),
['id' => 'notifDS', 'onClick' => 'uncheckNotifOption(this),']
),
$form->createElement(
'checkbox',
'n',
' ,',
_('None'),
['id' => 'notifN', 'onClick' => 'uncheckNotifOption(this),']
),
];
$form->addGroup($serviceNotifOpt, 'service_notifOpts', _('Notification Type'), ' ');
$serviceStalOpt = [
$form->createElement('checkbox', 'o', ' ,', _('Ok')),
$form->createElement('checkbox', 'w', ' ,', _('Warning')),
$form->createElement('checkbox', 'u', ' ,', _('Unknown')),
$form->createElement('checkbox', 'c', ' ,', _('Critical')),
];
$form->addGroup($serviceStalOpt, 'service_stalOpts', _('Stalking Options'), ' ');
if ($o === SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$mc_mod_traps = [
$form->createElement('radio', 'mc_mod_traps', null, _('Incremental'), '0'),
$form->createElement('radio', 'mc_mod_traps', null, _('Replacement'), '1'),
];
$form->addGroup($mc_mod_traps, 'mc_mod_traps', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_traps' => '0']);
}
$form->addElement('header', 'traps', _('SNMP Traps'));
$form->addElement('select2', 'service_traps', _('Service Trap Relation'), [], $attributes['traps']);
$servicePC = [
$form->createElement('radio', 'service_parallelize_check', null, _('Yes'), '1'),
$form->createElement('radio', 'service_parallelize_check', null, _('No'), '0'),
$form->createElement('radio', 'service_parallelize_check', null, _('Default'), '2'),
];
$form->addGroup($servicePC, 'service_parallelize_check', _('Parallel Check'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_parallelize_check' => '2']);
}
$serviceOOS = [
$form->createElement('radio', 'service_obsess_over_service', null, _('Yes'), '1'),
$form->createElement('radio', 'service_obsess_over_service', null, _('No'), '0'),
$form->createElement('radio', 'service_obsess_over_service', null, _('Default'), '2'),
];
$form->addGroup($serviceOOS, 'service_obsess_over_service', _('Obsess Over Service'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_obsess_over_service' => '2']);
}
$serviceCF = [
$form->createElement('radio', 'service_check_freshness', null, _('Yes'), '1'),
$form->createElement('radio', 'service_check_freshness', null, _('No'), '0'),
$form->createElement('radio', 'service_check_freshness', null, _('Default'), '2'),
];
$form->addGroup($serviceCF, 'service_check_freshness', _('Check Freshness'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_check_freshness' => '2']);
}
$serviceFDE = [
$form->createElement('radio', 'service_flap_detection_enabled', null, _('Yes'), '1'),
$form->createElement('radio', 'service_flap_detection_enabled', null, _('No'), '0'),
$form->createElement('radio', 'service_flap_detection_enabled', null, _('Default'), '2'),
];
$form->addGroup($serviceFDE, 'service_flap_detection_enabled', _('Flap Detection Enabled'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_flap_detection_enabled' => '2']);
}
$form->addElement('text', 'service_freshness_threshold', _('Freshness Threshold'), $attrsText2);
$form->addElement('text', 'service_low_flap_threshold', _('Low Flap Threshold'), $attrsText2);
$form->addElement('text', 'service_high_flap_threshold', _('High Flap Threshold'), $attrsText2);
$servicePPD = [
$form->createElement('radio', 'service_process_perf_data', null, _('Yes'), '1'),
$form->createElement('radio', 'service_process_perf_data', null, _('No'), '0'),
$form->createElement('radio', 'service_process_perf_data', null, _('Default'), '2'),
];
$form->addGroup($servicePPD, 'service_process_perf_data', _('Process Perf Data'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_process_perf_data' => '2']);
}
$serviceRSI = [
$form->createElement('radio', 'service_retain_status_information', null, _('Yes'), '1'),
$form->createElement('radio', 'service_retain_status_information', null, _('No'), '0'),
$form->createElement('radio', 'service_retain_status_information', null, _('Default'), '2'),
];
$form->addGroup($serviceRSI, 'service_retain_status_information', _('Retain Status Information'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_retain_status_information' => '2']);
}
$serviceRNI = [
$form->createElement('radio', 'service_retain_nonstatus_information', null, _('Yes'), '1'),
$form->createElement('radio', 'service_retain_nonstatus_information', null, _('No'), '0'),
$form->createElement('radio', 'service_retain_nonstatus_information', null, _('Default'), '2'),
];
$form->addGroup($serviceRNI, 'service_retain_nonstatus_information', _('Retain Non Status Information'), ' ');
if ($o !== SERVICE_TEMPLATE_MASSIVE_CHANGE) {
$form->setDefaults(['service_retain_nonstatus_information' => '2']);
}
$form->addElement('select2', 'graph_id', _('Graph Template'), [], $attributes['graph_templates']);
} else {
$form->addElement('header', 'classification', _('Classification'));
}
$form->addElement('text', 'command_command_id_arg', _('Args'), $attrsTextLong);
$form->addElement('text', 'service_max_check_attempts', _('Max Check Attempts'), $attrsText2);
$form->addElement('text', 'service_normal_check_interval', _('Normal Check Interval'), $attrsText2);
$form->addElement('text', 'service_retry_check_interval', _('Retry Check Interval'), $attrsText2);
$form->addElement('select2', 'timeperiod_tp_id', _('Check Period'), [], $attributes['check_periods']);
$cloneSetMacro = [
$form->addElement(
'text',
'macroInput[#index#]',
_('Name'),
[
'id' => 'macroInput_#index#',
'size' => 25,
]
),
$form->addElement(
'text',
'macroValue[#index#]',
_('Value'),
[
'id' => 'macroValue_#index#',
'size' => 25,
]
),
$form->addElement(
'checkbox',
'macroPassword[#index#]',
_('Password'),
null,
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/service_template_model/serviceTemplateModel.php | centreon/www/include/configuration/configObject/service_template_model/serviceTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
$service_id = filter_var(
$_GET['service_id'] ?? $_POST['service_id'] ?? null,
FILTER_VALIDATE_INT
);
if ($o == 'c' && $service_id == null) {
$o = '';
}
// Path to the configuration dir
$path = './include/configuration/configObject/service_template_model/';
$path2 = './include/configuration/configObject/service/';
// PHP functions
require_once $path2 . 'DB-Func.php';
require_once './include/common/common-Func.php';
global $isCloudPlatform;
$isCloudPlatform = isCloudPlatform();
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
$serviceObj = new CentreonService($pearDB);
$lockedElements = $serviceObj->getLockedServiceTemplates();
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
const SERVICE_TEMPLATE_ADD = 'a';
const SERVICE_TEMPLATE_WATCH = 'w';
const SERVICE_TEMPLATE_MODIFY = 'c';
const SERVICE_TEMPLATE_MASSIVE_CHANGE = 'mc';
const SERVICE_TEMPLATE_ACTIVATION = 's';
const SERVICE_TEMPLATE_MASSIVE_ACTIVATION = 'ms';
const SERVICE_TEMPLATE_DEACTIVATION = 'u';
const SERVICE_TEMPLATE_MASSIVE_DEACTIVATION = 'mu';
const SERVICE_TEMPLATE_DUPLICATION = 'm';
const SERVICE_TEMPLATE_DELETION = 'd';
switch ($o) {
case SERVICE_TEMPLATE_ADD:
case SERVICE_TEMPLATE_WATCH:
case SERVICE_TEMPLATE_MODIFY:
case SERVICE_TEMPLATE_MASSIVE_CHANGE:
require_once $path . 'formServiceTemplateModel.php';
break;
case SERVICE_TEMPLATE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceInDB($service_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceTemplateModel.php';
break;
case SERVICE_TEMPLATE_MASSIVE_ACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceTemplateModel.php';
break;
case SERVICE_TEMPLATE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceInDB($service_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceTemplateModel.php';
break;
case SERVICE_TEMPLATE_MASSIVE_DEACTIVATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableServiceInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceTemplateModel.php';
break;
case SERVICE_TEMPLATE_DUPLICATION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleServiceInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceTemplateModel.php';
break;
case SERVICE_TEMPLATE_DELETION:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteServiceTemplateByApi($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listServiceTemplateModel.php';
break;
default:
require_once $path . 'listServiceTemplateModel.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_dependency/listHostDependency.php | centreon/www/include/configuration/configObject/host_dependency/listHostDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*/
declare(strict_types=1);
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\ValueObjectException;
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
// Preserve and sanitize search term
$rawSearch = $_POST['searchHD'] ?? $_GET['searchHD'] ?? null;
if ($rawSearch !== null) {
// saving filters values
$search = HtmlSanitizer::createFromString((string) $rawSearch)
->removeTags()
->sanitize()
->getString();
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
// Fetch dependencies from DB with pagination
try {
$db = $pearDB;
$qb = $db->createQueryBuilder();
$qb->select('dep.dep_id', 'dep.dep_name', 'dep.dep_description')
->distinct()
->from('dependency', 'dep')
->innerJoin('dep', 'dependency_hostParent_relation', 'dhpr', 'dhpr.dependency_dep_id = dep.dep_id');
if (! $centreon->user->admin) {
$qb->innerJoin(
'dep',
"{$dbmon}.centreon_acl",
'acl',
'dhpr.host_host_id = acl.host_id'
)
->andWhere("acl.group_id IN ({$acl->getAccessGroupsString()})");
}
$params = null;
// Search filter
if ($search !== null && $search !== '') {
$qb->andWhere(
$qb->expr()->or(
$qb->expr()->like('dep.dep_name', ':search'),
$qb->expr()->like('dep.dep_description', ':search')
)
);
$params = QueryParameters::create([QueryParameter::string('search', "%{$search}%")]);
}
// Ordering and pagination
$qb->orderBy('dep.dep_name')
->addOrderBy('dep.dep_description')
->limit($limit)
->offset($num * $limit);
$sql = $qb->getQuery();
$dependencies = $db->fetchAllAssociative($sql, $params);
// Count total for pagination
$countQueryBuilder = $db->createQueryBuilder()
->select('COUNT(DISTINCT dep.dep_id) AS total')
->from('dependency', 'dep')
->innerJoin('dep', 'dependency_hostParent_relation', 'dhpr', 'dhpr.dependency_dep_id = dep.dep_id');
if (! $centreon->user->admin) {
$countQueryBuilder->innerJoin(
'dep',
"{$dbmon}.centreon_acl",
'acl',
'dhpr.host_host_id = acl.host_id'
)
->andWhere("acl.group_id IN ({$acl->getAccessGroupsString()})");
}
if ($search !== null && $search !== '') {
$countQueryBuilder->andWhere(
$countQueryBuilder->expr()->or(
$countQueryBuilder->expr()->like('dep.dep_name', ':search'),
$countQueryBuilder->expr()->like('dep.dep_description', ':search')
)
);
}
$countSql = $countQueryBuilder->getQuery();
$countResult = $pearDB->fetchAssociative($countSql, $params);
$rows = (int) ($countResult['total'] ?? 0);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching host dependencies',
['search' => $search],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('Error while retrieving host dependencies'));
$dependencies = [];
$rows = 0;
}
// Pagination setup
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$lvlAccess = ($centreon->user->access->page($p) === 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvlAccess);
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_description', _('Description'));
$tpl->assign('headerMenu_options', _('Options'));
// Build search form & results
$searchKey = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', "?p={$p}");
$form->addElement(
'submit',
'Search',
_('Search'),
[
'class' => 'btc bt_success',
'onClick' => "window.history.replaceState('', '', '?p={$p}');",
]
);
$elemArr = [];
$style = 'one';
foreach ($dependencies as $dep) {
$depId = (int) $dep['dep_id'];
$checkbox = $form->addElement('checkbox', "select[{$depId}]");
$dupInput = sprintf(
'<input onKeypress="if(event.keyCode>31&&(event.keyCode<45||event.keyCode>57))event.returnValue=false;if(event.which>31&&(event.which<45||event.which>57))return false;" maxlength="3" size="3" value="1" style="margin-bottom:0;" name="dupNbr[%d]"/>',
$depId
);
$elemArr[] = [
'MenuClass' => "list_{$style}",
'RowMenu_select' => $checkbox->toHtml(),
'RowMenu_name' => CentreonUtils::escapeSecure(myDecode((string) $dep['dep_name'])),
'RowMenu_description' => CentreonUtils::escapeSecure(myDecode((string) $dep['dep_description'])),
'RowMenu_link' => "main.php?p={$p}&o=c&dep_id={$depId}",
'RowMenu_options' => $dupInput,
];
$style = ($style === 'one') ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign('msg', [
'addL' => "main.php?p={$p}&o=a",
'addT' => _('Add'),
'delConfirm' => _('Do you confirm the deletion ?'),
]);
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchHD', $searchKey);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listHostDependency.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_dependency/help.php | centreon/www/include/configuration/configObject/host_dependency/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['name'] = dgettext('help', 'Define a short name for this dependency.');
$help['description'] = dgettext(
'help',
'Define a description for this dependency for easier identification and differentiation.'
);
$help['inherits_parent'] = sprintf(
"%s<br/><font color='red'><b><i>%s</i></b></font>",
dgettext(
'help',
'This directive indicates whether or not the dependency inherits dependencies of the host that is '
. 'being depended upon (also referred to as the master host). In other words, if the master host is '
. 'dependent upon other hosts and any one of those dependencies fail, this dependency will also fail.'
),
dgettext('help', 'Ignored by Centreon Engine.')
);
$help['execution_failure_criteria'] = dgettext(
'help',
'This directive is used to specify the criteria that determine when the dependent host should not be '
. 'actively checked. If the master host is in one of the failure states we specify, the dependent host '
. 'will not be actively checked. If you specify None as an option, the execution dependency will never '
. 'fail and the dependent host will always be actively checked (if other conditions allow for it to be).'
);
$help['notification_failure_criteria'] = dgettext(
'help',
'This directive is used to define the criteria that determine when notifications for the dependent host '
. 'should not be sent out. If the master host is in one of the failure states we specify, '
. 'notifications for the dependent host will not be sent to contacts. If you specify None as an option, '
. 'the notification dependency will never fail and notifications for the dependent host will always be sent out.'
);
$help['host_name'] = dgettext(
'help',
'This directive is used to identify the short name(s) of the host(s) that is being depended upon '
. '(also referred to as the master host).'
);
$help['hostgroup_name'] = dgettext(
'help',
'This directive is used to identify the short name(s) of the hostgroup(s) that is being depended upon '
. '(also referred to as the master host). The hostgroup_name may be used instead of, or in addition to, '
. 'the host_name directive.'
);
$help['dependent_host_name'] = dgettext('help', 'This directive is used to identify the dependent host(s).');
$help['dependent_hostgroup_name'] = dgettext(
'help',
'This directive is used to identify the short name(s) of the dependent hostgroup(s). '
. 'The dependent_hostgroup_name may be used instead of, or in addition to, the dependent_host_name directive.'
);
// unsupported in centreon
$help['dependency_period'] = dgettext(
'help',
'This directive is used to specify the short name of the time period during which this dependency is valid. '
. 'If this directive is not specified, the dependency is considered to be valid during all times.'
);
$help['dep_hSvChi'] = sprintf(
"%s<br/><font color='red'><b><i>%s</i></b></font>",
dgettext('help', 'This directive is used to identify the description of the dependent service.'),
dgettext('help', 'Compatible with Centreon Broker only.')
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_dependency/formHostDependency.php | centreon/www/include/configuration/configObject/host_dependency/formHostDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*/
declare(strict_types=1);
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\ValueObjectException;
if (! isset($centreon)) {
exit();
}
$dep = [];
$childServices = [];
$initialValues = [];
// Fetch existing dependency for modify or view
if (in_array($o, [MODIFY_DEPENDENCY, WATCH_DEPENDENCY], true) && $dep_id) {
try {
$queryBuilder = $pearDB->createQueryBuilder();
$queryBuilder->select('*')
->from('dependency', 'dep')
->where('dep.dep_id = :depId')
->limit(1);
$sql = $queryBuilder->getQuery();
$result = $pearDB->fetchAssociative($sql, QueryParameters::create([QueryParameter::int('depId', $dep_id)]));
if ($result === false) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Dependency not found',
['depId' => $dep_id]
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Dependency not found');
}
// Set base value
$dep = $result !== false ? array_map('myDecode', $result) : [];
// Set Notification Failure Criteria
$dep['notification_failure_criteria'] = explode(',', $dep['notification_failure_criteria']);
foreach ($dep['notification_failure_criteria'] as $key => $value) {
$dep['notification_failure_criteria'][trim($value)] = 1;
}
// Set Execution Failure Criteria
$dep['execution_failure_criteria'] = explode(',', $dep['execution_failure_criteria']);
foreach ($dep['execution_failure_criteria'] as $key => $value) {
$dep['execution_failure_criteria'][trim($value)] = 1;
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error retrieving dependency: ' . $exception->getMessage(),
['depId' => $dep_id],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error loading dependency ' . $dep_id);
$dep = [];
}
}
// Form attributes
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '10'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 150px;'];
$attrsTextarea = ['rows' => '3', 'cols' => '30'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
// AJAX datasource routes
$hostRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&action=list';
$serviceRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list';
$attrHosts = [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $hostRoute,
'multiple' => true,
'linkedObject' => 'centreonHost',
];
$attrServices = [
'datasourceOrigin' => 'ajax',
'availableDatasetRoute' => $serviceRoute,
'multiple' => true,
'linkedObject' => 'centreonService',
];
// Build form
$form = new HTML_QuickFormCustom('Form', 'post', "?p={$p}");
// Header
switch ($o) {
case ADD_DEPENDENCY:
$form->addElement('header', 'title', _('Add a Dependency'));
break;
case MODIFY_DEPENDENCY:
$form->addElement('header', 'title', _('Modify a Dependency'));
break;
case WATCH_DEPENDENCY:
$form->addElement('header', 'title', _('View a Dependency'));
break;
}
// Information section
$form->addElement('header', 'information', _('Information'));
$form->addElement('text', 'dep_name', _('Name'), $attrsText);
$form->addElement('text', 'dep_description', _('Description'), $attrsText);
// Parent relationship radios
$radios = [
$form->createElement('radio', 'inherits_parent', null, _('Yes'), '1'),
$form->createElement('radio', 'inherits_parent', null, _('No'), '0'),
];
$form->addGroup($radios, 'inherits_parent', _('Parent relationship'), ' ');
$form->setDefaults(['inherits_parent' => '1']);
// Notification criteria checkboxes
$notifIds = [
'o' => ['nUp', 'Ok/Up'],
'd' => ['nDown', 'Down'],
'u' => ['nUnreachable', 'Unreachable'],
'p' => ['nPending', 'Pending'],
'n' => ['nNone', 'None'],
];
$notif = [];
foreach ($notifIds as $key => $values) {
$notif[] = $form->createElement(
'checkbox',
$key,
' ',
_($values[1]),
['id' => $values[0], 'onClick' => 'applyNotificationRules(this);']
);
}
$form->addGroup($notif, 'notification_failure_criteria', _('Notification Failure Criteria'), ' ');
// Execution criteria checkboxes
$execIds = [
'o' => ['eUp', 'Up'],
'd' => ['eDown', 'Down'],
'u' => ['eUnreachable', 'Unreachable'],
'p' => ['ePending', 'Pending'],
'n' => ['eNone', 'None'],
];
$exec = [];
foreach ($execIds as $key => $values) {
$exec[] = $form->createElement(
'checkbox',
$key,
' ',
_($values[1]),
['id' => $values[0], 'onClick' => 'applyExecutionRules(this);']
);
}
$form->addGroup($exec, 'execution_failure_criteria', _('Execution Failure Criteria'), ' ');
// Hosts and services multi-selects with default values
$hostDefaultsRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host'
. '&action=defaultValues&target=dependency&field=dep_hostParents&id=' . $dep_id;
$form->addElement(
'select2',
'dep_hostParents',
_('Host Names'),
[],
array_merge($attrHosts, ['defaultDatasetRoute' => $hostDefaultsRoute])
);
$childDefaultsRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&action=defaultValues&target=dependency&field=dep_hostChilds&id=' . $dep_id;
$form->addElement(
'select2',
'dep_hostChilds',
_('Dependent Host Names'),
[],
array_merge($attrHosts, ['defaultDatasetRoute' => $childDefaultsRoute])
);
$serviceDefaultsRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=defaultValues&target=dependency&field=dep_hSvChi&id=' . $dep_id;
$form->addElement(
'select2',
'dep_hSvChi',
_('Dependent Services'),
[],
array_merge($attrServices, ['defaultDatasetRoute' => $serviceDefaultsRoute])
);
$form->addElement('textarea', 'dep_comment', _('Comments'), $attrsTextarea);
$form->addElement('hidden', 'dep_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
// Validation rules
$form->applyFilter('__ALL__', 'myTrim');
$form->registerRule('sanitize', 'callback', 'isNotEmptyAfterStringSanitize');
$form->addRule('dep_name', _('Compulsory Name'), 'required');
$form->addRule('dep_name', _('Unauthorized value'), 'sanitize');
$form->addRule('dep_description', _('Required Field'), 'required');
$form->addRule('dep_description', _('Unauthorized value'), 'sanitize');
$form->addRule('dep_hostParents', _('Required Field'), 'required');
$form->registerRule('cycle', 'callback', 'testHostDependencyCycle');
$form->addRule('dep_hostChilds', _('Circular Definition'), 'cycle');
$form->registerRule('exist', 'callback', 'testHostDependencyExistence');
$form->addRule('dep_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
$form->addRule('execution_failure_criteria', _('Required Field'), 'required');
$form->addRule('notification_failure_criteria', _('Required Field'), 'required');
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, '
. '"orange", TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], '
. 'WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= "<span style='display:none' id='help:{$key}'>{$text}</span>\n";
}
$tpl->assign('helptext', $helptext);
// View/Modify/Add buttons and defaults
if ($o == WATCH_DEPENDENCY) {
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p={$p}&o=c&dep_id={$dep_id}'"]
);
}
$form->setDefaults($dep);
$form->freeze();
} elseif ($o == MODIFY_DEPENDENCY) {
$form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($dep);
} elseif ($o == ADD_DEPENDENCY) {
$form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults(['inherits_parent' => '0']);
}
$tpl->assign('nagios', $oreon->user->get_version());
// Process submission
if ($form->validate()) {
try {
$depObj = $form->getElement('dep_id');
if ($form->getSubmitValue('submitA')) {
$depObj->setValue(insertHostDependencyInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateHostDependencyInDB((int) $depObj->getValue());
}
require_once 'listHostDependency.php';
return;
} catch (CentreonException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error processing host dependancy form: ' . $exception->getMessage(),
['depId' => (int) $depObj->getValue()],
$exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error processing host dependancy form');
$o = null;
}
}
// Render form
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formHostDependency.ihtml');
?>
<script type="text/javascript">
function applyNotificationRules(object) {
if (object.id == "nNone" && object.checked) {
document.getElementById('nUp').checked = false;
document.getElementById('nDown').checked = false;
document.getElementById('nUnreachable').checked = false;
document.getElementById('nPending').checked = false;
}
else {
document.getElementById('nNone').checked = false;
}
}
function applyExecutionRules(object) {
if (object.id === "eNone" && object.checked) {
document.getElementById('eUp').checked = false;
document.getElementById('eDown').checked = false;
document.getElementById('eUnreachable').checked = false;
document.getElementById('ePending').checked = false;
}
else {
document.getElementById('eNone').checked = false;
}
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_dependency/hostDependency.php | centreon/www/include/configuration/configObject/host_dependency/hostDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
const ADD_DEPENDENCY = 'a';
const WATCH_DEPENDENCY = 'w';
const MODIFY_DEPENDENCY = 'c';
const DUPLICATE_DEPENDENCY = 'm';
const DELETE_DEPENDENCY = 'd';
// Path to the configuration dir
$path = './include/configuration/configObject/host_dependency/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
use Core\Common\Domain\Exception\RepositoryException;
$dep_id = filter_var(
$_GET['dep_id'] ?? $_POST['dep_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $centreon->user->access;
$dbmon = $acl->getNameDBAcl();
try {
switch ($o) {
case ADD_DEPENDENCY:
case WATCH_DEPENDENCY:
case MODIFY_DEPENDENCY:
require_once $path . 'formHostDependency.php';
break;
case DUPLICATE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleHostDependencyInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostDependency.php';
break;
case DELETE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteHostDependencyInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listHostDependency.php';
break;
default:
require_once $path . 'listHostDependency.php';
break;
}
} catch (RepositoryException $exception) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while processing host dependencies: ' . $exception->getMessage(),
exception: $exception
);
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText('Error while processing host dependencies');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/host_dependency/DB-Func.php | centreon/www/include/configuration/configObject/host_dependency/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
if (! isset($centreon)) {
exit();
}
function testHostDependencyExistence(?string $name): bool
{
global $pearDB, $form;
try {
CentreonDependency::purgeObsoleteDependencies($pearDB);
$queryBuilder = $pearDB->createQueryBuilder();
$sql = $queryBuilder
->select('dep_id')
->from('dependency')
->where('dep_name = :name')
->getQuery();
$params = QueryParameters::create([
QueryParameter::string('name', (string) $name),
]);
$row = $pearDB->fetchAssociative($sql, $params);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error testing host dependency existence',
['dep_name' => $name],
$exception
);
}
$currentId = $form?->getSubmitValue('dep_id');
if ($row) {
return (int) $row['dep_id'] === (int) $currentId;
}
return true;
}
function testHostDependencyCycle($childs = null): bool
{
global $form;
$parents = [];
$childsMap = [];
if (isset($form)) {
$parents = $form->getSubmitValue('dep_hostParents') ?? [];
$childs = $form->getSubmitValue('dep_hostChilds') ?? [];
$childsMap = array_flip(array_map('intval', $childs));
}
foreach ($parents as $parent) {
if (isset($childsMap[(int) $parent])) {
return false;
}
}
return true;
}
function deleteHostDependencyInDB(array $dependencies = []): void
{
global $pearDB, $centreon;
foreach ($dependencies as $depId => $_) {
try {
// fetch name
$sqlSel = $pearDB->createQueryBuilder()
->select('dep_name')
->from('dependency')
->where('dep_id = :id')
->limit(1)
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('id', (int) $depId),
]);
$row = $pearDB->fetchAssociative($sqlSel, $params);
if (! $row) {
// nothing to delete
continue;
}
// delete record
$sqlDel = $pearDB->createQueryBuilder()
->delete('dependency')
->where('dep_id = :id')
->getQuery();
$pearDB->delete($sqlDel, $params);
// log deletion
$centreon->CentreonLogAction->insertLog(
'host dependency',
(int) $depId,
$row['dep_name'] ?? '',
'd'
);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error deleting host dependency',
['dep_id' => $depId],
$exception
);
}
}
}
function multipleHostDependencyInDB(array $dependencies = [], array $nbrDup = []): void
{
global $pearDB, $centreon;
foreach ($dependencies as $depId => $_) {
try {
$pearDB->beginTransaction();
// fetch original dependency row
$sqlSel = $pearDB->createQueryBuilder()
->select('*')
->from('dependency')
->where('dep_id = :id')
->limit(1)
->getQuery();
$params = QueryParameters::create([
QueryParameter::int('id', (int) $depId),
]);
$original = $pearDB->fetchAssociative($sqlSel, $params);
if (! $original) {
continue;
}
unset($original['dep_id']);
// duplicate as many times as requested
$count = $nbrDup[$depId] ?? 0;
for ($i = 1; $i <= $count; $i++) {
$dup = $original;
$dupName = $dup['dep_name'] . "_{$i}";
$dup['dep_name'] = HtmlSanitizer::createFromString($dupName)
->removeTags()
->sanitize()
->getString();
if (! testHostDependencyExistence($dup['dep_name'])) {
continue;
}
// insert duplicated dependency
$cols = array_keys($dup);
$sqlIns = $pearDB->createQueryBuilder()
->insert('dependency')
->values(array_combine(
$cols,
array_map(fn ($c) => ':' . $c, $cols)
))
->getQuery();
$insParams = QueryParameters::create(
array_map(fn ($c) => QueryParameter::string($c, (string) $dup[$c]), $cols)
);
$pearDB->insert($sqlIns, $insParams);
$newId = (int) $pearDB->getLastInsertId();
// duplicate relations
foreach ([
'dependency_hostParent_relation',
'dependency_hostChild_relation',
'dependency_serviceChild_relation',
] as $table) {
// No need of Distinct here, as we are sure that the relation is unique
$sqlRelSel = $pearDB->createQueryBuilder()
->select('*')
->from($table)
->where('dependency_dep_id = :id')
->getQuery();
$rels = $pearDB->fetchAllAssociative($sqlRelSel, $params);
foreach ($rels as $rowRel) {
$fields = array_keys($rowRel);
$sqlRelIns = $pearDB->createQueryBuilder()
->insert($table)
->values(array_combine(
$fields,
array_map(fn ($c) => ':' . $c, $fields)
))
->getQuery();
$relParams = QueryParameters::create(
array_map(
fn ($c) => QueryParameter::int(
$c,
$c === 'dependency_dep_id' ? $newId : (int) $rowRel[$c]
),
$fields
)
);
$pearDB->insert($sqlRelIns, $relParams);
}
}
$centreon->CentreonLogAction->insertLog(
'host dependency',
$newId,
$dupName,
'a',
$fields
);
}
$pearDB->commit();
} catch (ValueObjectException|CollectionException|ConnectionException|RepositoryException $exception) {
$pearDB->rollBack();
throw new RepositoryException(
'Error duplicating host dependency',
['dep_id' => $depId],
$exception
);
}
}
}
/**
* Create a host dependency
*
* @param array<string, mixed> $ret
* @return int
*/
function insertHostDependency(array $data = []): int
{
global $form, $pearDB, $centreon;
try {
$values = sanitizeResourceParameters($data ?: $form->getSubmitValues());
$queryBuilderIns = $pearDB->createQueryBuilder();
$ins = $queryBuilderIns
->insert('dependency')
->values([
'dep_name' => ':depName',
'dep_description' => ':depDesc',
'inherits_parent' => ':inherits',
'execution_failure_criteria' => ':exeFail',
'notification_failure_criteria' => ':notFail',
'dep_comment' => ':comment',
])
->getQuery();
$params = QueryParameters::create([
QueryParameter::string('depName', $values['dep_name']),
QueryParameter::string('depDesc', $values['dep_description']),
QueryParameter::string('inherits', $values['inherits_parent']),
QueryParameter::string('exeFail', $values['execution_failure_criteria'] ?? null),
QueryParameter::string('notFail', $values['notification_failure_criteria'] ?? null),
QueryParameter::string('comment', $values['dep_comment']),
]);
$pearDB->insert($ins, $params);
$id = (int) $pearDB->getLastInsertId();
$centreon->CentreonLogAction->insertLog(
'host dependency',
$id,
$values['dep_name'],
'a',
CentreonLogAction::prepareChanges($values)
);
return $id;
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error inserting host dependency',
['data' => $data],
$exception
);
}
}
/**
* Update a host dependency
*
* @param null|int $depId
*/
function updateHostDependency(int $depId): void
{
global $form, $pearDB, $centreon;
try {
$values = sanitizeResourceParameters($form->getSubmitValues());
$queryBuilderUpdate = $pearDB->createQueryBuilder();
$update = $queryBuilderUpdate
->update('dependency')
->set('dep_name', ':depName')
->set('dep_description', ':depDesc')
->set('inherits_parent', ':inherits')
->set('execution_failure_criteria', ':exeFail')
->set('notification_failure_criteria', ':notFail')
->set('dep_comment', ':comment')
->where('dep_id = :depId')
->getQuery();
$params = QueryParameters::create([
QueryParameter::string('depName', $values['dep_name']),
QueryParameter::string('depDesc', $values['dep_description']),
QueryParameter::string('inherits', $values['inherits_parent']),
QueryParameter::string('exeFail', $values['execution_failure_criteria'] ?? null),
QueryParameter::string('notFail', $values['notification_failure_criteria'] ?? null),
QueryParameter::string('comment', $values['dep_comment']),
QueryParameter::int('depId', $depId),
]);
$pearDB->update($update, $params);
$centreon->CentreonLogAction->insertLog(
'host dependency',
$depId,
$values['dep_name'] ?? '',
'c',
CentreonLogAction::prepareChanges($values)
);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error updating host dependency',
['dep_id' => $depId],
$exception
);
}
}
/**
* sanitize resources parameter for Create / Update a host dependency
*
* @param array<string, mixed> $resources
* @return array<string, mixed>
*/
function sanitizeResourceParameters(array $resources): array
{
$sanitizedParameters = [];
$sanitizedParameters['dep_name'] = HtmlSanitizer::createFromString(($resources['dep_name'] ?? ''))
->removeTags()->sanitize()->getString();
if ($sanitizedParameters['dep_name'] === '') {
throw new RepositoryException(_("Dependency name can't be empty"));
}
$sanitizedParameters['dep_description'] = HtmlSanitizer::createFromString(($resources['dep_description'] ?? ''))
->removeTags()->sanitize()->getString();
if ($sanitizedParameters['dep_description'] === '') {
throw new RepositoryException(_("Dependency description can't be empty"));
}
$sanitizedParameters['inherits_parent'] = $resources['inherits_parent']['inherits_parent'] == 1 ? '1' : '0';
if (! empty($resources['execution_failure_criteria']) && is_array($resources['execution_failure_criteria'])) {
$sanitizedParameters['execution_failure_criteria'] = HtmlSanitizer::createFromString(
implode(',', array_keys($resources['execution_failure_criteria']))
)->removeTags()->sanitize()->getString();
}
if (! empty($resources['notification_failure_criteria']) && is_array($resources['notification_failure_criteria'])) {
$sanitizedParameters['notification_failure_criteria'] = HtmlSanitizer::createFromString(
implode(',', array_keys($resources['notification_failure_criteria']))
)->removeTags()->sanitize()->getString();
}
$sanitizedParameters['dep_comment'] = HtmlSanitizer::createFromString(($resources['dep_comment'] ?? ''))
->removeTags()->sanitize()->getString();
return $sanitizedParameters;
}
function updateHostDependencyHostParents(int $depId, array $list = []): void
{
global $pearDB, $form;
try {
$del = $pearDB->createQueryBuilder()
->delete('dependency_hostParent_relation')
->where('dependency_dep_id = :id')
->getQuery();
$pearDB->delete($del, QueryParameters::create([QueryParameter::int('id', $depId)]));
$items = $list['dep_hostParents'] ?? CentreonUtils::mergeWithInitialValues($form, 'dep_hostParents');
foreach ($items as $host) {
$ins = $pearDB->createQueryBuilder()
->insert('dependency_hostParent_relation')
->values([
'dependency_dep_id' => ':id',
'host_host_id' => ':host',
])
->getQuery();
$pearDB->insert($ins, QueryParameters::create([
QueryParameter::int('id', $depId),
QueryParameter::int('host', (int) $host),
]));
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error updating host dependency parents',
['dep_id' => $depId],
$exception
);
}
}
function updateHostDependencyHostChilds(int $depId, array $list = []): void
{
global $form, $pearDB;
try {
$del = $pearDB->createQueryBuilder()
->delete('dependency_hostChild_relation')
->where('dependency_dep_id = :id')
->getQuery();
$pearDB->delete($del, QueryParameters::create([QueryParameter::int('id', $depId)]));
$items = $list['dep_hostChilds'] ?? CentreonUtils::mergeWithInitialValues($form, 'dep_hostChilds');
foreach ($items as $host) {
$ins = $pearDB->createQueryBuilder()
->insert('dependency_hostChild_relation')
->values([
'dependency_dep_id' => ':id',
'host_host_id' => ':host',
])
->getQuery();
$pearDB->insert($ins, QueryParameters::create([
QueryParameter::int('id', $depId),
QueryParameter::int('host', (int) $host),
]));
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error updating host dependency childs',
['dep_id' => $depId],
$exception
);
}
}
function updateHostDependencyServiceChildren(int $dep_id, array $list = []): void
{
global $form, $pearDB;
try {
$del = $pearDB->createQueryBuilder()
->delete('dependency_serviceChild_relation')
->where('dependency_dep_id = :id')
->getQuery();
$pearDB->delete($del, QueryParameters::create([QueryParameter::int('id', $dep_id)]));
$items = $list['dep_hSvChi'] ?? CentreonUtils::mergeWithInitialValues($form, 'dep_hSvChi');
foreach ($items as $item) {
[$host, $service] = explode('-', $item) + [null, null];
if ($host !== null && $service !== null) {
$ins = $pearDB->createQueryBuilder()
->insert('dependency_serviceChild_relation')
->values([
'dependency_dep_id' => ':id',
'service_service_id' => ':service',
'host_host_id' => ':host',
])
->getQuery();
$pearDB->insert($ins, QueryParameters::create([
QueryParameter::int('id', $dep_id),
QueryParameter::int('service', (int) $service),
QueryParameter::int('host', (int) $host),
]));
}
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
'Error updating host dependency service children',
['dep_id' => $dep_id],
$exception
);
}
}
function insertHostDependencyInDB(array $data = []): int
{
$id = insertHostDependency($data);
updateHostDependencyHostParents($id, $data);
updateHostDependencyHostChilds($id, $data);
updateHostDependencyServiceChildren($id, $data);
return $id;
}
function updateHostDependencyInDB(int $id): void
{
updateHostDependency($id);
updateHostDependencyHostParents($id);
updateHostDependencyHostChilds($id);
updateHostDependencyServiceChildren($id);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact_template_model/listContactTemplateModel.php | centreon/www/include/configuration/configObject/contact_template_model/listContactTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
$contactTypeIcone = [1 => returnSvg('www/img/icons/admin.svg', 'var(--icons-fill-color)', 22, 22), 2 => returnSvg('www/img/icons/user.svg', 'var(--icons-fill-color)', 22, 22), 3 => returnSvg('www/img/icons/user-template.svg', 'var(--icons-fill-color)', 22, 22)];
// Create Timeperiod Cache
$tpCache = ['' => ''];
$dbResult = $pearDB->query('SELECT tp_name, tp_id FROM timeperiod');
while ($data = $dbResult->fetch()) {
$tpCache[$data['tp_id']] = $data['tp_name'];
}
unset($data);
$dbResult->closeCursor();
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchCT'] ?? $_GET['searchCT'] ?? null
);
if (isset($_POST['searchCT']) || isset($_GET['searchCT'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$clauses = [];
if ($search) {
$clauses = ['contact_name' => '%' . $search . '%'];
}
$fields = ['contact_id', 'contact_name', 'contact_alias', 'timeperiod_tp_id', 'timeperiod_tp_id2', 'contact_activate'];
$contacts = $contactObj->getContactTemplates(
$fields,
$clauses,
['contact_name', 'ASC'],
[($num * $limit), $limit]
);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Full Name'));
$tpl->assign('headerMenu_desc', _('Alias / Login'));
$tpl->assign('headerMenu_email', _('Email'));
$tpl->assign('headerMenu_hostNotif', _('Host Notification Period'));
$tpl->assign('headerMenu_svNotif', _('Services Notification Period'));
$tpl->assign('headerMenu_lang', _('Language'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_access', _('Access'));
$tpl->assign('headerMenu_admin', _('Admin'));
$tpl->assign('headerMenu_options', _('Options'));
// Contact list
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
foreach ($contacts as $contact) {
$selectedElements = $form->addElement('checkbox', 'select[' . $contact['contact_id'] . ']');
$moptions = '';
if ($contact['contact_id'] != $centreon->user->get_id()) {
if ($contact['contact_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&contact_id=' . $contact['contact_id']
. '&o=u&limit=' . $limit . '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Disabled') . "'></a> ";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&contact_id=' . $contact['contact_id']
. '&o=s&limit=' . $limit . '&num=' . $num . '&search=' . $search . '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Enabled') . "'></a> ";
}
} else {
$moptions .= ' ';
}
$moptions .= ' ';
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr["
. $contact['contact_id'] . "]' />";
$contact_type = 0;
if (isset($contact['contact_register']) && $contact['contact_register']) {
$contact_type = $contact['contact_admin'] == 1 ? 1 : 2;
} else {
$contact_type = 3;
}
$elemArr[] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => html_entity_decode($contact['contact_name'], ENT_QUOTES, 'UTF-8'), 'RowMenu_ico' => $contactTypeIcone[$contact_type] ?? '', 'RowMenu_ico_title' => _('This is a contact template.'), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&contact_id=' . $contact['contact_id'], 'RowMenu_desc' => CentreonUtils::escapeSecure(
html_entity_decode(
$contact['contact_alias'],
ENT_QUOTES,
'UTF-8'
)
), 'RowMenu_hostNotif' => html_entity_decode($tpCache[($contact['timeperiod_tp_id'] ?? '')], ENT_QUOTES, 'UTF-8') . ' ('
. ($contact['contact_host_notification_options'] ?? '') . ')', 'RowMenu_svNotif' => html_entity_decode($tpCache[($contact['timeperiod_tp_id2'] ?? '')], ENT_QUOTES, 'UTF-8') . ' ('
. ($contact['contact_service_notification_options'] ?? '') . ')', 'RowMenu_status' => $contact['contact_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $contact['contact_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign('msg', ['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add')]);
if ($centreon->optGen['ldap_auth_enable']) {
$tpl->assign('ldap', $centreon->optGen['ldap_auth_enable']);
}
// Toolbar select
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3 || this.form.elements['o1'].selectedIndex == 4 ||"
. "this.form.elements['o1'].selectedIndex == 5){"
. " setO(this.form.elements['o1'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change'), 'ms' => _('Enable'), 'mu' => _('Disable')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3 || this.form.elements['o2'].selectedIndex == 4 ||"
. "this.form.elements['o2'].selectedIndex == 5){"
. " setO(this.form.elements['o2'].value); submit();} "
. "this.form.elements['o1'].selectedIndex = 0"];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change'), 'ms' => _('Enable'), 'mu' => _('Disable')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchCT', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listContactTemplateModel.ihtml');
?>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact_template_model/contact_template.php | centreon/www/include/configuration/configObject/contact_template_model/contact_template.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Infrastructure\Event\EventDispatcher;
use Centreon\Infrastructure\Event\EventHandler;
use Centreon\ServiceProvider;
if (! isset($centreon)) {
exit();
}
$cG = array_key_exists('contact_id', $_GET) && $_GET['contact_id'] !== null
? HtmlSanitizer::createFromString($_GET['contact_id'])->sanitize()->getString()
: null;
$cP = array_key_exists('contact_id', $_POST) && $_POST['contact_id'] !== null
? HtmlSanitizer::createFromString($_POST['contact_id'])->sanitize()->getString()
: null;
$contact_id = $cG ?: $cP;
$cG = array_key_exists('select', $_GET) && $_GET['select'] !== null
? validateInput($_GET['select'])
: null;
$cP = array_key_exists('select', $_POST) && $_POST['select'] !== null
? validateInput($_POST['select'])
: null;
$select = $cG ?: $cP;
$cG = array_key_exists('dupNbr', $_GET) && $_GET['dupNbr'] !== null
? validateInput($_GET['dupNbr'])
: null;
$cP = array_key_exists('dupNbr', $_POST) && $_POST['dupNbr'] !== null
? validateInput($_POST['dupNbr'])
: null;
$dupNbr = $cG ?: $cP;
function validateInput(array|string $inputs): array
{
if (is_string($inputs)) {
$inputs = explode(',', trim($inputs, ','));
}
foreach ($inputs as $contactTemplateId => $value) {
if (
filter_var($contactTemplateId, FILTER_VALIDATE_INT) !== false
&& filter_var($value, FILTER_VALIDATE_INT) !== false
) {
continue;
}
throw new Exception('Invalid value supplied');
}
return $inputs;
}
// Path to the configuration dir
$path = './include/configuration/configObject/contact_template_model/';
// PHP functions
require_once './include/configuration/configObject/contact/DB-Func.php';
require_once './include/common/common-Func.php';
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$contactObj = new CentreonContact($pearDB);
/**
* @var EventDispatcher $eventDispatcher
*/
$eventDispatcher = $dependencyInjector[ServiceProvider::CENTREON_EVENT_DISPATCHER];
$eventContext = 'contact.template.form';
if (! is_null($eventDispatcher->getDispatcherLoader())) {
$eventDispatcher->getDispatcherLoader()->load();
}
$eventDispatcher->addEventHandler(
$eventContext,
EventDispatcher::EVENT_DUPLICATE,
(function (): EventHandler {
$handler = new EventHandler();
$handler->setProcessing(function (array $arguments) {
if (isset($arguments['contact_ids'], $arguments['numbers'])) {
$newContactIds = multipleContactInDB(
$arguments['contact_ids'],
$arguments['numbers']
);
// We store the result for possible future use
return ['new_contact_ids' => $newContactIds];
}
});
return $handler;
})()
);
/*
* We add the delete event in the context named 'contact.template.form' for and event type
* EventDispatcher::EVENT_DELETE
*/
$eventDispatcher->addEventHandler(
$eventContext,
EventDispatcher::EVENT_DELETE,
(function () {
// We define an event to delete a list of contacts
$handler = new EventHandler();
$handler->setProcessing(function ($arguments): void {
if (isset($arguments['contact_ids'])) {
deleteContactInDB($arguments['contact_ids']);
}
});
return $handler;
})()
);
switch ($o) {
case 'mc':
require_once $path . 'formContactTemplateModel.php';
break; // Massive Change
case 'a':
require_once $path . 'formContactTemplateModel.php';
break; // Add a contact template
case 'w':
require_once $path . 'formContactTemplateModel.php';
break; // Watch a contact template
case 'c':
require_once $path . 'formContactTemplateModel.php';
break; // Modify a contact template
case 's':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableContactInDB($contact_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactTemplateModel.php';
break; // Activate a contact template
case 'ms':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
enableContactInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactTemplateModel.php';
break;
case 'u':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableContactInDB($contact_id);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactTemplateModel.php';
break; // Desactivate a contact
case 'mu':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
disableContactInDB(null, $select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactTemplateModel.php';
break;
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
// We notify that we have made a duplicate
$eventDispatcher->notify(
$eventContext,
EventDispatcher::EVENT_DUPLICATE,
[
'contact_ids' => $select ?? [],
'numbers' => $dupNbr,
]
);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactTemplateModel.php';
break; // Duplicate n contacts
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
// We notify that we have made a delete
$eventDispatcher->notify(
$eventContext,
EventDispatcher::EVENT_DELETE,
['contact_ids' => $select ?? []]
);
} else {
unvalidFormMessage();
}
require_once $path . 'listContactTemplateModel.php';
break; // Delete n contacts
default:
require_once $path . 'listContactTemplateModel.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact_template_model/formContactTemplateModel.php | centreon/www/include/configuration/configObject/contact_template_model/formContactTemplateModel.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Centreon\Infrastructure\Event\EventDispatcher;
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
$cct = [];
if (($o == 'c' || $o == 'w') && $contact_id) {
/**
* Init Tables informations
*/
$cct['contact_hostNotifCmds'] = [];
$cct['contact_svNotifCmds'] = [];
$cct['contact_cgNotif'] = [];
$statement = $pearDB->prepare('SELECT * FROM contact WHERE contact_id = :contactId LIMIT 1');
$statement->bindValue(':contactId', $contact_id, PDO::PARAM_INT);
$statement->execute();
$cct = array_map('myDecode', $statement->fetchRow());
$statement->closeCursor();
/**
* Set Host Notification Options
*/
$tmp = explode(',', $cct['contact_host_notification_options']);
foreach ($tmp as $key => $value) {
$cct['contact_hostNotifOpts'][trim($value)] = 1;
}
/**
* Set Service Notification Options
*/
$tmp = explode(',', $cct['contact_service_notification_options']);
foreach ($tmp as $key => $value) {
$cct['contact_svNotifOpts'][trim($value)] = 1;
}
/**
* Set Host Notification Commands
*/
$statement = $pearDB->prepare(
<<<'SQL'
SELECT DISTINCT command_command_id FROM contact_hostcommands_relation
WHERE contact_contact_id = :contactId
SQL
);
$statement->bindValue(':contactId', $contact_id, PDO::PARAM_INT);
$statement->execute();
for ($i = 0; $notifCmd = $statement->fetchRow(); $i++) {
$cct['contact_hostNotifCmds'][$i] = $notifCmd['command_command_id'];
}
$statement->closeCursor();
/**
* Set Service Notification Commands
*/
$statement = $pearDB->prepare(
<<<'SQL'
SELECT DISTINCT command_command_id FROM contact_servicecommands_relation
WHERE contact_contact_id = :contactId
SQL
);
$statement->bindValue(':contactId', $contact_id, PDO::PARAM_INT);
$statement->execute();
for ($i = 0; $notifCmd = $statement->fetchRow(); $i++) {
$cct['contact_svNotifCmds'][$i] = $notifCmd['command_command_id'];
}
$statement->closeCursor();
}
/**
* Get Langs
*/
$langs = [];
$langs = getLangs();
if ($o == 'mc') {
array_unshift($langs, null);
}
/**
* Timeperiods comes from DB -> Store in $notifsTps Array
* When we make a massive change, give the possibility to not crush value
*/
$notifTps = [null => null];
$DBRESULT = $pearDB->query('SELECT tp_id, tp_name FROM timeperiod ORDER BY tp_name');
while ($notifTp = $DBRESULT->fetchRow()) {
$notifTps[$notifTp['tp_id']] = $notifTp['tp_name'];
}
$DBRESULT->closeCursor();
/**
* Notification commands comes from DB -> Store in $notifsCmds Array
*/
$notifCmds = [];
$query = "SELECT command_id, command_name FROM command WHERE command_type = '1' ORDER BY command_name";
$DBRESULT = $pearDB->query($query);
while ($notifCmd = $DBRESULT->fetchRow()) {
$notifCmds[$notifCmd['command_id']] = $notifCmd['command_name'];
}
$DBRESULT->closeCursor();
/**
* Contacts Templates
*/
$strRestrinction = isset($contact_id) ? ' AND contact_id != :contactId ' : '';
$contactTpl = [null => ''];
$statement = $pearDB->prepare(
<<<SQL
SELECT contact_id, contact_name FROM contact
WHERE contact_register = '0' {$strRestrinction} ORDER BY contact_name
SQL
);
if (! empty($strRestrinction)) {
$statement->bindValue(':contactId', $contact_id, PDO::PARAM_INT);
}
$statement->execute();
while ($contacts = $statement->fetchRow()) {
$contactTpl[$contacts['contact_id']] = $contacts['contact_name'];
}
$statement->closeCursor();
/**
* Template / Style for Quickform input
*/
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '60'];
$attrsTextDescr = ['size' => '80'];
$attrsTextMail = ['size' => '90'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 100px;'];
$attrsTextarea = ['rows' => '15', 'cols' => '100'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod&action=list';
$attrTimeperiods = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => false, 'linkedObject' => 'centreonTimeperiod'];
$attrCommands = ['datasourceOrigin' => 'ajax', 'multiple' => true, 'linkedObject' => 'centreonCommand'];
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// prepare event data
$eventData = [
'form' => $form,
'tpl' => $tpl,
'contact_id' => $contact_id,
];
switch ($o) {
case 'a':
$form->addElement('header', 'title', _('Add a User Template'));
$eventDispatcher->notify($eventContext, EventDispatcher::EVENT_DISPLAY, $eventData);
break;
case 'c':
$form->addElement('header', 'title', _('Modify a User Template'));
$eventDispatcher->notify($eventContext, EventDispatcher::EVENT_READ, $eventData);
break;
case 'w':
$form->addElement('header', 'title', _('View a User Template'));
$eventDispatcher->notify($eventContext, EventDispatcher::EVENT_READ, $eventData);
break;
case 'mc':
$form->addElement('header', 'title', _('Mass Change'));
$eventDispatcher->notify($eventContext, EventDispatcher::EVENT_DISPLAY, $eventData);
break;
}
/**
* Contact basic information
*/
$form->addElement('header', 'information', _('General Information'));
$form->addElement('header', 'additional', _('Additional Information'));
$form->addElement('header', 'centreon', _('Centreon Authentication'));
/**
* Don't change contact name and alias in massif change
* Don't change contact name, alias or autologin key in massive change
*/
if ($o != 'mc') {
$form->addElement('text', 'contact_name', _('Full Name'), $attrsTextDescr);
$form->addElement('text', 'contact_alias', _('Alias / Login'), $attrsText);
}
/**
* Contact template used
*/
$form->addElement('select', 'contact_template_id', _('Contact template used'), $contactTpl);
// ------------------------ Topoogy ----------------------------
$pages = [];
$aclUser = $centreon->user->lcaTStr;
if ($aclUser !== '') {
$acls = array_flip(explode(',', $aclUser));
/**
* Transform [1, 2, 101, 202, 10101, 20201] to :
*
* 1
* 101
* 10101
* 2
* 202
* 20201
*/
$createTopologyTree = function (array $topologies): array {
ksort($topologies, \SORT_ASC);
$parentsLvl = [];
// Classify topologies by parents
foreach (array_keys($topologies) as $page) {
if (strlen($page) === 1) {
// MENU level 1
if (! array_key_exists($page, $parentsLvl)) {
$parentsLvl[$page] = [];
}
} elseif (strlen($page) === 3) {
// MENU level 2
$parentLvl1 = substr($page, 0, 1);
if (! array_key_exists($parentLvl1, $parentsLvl)) {
$parentsLvl[$parentLvl1] = [];
}
if (! array_key_exists($page, $parentsLvl[$parentLvl1])) {
$parentsLvl[$parentLvl1][$page] = [];
}
} elseif (strlen($page) === 5) {
// MENU level 3
$parentLvl1 = substr($page, 0, 1);
$parentLvl2 = substr($page, 0, 3);
if (! array_key_exists($parentLvl1, $parentsLvl)) {
$parentsLvl[$parentLvl1] = [];
}
if (! array_key_exists($parentLvl2, $parentsLvl[$parentLvl1])) {
$parentsLvl[$parentLvl1][$parentLvl2] = [];
}
if (! in_array($page, $parentsLvl[$parentLvl1][$parentLvl2])) {
$parentsLvl[$parentLvl1][$parentLvl2][] = $page;
}
}
}
return $parentsLvl;
};
/**
* Check if at least one child can be shown
*/
$oneChildCanBeShown = function () use (&$childrenLvl3, &$translatedPages): bool {
foreach ($childrenLvl3 as $topologyPage) {
if ($translatedPages[$topologyPage]['show']) {
return true;
}
}
return false;
};
$topologies = $createTopologyTree($acls);
/**
* Retrieve the name of all topologies available for this user
*/
$aclTopologies = $pearDB->query(
'SELECT topology_page, topology_name, topology_show '
. 'FROM topology '
. "WHERE topology_page IN ({$aclUser})"
);
$translatedPages = [];
while ($topology = $aclTopologies->fetch(PDO::FETCH_ASSOC)) {
$translatedPages[$topology['topology_page']] = [
'i18n' => _($topology['topology_name']),
'show' => ((int) $topology['topology_show'] === 1),
];
}
/**
* Create flat tree for menu with the topologies names
* [item1Id] = menu1 > submenu1 > item1
* [item2Id] = menu2 > submenu2 > item2
*/
foreach ($topologies as $parentLvl1 => $childrenLvl2) {
$parentNameLvl1 = $translatedPages[$parentLvl1]['i18n'];
foreach ($childrenLvl2 as $parentLvl2 => $childrenLvl3) {
$parentNameLvl2 = $translatedPages[$parentLvl2]['i18n'];
$isThirdLevelMenu = false;
$parentLvl3 = null;
if ($oneChildCanBeShown()) {
/**
* There is at least one child that can be shown then we can
* process the third level
*/
foreach ($childrenLvl3 as $parentLvl3) {
if ($translatedPages[$parentLvl3]['show']) {
$parentNameLvl3 = $translatedPages[$parentLvl3]['i18n'];
if ($parentNameLvl2 === $parentNameLvl3) {
/**
* The name between lvl2 and lvl3 are equals.
* We keep only lvl1 and lvl3
*/
$pages[$parentLvl3] = $parentNameLvl1 . ' > '
. $parentNameLvl3;
} else {
$pages[$parentLvl3] = $parentNameLvl1 . ' > '
. $parentNameLvl2 . ' > '
. $parentNameLvl3;
}
}
}
$isThirdLevelMenu = true;
}
// select parent from level 2 if level 3 is missing
$pageId = $parentLvl3 ?? $parentLvl2;
if (! $isThirdLevelMenu && $translatedPages[$pageId]['show']) {
/**
* We show only first and second level
*/
$pages[$pageId]
= $parentNameLvl1 . ' > ' . $parentNameLvl2;
}
}
}
}
$form->addElement('select', 'default_page', _('Default page'), $pages);
$form->addElement('header', 'furtherAddress', _('Additional Addresses'));
$form->addElement('text', 'contact_address1', _('Address1'), $attrsText);
$form->addElement('text', 'contact_address2', _('Address2'), $attrsText);
$form->addElement('text', 'contact_address3', _('Address3'), $attrsText);
$form->addElement('text', 'contact_address4', _('Address4'), $attrsText);
$form->addElement('text', 'contact_address5', _('Address5'), $attrsText);
$form->addElement('text', 'contact_address6', _('Address6'), $attrsText);
/**
* Notification informations
*/
$form->addElement('header', 'notification', _('Notification'));
$tab = [];
$tab[] = $form->createElement('radio', 'contact_enable_notifications', null, _('Yes'), '1');
$tab[] = $form->createElement('radio', 'contact_enable_notifications', null, _('No'), '0');
$tab[] = $form->createElement('radio', 'contact_enable_notifications', null, _('Default'), '2');
$form->addGroup($tab, 'contact_enable_notifications', _('Enable Notifications'), ' ');
if ($o != 'mc') {
$form->setDefaults(['contact_enable_notifications' => '2']);
}
/** * *****************************
* Host notifications
*/
$form->addElement('header', 'hostNotification', _('Host'));
$hostNotifOpt[] = $form->createElement(
'checkbox',
'd',
' ',
_('Down'),
['id' => 'hDown', 'onClick' => 'uncheckAllH(this);']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unreachable'),
['id' => 'hUnreachable', 'onClick' => 'uncheckAllH(this);']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'r',
' ',
_('Recovery'),
['id' => 'hRecovery', 'onClick' => 'uncheckAllH(this);']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'f',
' ',
_('Flapping'),
['id' => 'hFlapping', 'onClick' => 'uncheckAllH(this);']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
's',
' ',
_('Downtime Scheduled'),
['id' => 'hScheduled', 'onClick' => 'uncheckAllH(this);']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'hNone', 'onClick' => 'javascript:uncheckAllH(this);']
);
$form->addGroup($hostNotifOpt, 'contact_hostNotifOpts', _('Host Notification Options'), ' ');
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod'
. '&action=defaultValues&target=contact&field=timeperiod_tp_id&id=' . $contact_id;
$attrTimeperiod1 = array_merge(
$attrTimeperiods,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'timeperiod_tp_id', _('Host Notification Period'), [], $attrTimeperiod1);
unset($hostNotifOpt);
if ($o == 'mc') {
$mc_mod_hcmds = [];
$mc_mod_hcmds[] = $form->createElement('radio', 'mc_mod_hcmds', null, _('Incremental'), '0');
$mc_mod_hcmds[] = $form->createElement('radio', 'mc_mod_hcmds', null, _('Replacement'), '1');
$form->addGroup($mc_mod_hcmds, 'mc_mod_hcmds', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_hcmds' => '0']);
}
$defaultRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_command'
. '&action=defaultValues&target=contact&field=contact_hostNotifCmds&id=' . $contact_id;
$availableRoute = './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_command&action=list&t=1';
$attrCommand1 = array_merge(
$attrCommands,
['defaultDatasetRoute' => $defaultRoute, 'availableDatasetRoute' => $availableRoute]
);
$form->addElement('select2', 'contact_hostNotifCmds', _('Host Notification Commands'), [], $attrCommand1);
/** * *****************************
* Service notifications
*/
$form->addElement('header', 'serviceNotification', _('Service'));
$svNotifOpt[] = $form->createElement(
'checkbox',
'w',
' ',
_('Warning'),
['id' => 'sWarning', 'onClick' => 'uncheckAllS(this);']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unknown'),
['id' => 'sUnknown', 'onClick' => 'uncheckAllS(this);']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'c',
' ',
_('Critical'),
['id' => 'sCritical', 'onClick' => 'uncheckAllS(this);']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'r',
' ',
_('Recovery'),
['id' => 'sRecovery', 'onClick' => 'uncheckAllS(this);']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'f',
' ',
_('Flapping'),
['id' => 'sFlapping', 'onClick' => 'uncheckAllS(this);']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
's',
' ',
_('Downtime Scheduled'),
['id' => 'sScheduled', 'onClick' => 'uncheckAllS(this);']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'sNone', 'onClick' => 'uncheckAllS(this);']
);
$form->addGroup($svNotifOpt, 'contact_svNotifOpts', _('Service Notification Options'), ' ');
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod'
. '&action=defaultValues&target=contact&field=timeperiod_tp_id2&id=' . $contact_id;
$attrTimeperiod2 = array_merge(
$attrTimeperiods,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'timeperiod_tp_id2', _('Service Notification Period'), [], $attrTimeperiod2);
if ($o == 'mc') {
$mc_mod_svcmds = [];
$mc_mod_svcmds[] = $form->createElement('radio', 'mc_mod_svcmds', null, _('Incremental'), '0');
$mc_mod_svcmds[] = $form->createElement('radio', 'mc_mod_svcmds', null, _('Replacement'), '1');
$form->addGroup($mc_mod_svcmds, 'mc_mod_svcmds', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_svcmds' => '0']);
}
$defaultRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_command'
. '&action=defaultValues&target=contact&field=contact_svNotifCmds&id=' . $contact_id;
$availableRoute = './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_command&action=list&t=1';
$attrCommand2 = array_merge(
$attrCommands,
['defaultDatasetRoute' => $defaultRoute, 'availableDatasetRoute' => $availableRoute]
);
$form->addElement('select2', 'contact_svNotifCmds', _('Service Notification Commands'), [], $attrCommand2);
/**
* Further informations
*/
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$cctActivation[] = $form->createElement('radio', 'contact_activate', null, _('Enabled'), '1');
$cctActivation[] = $form->createElement('radio', 'contact_activate', null, _('Disabled'), '0');
$form->addGroup($cctActivation, 'contact_activate', _('Status'), ' ');
$form->setDefaults(['contact_activate' => '1']);
if ($o == 'c' && $centreon->user->get_id() == $cct['contact_id']) {
$form->freeze('contact_activate');
}
$form->addElement('hidden', 'contact_register');
$form->setDefaults(['contact_register' => '0']);
$form->addElement('textarea', 'contact_comment', _('Comments'), $attrsTextarea);
$form->addElement('hidden', 'contact_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
if (is_array($select)) {
$select_str = $select !== []
? implode(',', array_keys($select))
: null;
$select_pear = $form->addElement('hidden', 'select');
$select_pear->setValue($select_str);
}
/**
* Form Rules
*/
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['contact_name']);
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('contact_name', 'myReplace');
$from_list_menu = false;
if ($o != 'mc') {
$ret = $form->getSubmitValues();
$form->addRule('contact_name', _('Compulsory Name'), 'required');
$form->addRule('contact_alias', _('Compulsory Alias'), 'required');
if (isset($ret['contact_enable_notifications']['contact_enable_notifications'])
&& $ret['contact_enable_notifications']['contact_enable_notifications'] == 1
) {
if (isset($ret['contact_template_id']) && $ret['contact_template_id'] == '') {
$form->addRule('timeperiod_tp_id', _('Compulsory Period'), 'required');
$form->addRule('timeperiod_tp_id2', _('Compulsory Period'), 'required');
$form->addRule('contact_hostNotifOpts', _('Compulsory Option'), 'required');
$form->addRule('contact_svNotifOpts', _('Compulsory Option'), 'required');
$form->addRule('contact_hostNotifCmds', _('Compulsory Command'), 'required');
$form->addRule('contact_svNotifCmds', _('Compulsory Command'), 'required');
}
}
$form->registerRule('exist', 'callback', 'testContactExistence');
$form->addRule('contact_name', "<font style='color: red;'>*</font> " . _('Contact already exists'), 'exist');
$form->registerRule('existAlias', 'callback', 'testAliasExistence');
$form->addRule(
'contact_alias',
"<font style='color: red;'>*</font> " . _('Alias already exists'),
'existAlias'
);
} elseif ($o == 'mc') {
$from_list_menu = $form->getSubmitValue('submitMC') ? false : true;
}
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, '
. '"orange", TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], '
. 'WIDTH, -300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once _CENTREON_PATH_ . '/www/include/configuration/configObject/contact/help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
if ($o == 'w') {
// Just watch a contact information
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&contact_id=' . $contact_id . "'"]
);
}
$form->setDefaults($cct);
$form->freeze();
} elseif ($o == 'c') {
// Modify a contact information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($cct);
} elseif ($o == 'a') {
// Add a contact information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
} elseif ($o == 'mc') {
// Massive Change
$subMC = $form->addElement('submit', 'submitMC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if ($form->validate() && $from_list_menu == false) {
$cctObj = $form->getElement('contact_id');
$eventData = [
'form' => $form,
'contact_id' => $cctObj->getValue(),
];
if ($form->getSubmitValue('submitA')) {
$newContactId = insertContactInDB();
$cctObj->setValue($newContactId);
$eventData['contact_id'] = $newContactId;
$eventDispatcher->notify($eventContext, EventDispatcher::EVENT_ADD, $eventData);
} elseif ($form->getSubmitValue('submitC')) {
updateContactInDB($cctObj->getValue());
$eventDispatcher->notify($eventContext, EventDispatcher::EVENT_UPDATE, $eventData);
} elseif ($form->getSubmitValue('submitMC')) {
if (! is_array($select)) {
$select = explode(',', $select);
}
foreach ($select as $key => $value) {
if ($value) {
updateContactInDB($value, true);
$eventDispatcher->notify($eventContext, EventDispatcher::EVENT_UPDATE, $eventData);
}
}
}
$o = null;
$valid = true;
}
if ($valid) {
require_once $path . 'listContactTemplateModel.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formContactTemplateModel.ihtml');
}
?>
<script type="text/javascript">
function uncheckAllH(object) {
if (object.id == "hNone" && object.checked) {
document.getElementById('hDown').checked = false;
document.getElementById('hUnreachable').checked = false;
document.getElementById('hRecovery').checked = false;
if (document.getElementById('hFlapping')) {
document.getElementById('hFlapping').checked = false;
}
if (document.getElementById('hScheduled')) {
document.getElementById('hScheduled').checked = false;
}
} else {
document.getElementById('hNone').checked = false;
}
}
function uncheckAllS(object) {
if (object.id == "sNone" && object.checked) {
document.getElementById('sWarning').checked = false;
document.getElementById('sUnknown').checked = false;
document.getElementById('sCritical').checked = false;
document.getElementById('sRecovery').checked = false;
if (document.getElementById('sFlapping')) {
document.getElementById('sFlapping').checked = false;
}
if (document.getElementById('sScheduled')) {
document.getElementById('sScheduled').checked = false;
}
} else {
document.getElementById('sNone').checked = false;
}
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/escalation/help.php | centreon/www/include/configuration/configObject/escalation/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['name'] = dgettext('help', 'Enter a short name for the escalation to identify it.');
$help['alias'] = dgettext('help', 'The alias is used to define a longer name or description for the escalation.');
$help['first_notification'] = dgettext(
'help',
'Enter a number that identifies the first notification for which this escalation is effective. '
. 'For instance, if you set this value to 3, this escalation will only be used if the host is down or '
. 'unreachable long enough for a third notification to go out.'
);
$help['last_notification'] = dgettext(
'help',
'Enter a number that identifies the last notification for which this escalation is effective. '
. 'For instance, if you set this value to 5, this escalation will not be used if more than five notifications are '
. 'sent out for the host. Setting this value to 0 means to keep using this escalation entry forever '
. '(no matter how many notifications go out).'
);
$help['notification_interval'] = dgettext(
'help',
'Select the interval at which notifications should be made while this escalation is valid. If you specify '
. 'a value of 0 for the interval, Monitoring Engine will send the first notification when this escalation '
. 'definition is valid, but will then prevent any more problem notifications from being sent out. '
. 'Notifications are sent out again until the host or service recovers. This is useful if you want to stop '
. 'having notifications sent out after a certain amount of time. Note: If multiple escalation entries overlap '
. 'for one or more notification ranges, the smallest notification interval from all escalation entries is used.'
);
$help['escalation_period'] = dgettext(
'help',
'Select the time period during which this escalation is valid. If no time period is specified, '
. 'the escalation is considered to be valid during all times.'
);
$help['host_escalation_options'] = dgettext(
'help',
'Define the criteria that determine when the host escalation is used. The escalation is used only if the '
. 'host is in one of the states specified in these options. If no options are specified in a host escalation, '
. 'the escalation is considered to be valid during all host states.'
);
$help['service_escalation_options'] = dgettext(
'help',
'Define the criteria that determine when the service escalation is used. The escalation is used only if '
. 'the service is in one of the states specified in these options. If no options are specified in a service '
. 'escalation, the escalation is considered to be valid during all service states.'
);
$help['contact_groups'] = dgettext(
'help',
'Select the contact group(s) that should be notified when the notification is escalated. '
. 'You must specify at least one contact group in each escalation definition.'
);
$help['host_name'] = dgettext('help', 'Select the host(s) that the escalation should apply to or is associated with.');
$help['service_description'] = dgettext(
'help',
'Select the service(s) the escalation should apply to or is associated with.'
);
$help['hostgroup_name'] = dgettext(
'help',
'Select the hostgroup(s) that the escalation should apply to. The escalation will apply to all hosts that '
. 'are members of the specified hostgroup(s).'
);
$help['servicegroup_name'] = dgettext(
'help',
'Select the service group(s) the escalation should apply to or is associated with. The escalation will apply '
. 'to all services that are members of the specified service group(s).'
);
$help['metaservice_name'] = dgettext(
'help',
'Select the meta service(s) the escalation should apply to or is associated with.'
);
// unsupported in centreon
$help['contacts'] = dgettext(
'help',
'Select contacts that should be notified whenever there are problems (or recoveries) with this host. '
. "Useful if you want notifications to go to just a few people and don't want to configure contact groups. "
. 'You must specify at least one contact or contact group in each host escalation definition.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/escalation/escalation.php | centreon/www/include/configuration/configObject/escalation/escalation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
if (! isset($centreon)) {
exit();
}
$rawEscId = $_GET['esc_id'] ?? $_POST['esc_id'] ?? null;
$esc_id = is_scalar($rawEscId)
? filter_var((string) $rawEscId, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE)
: null;
$rawSelect = $_GET['select'] ?? $_POST['select'] ?? [];
$select = [];
if (is_array($rawSelect)) {
foreach ($rawSelect as $key => $val) {
$id = filter_var((string) $key, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
if ($id !== null) {
// preserve the key so array_keys($select) === [123, 456, …]
$select[$id] = true;
}
}
}
$rawDupNbr = $_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [];
$dupNbr = [];
if (is_array($rawDupNbr)) {
foreach ($rawDupNbr as $key => $val) {
$id = filter_var((string) $key, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
$num = filter_var((string) $val, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
if ($id !== null && $num !== null) {
$dupNbr[$id] = $num;
}
}
}
// Path to the configuration dir
$path = './include/configuration/configObject/escalation/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $centreon->user->access;
$dbmon = $acl->getNameDBAcl('broker');
$hgs = $acl->getHostGroupAclConf(null, 'broker');
$hgString = CentreonUtils::toStringWithQuotes($hgs);
$sgs = $acl->getServiceGroupAclConf(null, 'broker');
$sgString = CentreonUtils::toStringWithQuotes($sgs);
switch ($o) {
case 'a':
require_once $path . 'formEscalation.php';
break; // Add a Escalation
case 'w':
require_once $path . 'formEscalation.php';
break; // Watch a Escalation
case 'c':
require_once $path . 'formEscalation.php';
break; // Modify a Escalation
case 'm':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleEscalationInDB($select ?? [], $dupNbr);
} else {
unvalidFormMessage();
}
require_once $path . 'listEscalation.php';
break; // Duplicate n Escalations
case 'd':
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteEscalationInDB($select ?? []);
} else {
unvalidFormMessage();
}
require_once $path . 'listEscalation.php';
break; // Delete n Escalation
default:
require_once $path . 'listEscalation.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/escalation/listEscalation.php | centreon/www/include/configuration/configObject/escalation/listEscalation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
const LIST_BY_HOSTS = 'h';
const LIST_BY_SERVICES = 'sv';
const LIST_BY_HOSTGROUPS = 'hg';
const LIST_BY_SERVICEGROUPS = 'sg';
const LIST_BY_METASERVICES = 'ms';
$list = array_key_exists('list', $_GET) && $_GET['list'] !== null
? HtmlSanitizer::createFromString($_GET['list'])->sanitize()->getString()
: null;
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchE'] ?? $_GET['searchE'] ?? null
);
if (isset($_POST['searchE']) || isset($_GET['searchE'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
$aclFrom = '';
$aclCond = [
LIST_BY_HOSTS => '',
LIST_BY_SERVICES => '',
LIST_BY_HOSTGROUPS => '',
LIST_BY_SERVICEGROUPS => '',
LIST_BY_METASERVICES => ''];
if (! $centreon->user->admin) {
/** @var CentreonACL $acl */
$aclIds = array_keys($acl->getAccessGroups());
$bindAccessGroups = [];
foreach ($aclIds as $aclId) {
$bindAccessGroups[':acl_' . $aclId] = $aclId;
}
$hostGroupIds = array_map(
static fn (string $hostGroupId) => (int) trim($hostGroupId, "' "),
explode(',', $hgString)
);
$bindHostGroups = [];
foreach ($hostGroupIds as $hostGroupId) {
$bindHostGroups[':hg_' . $hostGroupId] = $hostGroupId;
}
$serviceGroupIds = array_map(
static fn (string $serviceGroupId) => (int) trim($serviceGroupId, "' "),
explode(',', $sgString)
);
$bindServiceGroups = [];
foreach ($serviceGroupIds as $serviceGroupId) {
$bindServiceGroups[':sg_' . $serviceGroupId] = $serviceGroupId;
}
$metaServiceIds = array_keys($acl->getMetaServices());
$bindMetaServices = [];
foreach ($metaServiceIds as $metaServiceId) {
$bindMetaServices[':ms_' . $metaServiceId] = $metaServiceId;
}
$accessGroupsAsString = implode(',', array_keys($bindAccessGroups));
$aclFrom = ", `{$dbmon}`.centreon_acl acl ";
$aclCond[LIST_BY_HOSTS] = ! empty($accessGroupsAsString)
? " AND ehr.host_host_id = acl.host_id AND acl.group_id IN ({$accessGroupsAsString}) "
: '';
$aclCond[LIST_BY_SERVICES] = ! empty($accessGroupsAsString)
? ' AND esr.host_host_id = acl.host_id'
. ' AND esr.service_service_id = acl.service_id'
. " AND acl.group_id IN ({$accessGroupsAsString})"
: '';
$aclCond[LIST_BY_HOSTGROUPS] = $bindHostGroups !== []
? $acl->queryBuilder('AND', 'hostgroup_hg_id', implode(',', array_keys($bindHostGroups)))
: '';
$aclCond[LIST_BY_SERVICEGROUPS] = $bindServiceGroups !== []
? $acl->queryBuilder('AND', 'servicegroup_sg_id', implode(',', array_keys($bindServiceGroups)))
: '';
$aclCond[LIST_BY_METASERVICES] = $bindMetaServices !== []
? $acl->queryBuilder('AND', 'meta_service_meta_id', implode(',', array_keys($bindMetaServices)))
: '';
}
$rq = 'SELECT SQL_CALC_FOUND_ROWS esc_id, esc_name, esc_alias FROM escalation esc';
if ($list && $list == LIST_BY_HOSTS) {
$rq .= ' WHERE (SELECT DISTINCT COUNT(host_host_id) '
. ' FROM escalation_host_relation ehr ' . $aclFrom
. ' WHERE ehr.escalation_esc_id = esc.esc_id ' . $aclCond[LIST_BY_HOSTS] . ') > 0 ';
} elseif ($list && $list == LIST_BY_SERVICES) {
$rq .= ' WHERE (SELECT DISTINCT COUNT(*) '
. ' FROM escalation_service_relation esr ' . $aclFrom
. 'WHERE esr.escalation_esc_id = esc.esc_id ' . $aclCond[LIST_BY_SERVICES] . ') > 0 ';
} elseif ($list && $list == LIST_BY_HOSTGROUPS) {
$rq .= ' WHERE (SELECT DISTINCT COUNT(*) '
. 'FROM escalation_hostgroup_relation ehgr '
. 'WHERE ehgr.escalation_esc_id = esc.esc_id ' . $aclCond[LIST_BY_HOSTGROUPS] . ') > 0 ';
} elseif ($list && $list == LIST_BY_SERVICEGROUPS) {
$rq .= ' WHERE (SELECT DISTINCT COUNT(*) '
. ' FROM escalation_servicegroup_relation esgr '
. ' WHERE esgr.escalation_esc_id = esc.esc_id ' . $aclCond[LIST_BY_SERVICEGROUPS] . ') > 0 ';
} elseif ($list && $list == LIST_BY_METASERVICES) {
$rq .= ' WHERE (SELECT DISTINCT COUNT(*) '
. ' FROM escalation_meta_service_relation emsr '
. ' WHERE emsr.escalation_esc_id = esc.esc_id ' . $aclCond[LIST_BY_METASERVICES] . ') > 0 ';
}
// Check if $search was init
if ($search && $list) {
$rq .= ' AND (esc.esc_name LIKE :search OR esc.esc_alias LIKE :search)';
} elseif ($search) {
$rq .= ' WHERE (esc.esc_name LIKE :search OR esc.esc_alias LIKE :search)';
}
// Set Order and limits
$rq .= ' ORDER BY esc_name LIMIT ' . $num * $limit . ', ' . $limit;
$statement = $pearDB->prepare($rq);
if (! $centreon->user->admin) {
switch ($list) {
case LIST_BY_HOSTS:
case LIST_BY_SERVICES:
foreach ($bindAccessGroups as $accessGroupToken => $accessGroupId) {
$statement->bindValue($accessGroupToken, $accessGroupId, PDO::PARAM_INT);
}
break;
case LIST_BY_HOSTGROUPS:
foreach ($bindHostGroups as $hostGroupToken => $hostGroupId) {
$statement->bindValue($hostGroupToken, $hostGroupId, PDO::PARAM_INT);
}
break;
case LIST_BY_SERVICEGROUPS:
foreach ($bindServiceGroups as $serviceGroupToken => $serviceGroupId) {
$statement->bindValue($serviceGroupToken, $serviceGroupId, PDO::PARAM_INT);
}
break;
case LIST_BY_METASERVICES:
foreach ($bindMetaServices as $metaServiceToken => $metaServiceId) {
$statement->bindValue($metaServiceToken, $metaServiceId, PDO::PARAM_INT);
}
break;
default:
break;
}
}
if ($search) {
$statement->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
}
$statement->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_alias', _('Alias'));
$tpl->assign('headerMenu_options', _('Options'));
// Escalation list
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
for ($i = 0; $esc = $statement->fetch(); $i++) {
$esc = array_map('myDecode', $esc);
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $esc['esc_id'] . ']');
$moptions
.= ' <input onKeypress="if(event.keyCode > 31 && '
. '(event.keyCode < 45 || event.keyCode > 57)) event.returnValue = false; '
. 'if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" "
. "name='dupNbr[" . $esc['esc_id'] . "]'></input>";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure($esc['esc_name']), 'RowMenu_alias' => CentreonUtils::escapeSecure($esc['esc_alias']), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&esc_id=' . $esc['esc_id'], 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
// Toolbar select more_actions
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchE', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listEscalation.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/escalation/formEscalation.php | centreon/www/include/configuration/configObject/escalation/formEscalation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
// Database retrieve information for Escalation
$esc = [];
if (($o == 'c' || $o == 'w') && $esc_id) {
$statement = $pearDB->prepare('SELECT * FROM escalation WHERE esc_id = :escId LIMIT 1');
$statement->bindValue(':escId', $esc_id, PDO::PARAM_INT);
$statement->execute();
// Set base value
$esc = array_map('myDecode', $statement->fetchRow());
// Set Host Options
$esc['escalation_options1'] = explode(',', $esc['escalation_options1']);
foreach ($esc['escalation_options1'] as $key => $value) {
$esc['escalation_options1'][trim($value)] = 1;
}
// Set Service Options
$esc['escalation_options2'] = explode(',', $esc['escalation_options2']);
foreach ($esc['escalation_options2'] as $key => $value) {
$esc['escalation_options2'][trim($value)] = 1;
}
}
//
// End of "database-retrieved" information
// #########################################################
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '10'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 150px;'];
$attrsAdvSelect2 = ['style' => 'width: 300px; height: 400px;'];
$attrsTextarea = ['rows' => '5', 'cols' => '80'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>'
. '{unselected}</td><td align="center">{add}<br /><br /><br />'
. '{remove}</td><td><div class="ams">{label_3}</div>{selected}'
. '</td></tr></table>';
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == 'a') {
$form->addElement('header', 'title', _('Add an Escalation'));
} elseif ($o == 'c') {
$form->addElement('header', 'title', _('Modify an Escalation'));
} elseif ($o == 'w') {
$form->addElement('header', 'title', _('View an Escalation'));
}
//
// # Escalation basic information
//
$form->addElement('header', 'information', _('Information'));
$form->addElement('text', 'esc_name', _('Escalation Name'), $attrsText);
$form->addElement('text', 'esc_alias', _('Alias'), $attrsText);
$form->addElement('text', 'first_notification', _('First Notification'), $attrsText2);
$form->addElement('text', 'last_notification', _('Last Notification'), $attrsText2);
$form->addElement('text', 'notification_interval', _('Notification Interval'), $attrsText2);
$timeAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod&action=list';
$attrTimeperiods = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $timeAvRoute, 'multiple' => false, 'linkedObject' => 'centreonTimeperiod'];
$form->addElement('select2', 'escalation_period', _('Escalation Period'), [], $attrTimeperiods);
$tab = [];
$tab[] = $form->createElement('checkbox', 'd', ' ', _('Down'));
$tab[] = $form->createElement('checkbox', 'u', ' ', _('Unreachable'));
$tab[] = $form->createElement('checkbox', 'r', ' ', _('Recovery'));
$form->addGroup($tab, 'escalation_options1', _('Hosts Escalation Options'), ' ');
$tab = [];
$tab[] = $form->createElement('checkbox', 'w', ' ', _('Warning'));
$tab[] = $form->createElement('checkbox', 'u', ' ', _('Unknown'));
$tab[] = $form->createElement('checkbox', 'c', ' ', _('Critical'));
$tab[] = $form->createElement('checkbox', 'r', ' ', _('Recovery'));
$form->addGroup($tab, 'escalation_options2', _('Services Escalation Options'), ' ');
$form->addElement('textarea', 'esc_comment', _('Comments'), $attrsTextarea);
$contactDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup'
. '&action=defaultValues&target=escalation&field=esc_cgs&id=' . $esc_id;
$contactAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup'
. '&action=list';
$attrContactgroups = ['datasourceOrigin' => 'ajax', 'defaultDatasetRoute' => $contactDeRoute, 'availableDatasetRoute' => $contactAvRoute, 'multiple' => true, 'linkedObject' => 'centreonContactgroup'];
$form->addElement('select2', 'esc_cgs', _('Linked Contact Groups'), [], $attrContactgroups);
$form->addElement('checkbox', 'host_inheritance_to_services', '', _('Host inheritance to services'));
$form->addElement('checkbox', 'hostgroup_inheritance_to_services', '', _('Hostgroup inheritance to services'));
$hostDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host'
. '&action=defaultValues&target=escalation&field=esc_hosts&id=' . $esc_id;
$hostAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_host&action=list';
$attrHosts = ['datasourceOrigin' => 'ajax', 'defaultDatasetRoute' => $hostDeRoute, 'availableDatasetRoute' => $hostAvRoute, 'multiple' => true, 'linkedObject' => 'centreonHost'];
$form->addElement('select2', 'esc_hosts', _('Hosts'), [], $attrHosts);
$servDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_service'
. '&action=defaultValues&target=escalation&field=esc_hServices&id=' . $esc_id;
$servAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list';
$attrServices = ['datasourceOrigin' => 'ajax', 'defaultDatasetRoute' => $servDeRoute, 'availableDatasetRoute' => $servAvRoute, 'multiple' => true, 'linkedObject' => 'centreonService'];
$form->addElement('select2', 'esc_hServices', _('Services by Host'), [], $attrServices);
$hostgDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup'
. '&action=defaultValues&target=escalation&field=esc_hgs&id=' . $esc_id;
$hostgAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_hostgroup&action=list';
$attrHostgroups = ['datasourceOrigin' => 'ajax', 'defaultDatasetRoute' => $hostgDeRoute, 'availableDatasetRoute' => $hostgAvRoute, 'multiple' => true, 'linkedObject' => 'centreonHostgroups'];
$form->addElement('select2', 'esc_hgs', _('Host Group'), [], $attrHostgroups);
$MetaDeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_meta'
. '&action=defaultValues&target=escalation&field=esc_metas&id=' . $esc_id;
$MetaAvRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_meta&action=list';
$attrMetas = ['datasourceOrigin' => 'ajax', 'defaultDatasetRoute' => $MetaDeRoute, 'availableDatasetRoute' => $MetaAvRoute, 'multiple' => true, 'linkedObject' => 'centreonMeta'];
$form->addElement('select2', 'esc_metas', _('Meta Service'), [], $attrMetas);
$sgDefaultRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicegroup'
. '&action=defaultValues&target=escalation&field=esc_sgs&id=' . $esc_id;
$sgAvailableRoute = './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_servicegroup&action=list';
$attrServicegroups = ['datasourceOrigin' => 'ajax', 'defaultDatasetRoute' => $sgDefaultRoute, 'availableDatasetRoute' => $sgAvailableRoute, 'multiple' => true, 'linkedObject' => 'centreonServicegroups'];
$form->addElement('select2', 'esc_sgs', _('Service Group'), [], $attrServicegroups);
$form->addElement('hidden', 'esc_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
if (isset($initialValues)) {
$init->setValue(serialize($initialValues));
}
//
// # Form Rules
//
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('esc_name', _('Compulsory Name'), 'required');
$form->addRule('first_notification', _('Required Field'), 'required');
$form->addRule('last_notification', _('Required Field'), 'required');
$form->addRule('notification_interval', _('Required Field'), 'required');
$form->addRule('esc_cgs', _('Required Field'), 'required');
$form->registerRule('exist', 'callback', 'testExistence');
$form->addRule('esc_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
$form->registerRule('positiveInteger', 'callback', 'isPositiveInteger');
$form->addRule('first_notification', _('Must be a positive integer or 0'), 'positiveInteger');
$form->addRule('last_notification', _('Must be a positive integer or 0'), 'positiveInteger');
$form->addRule('notification_interval', _('Must be a positive integer or 0'), 'positiveInteger');
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Just watch an Escalation information
if ($o == 'w') {
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&esc_id=' . $esc_id . "'"]
);
}
$form->setDefaults($esc);
$form->freeze();
} elseif ($o == 'c') { // Modify an Escalation information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($esc);
} elseif ($o == 'a') { // Add an Escalation information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$tpl->assign('time_unit', ' * ' . $centreon->optGen['interval_length'] . ' ' . _('seconds'));
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange",'
. ' TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, -300,'
. ' SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$valid = false;
if ($form->validate()) {
$escObj = $form->getElement('esc_id');
if ($form->getSubmitValue('submitA')) {
$escObj->setValue(insertEscalationInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateEscalationInDB($escObj->getValue('esc_id'));
}
$o = null;
$valid = true;
}
if ($valid) {
require_once 'listEscalation.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formEscalation.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/escalation/DB-Func.php | centreon/www/include/configuration/configObject/escalation/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
/**
* @param string|null $name
* @throws Exception
* @return bool
*/
function testExistence(?string $name = null): bool
{
global $pearDB;
global $form;
$id = isset($form) ? $form->getSubmitValue('esc_id') : null;
$stmt = $pearDB->prepare('SELECT esc_id FROM escalation WHERE esc_name = :name');
$stmt->bindValue(':name', html_entity_decode($name, ENT_QUOTES, 'UTF-8'), PDO::PARAM_STR);
$stmt->execute();
$escalation = $stmt->fetch();
return ! ($stmt->rowCount() >= 1 && $escalation['esc_id'] !== (int) $id);
}
/**
* @param array $escalations
* @throws Exception
*/
function deleteEscalationInDB(array $escalations = [])
{
global $pearDB, $centreon;
foreach (array_keys($escalations) as $escalationId) {
$stmt = $pearDB->prepare('SELECT esc_name FROM `escalation` WHERE `esc_id` = :escalationId LIMIT 1');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalation = $stmt->fetch();
$stmt = $pearDB->prepare('DELETE FROM escalation WHERE esc_id = :escalationId');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$centreon->CentreonLogAction->insertLog('escalation', $escalationId, $escalation['esc_name'], 'd');
}
}
function multipleEscalationInDB(array $escalations = [], array $nbrDup = []): void
{
global $pearDB, $centreon;
foreach (array_keys($escalations) as $escalationId) {
$stmt = $pearDB->prepare('SELECT * FROM `escalation` WHERE `esc_id` = :escalationId LIMIT 1');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalationModel = $stmt->fetch();
if (! $escalationModel) {
continue;
}
for ($i = 1; $i <= $nbrDup[$escalationId]; $i++) {
$escalationDuplicate = $escalationModel;
$escalationDuplicate['esc_name'] = $escalationModel['esc_name'] . '_' . $i;
if (testExistence($escalationDuplicate['esc_name'])) {
$escalationDuplicate['esc_id'] = insertEscalation($pearDB, $escalationDuplicate, false);
if (! $escalationDuplicate['esc_id']) {
continue;
}
$stmt = $pearDB->prepare(
'SELECT DISTINCT contactgroup_cg_id
FROM escalation_contactgroup_relation
WHERE escalation_esc_id = :escalationId'
);
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalationContactGroups = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
updateEscalationContactGroups($pearDB, $escalationContactGroups, $escalationDuplicate['esc_id']);
$stmt = $pearDB->prepare(
'SELECT DISTINCT host_host_id
FROM escalation_host_relation
WHERE escalation_esc_id = :escalationId'
);
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalationHosts = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
updateEscalationHosts($pearDB, $escalationHosts, $escalationDuplicate['esc_id']);
$stmt = $pearDB->prepare(
'SELECT DISTINCT hostgroup_hg_id
FROM escalation_hostgroup_relation
WHERE escalation_esc_id = :escalationId'
);
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalationHostGroups = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
updateEscalationHostGroups($pearDB, $escalationHostGroups, $escalationDuplicate['esc_id']);
$stmt = $pearDB->prepare(
"SELECT DISTINCT CONCAT(host_host_id, '-', service_service_id)
FROM escalation_service_relation
WHERE escalation_esc_id = :escalationId"
);
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalationServices = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
updateEscalationServices($pearDB, $escalationServices, $escalationDuplicate['esc_id']);
$stmt = $pearDB->prepare(
'SELECT DISTINCT meta_service_meta_id
FROM escalation_meta_service_relation
WHERE escalation_esc_id = :escalationId'
);
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalationMetas = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
updateEscalationMetaServices($pearDB, $escalationMetas, $escalationDuplicate['esc_id']);
$stmt = $pearDB->prepare(
'SELECT DISTINCT servicegroup_sg_id
FROM escalation_servicegroup_relation
WHERE escalation_esc_id = :escalationId'
);
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$escalationServiceGroups = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
updateEscalationServiceGroups($pearDB, $escalationServiceGroups, $escalationDuplicate['esc_id']);
$centreon->CentreonLogAction->insertLog(
'escalation',
$escalationDuplicate['esc_id'],
$escalationDuplicate['esc_name'],
'a'
);
}
}
}
}
function updateEscalationInDB($escalationId): void
{
global $form, $pearDB;
if (! $escalationId) {
exit;
}
$data = $form->getSubmitValues();
updateEscalation($pearDB, $data, $escalationId);
$escalationContactGroups = CentreonUtils::mergeWithInitialValues($form, 'esc_cgs');
updateEscalationContactGroups($pearDB, $escalationContactGroups, $escalationId);
$escalationHosts = CentreonUtils::mergeWithInitialValues($form, 'esc_hosts');
updateEscalationHosts($pearDB, $escalationHosts, $escalationId);
$escalationHostGroups = CentreonUtils::mergeWithInitialValues($form, 'esc_hgs');
updateEscalationHostGroups($pearDB, $escalationHostGroups, $escalationId);
$escalationServices = CentreonUtils::mergeWithInitialValues($form, 'esc_hServices');
updateEscalationServices($pearDB, $escalationServices, $escalationId);
$escalationMetas = CentreonUtils::mergeWithInitialValues($form, 'esc_metas');
updateEscalationMetaServices($pearDB, $escalationMetas, $escalationId);
$escalationServiceGroups = CentreonUtils::mergeWithInitialValues($form, 'esc_sgs');
updateEscalationServiceGroups($pearDB, $escalationServiceGroups, $escalationId);
}
/**
* @throws Exception
* @return int|null
*/
function insertEscalationInDB(): ?int
{
global $form, $pearDB;
$data = $form->getSubmitValues();
if (! $escalationId = insertEscalation($pearDB, $data)) {
return null;
}
$escalationContactGroups = CentreonUtils::mergeWithInitialValues($form, 'esc_cgs');
updateEscalationContactGroups($pearDB, $escalationContactGroups, $escalationId);
$escalationHosts = CentreonUtils::mergeWithInitialValues($form, 'esc_hosts');
updateEscalationHosts($pearDB, $escalationHosts, $escalationId);
$escalationHostGroups = CentreonUtils::mergeWithInitialValues($form, 'esc_hgs');
updateEscalationHostGroups($pearDB, $escalationHostGroups, $escalationId);
$escalationServices = CentreonUtils::mergeWithInitialValues($form, 'esc_hServices');
updateEscalationServices($pearDB, $escalationServices, $escalationId);
$escalationMetas = CentreonUtils::mergeWithInitialValues($form, 'esc_metas');
updateEscalationMetaServices($pearDB, $escalationMetas, $escalationId);
$escalationServiceGroups = CentreonUtils::mergeWithInitialValues($form, 'esc_sgs');
updateEscalationServiceGroups($pearDB, $escalationServiceGroups, $escalationId);
return $escalationId;
}
/**
* @param CentreonDB $pearDB
* @param array<string,mixed> $data
* @param bool $logAction (default = true)
* @throws Exception
* @return int|null
*/
function insertEscalation(CentreonDB $pearDB, array $data, bool $logAction = true): ?int
{
$data['esc_name'] = HtmlSanitizer::createFromString($data['esc_name'])->sanitize()->getString();
$data['esc_alias'] = HtmlSanitizer::createFromString($data['esc_alias'])->sanitize()->getString();
$data['esc_comment'] = HtmlSanitizer::createFromString($data['esc_comment'])->sanitize()->getString();
$query = 'INSERT INTO escalation (
esc_name, esc_alias, first_notification, last_notification, notification_interval,
escalation_period, host_inheritance_to_services, hostgroup_inheritance_to_services, escalation_options1,
escalation_options2, esc_comment
) VALUES (
:esc_name, :esc_alias, :first_notification, :last_notification, :notification_interval, :escalation_period,
:host_inheritance_to_services, :hostgroup_inheritance_to_services, :escalation_options1,
:escalation_options2, :esc_comment
) ';
$params = [
'esc_name' => PDO::PARAM_STR,
'esc_alias' => PDO::PARAM_STR,
'first_notification' => PDO::PARAM_INT,
'last_notification' => PDO::PARAM_INT,
'notification_interval' => PDO::PARAM_INT,
'escalation_period' => PDO::PARAM_INT,
'host_inheritance_to_services' => 'checkbox',
'hostgroup_inheritance_to_services' => 'checkbox',
'escalation_options1' => PDO::PARAM_STR,
'escalation_options2' => PDO::PARAM_STR,
'esc_comment' => PDO::PARAM_STR,
];
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $paramType) {
if ($paramType === PDO::PARAM_INT) {
$stmt->bindValue(
':' . $paramName,
isset($data[$paramName]) && $data[$paramName] !== '' ? $data[$paramName] : null,
$paramType
);
} elseif ($paramType === PDO::PARAM_STR) {
$value = isset($data[$paramName])
? (is_array($data[$paramName]) ? implode(',', array_keys($data[$paramName])) : $data[$paramName])
: null;
$stmt->bindValue(
':' . $paramName,
$value,
$paramType
);
} else {
$stmt->bindValue(
':' . $paramName,
$data[$paramName] ?? 0,
PDO::PARAM_INT
);
}
}
$stmt->execute();
$dbResult = $pearDB->query('SELECT MAX(esc_id) FROM escalation');
$escalationId = $dbResult->fetch();
$escalationId = $escalationId ? (int) $escalationId['MAX(esc_id)'] : null;
if ($logAction) {
logEscalation($escalationId, 'a', $data);
}
return $escalationId;
}
/**
* @param CentreonDB $pearDB
* @param array<string,mixed> $data
* @param int $escalationId
* @throws Exception
*/
function updateEscalation(CentreonDB $pearDB, array $data, int $escalationId): void
{
$data['esc_name'] = HtmlSanitizer::createFromString($data['esc_name'])->sanitize()->getString();
$data['esc_alias'] = HtmlSanitizer::createFromString($data['esc_alias'])->sanitize()->getString();
$data['esc_comment'] = HtmlSanitizer::createFromString($data['esc_comment'])->sanitize()->getString();
$query = 'UPDATE escalation SET
esc_name = :esc_name,
esc_alias = :esc_alias,
first_notification = :first_notification,
last_notification = :last_notification,
notification_interval = :notification_interval,
escalation_period = :escalation_period,
host_inheritance_to_services = :host_inheritance_to_services,
hostgroup_inheritance_to_services = :hostgroup_inheritance_to_services,
escalation_options1 = :escalation_options1,
escalation_options2 = :escalation_options2,
esc_comment = :esc_comment
WHERE esc_id = :esc_id';
$params = [
'esc_name' => PDO::PARAM_STR,
'esc_alias' => PDO::PARAM_STR,
'first_notification' => PDO::PARAM_INT,
'last_notification' => PDO::PARAM_INT,
'notification_interval' => PDO::PARAM_INT,
'escalation_period' => PDO::PARAM_INT,
'host_inheritance_to_services' => 'checkbox',
'hostgroup_inheritance_to_services' => 'checkbox',
'escalation_options1' => PDO::PARAM_STR,
'escalation_options2' => PDO::PARAM_STR,
'esc_comment' => PDO::PARAM_STR,
];
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $paramType) {
if ($paramType === PDO::PARAM_INT) {
$stmt->bindValue(
':' . $paramName,
isset($data[$paramName]) && $data[$paramName] !== '' ? $data[$paramName] : null,
$paramType
);
} elseif ($paramType === PDO::PARAM_STR) {
$value = isset($data[$paramName])
? (is_array($data[$paramName]) ? implode(',', array_keys($data[$paramName])) : $data[$paramName])
: null;
$stmt->bindValue(
':' . $paramName,
$value,
$paramType
);
} else {
$stmt->bindValue(
':' . $paramName,
isset($data[$paramName]) ? 1 : 0,
PDO::PARAM_INT
);
}
}
$stmt->bindValue(':esc_id', $escalationId, PDO::PARAM_INT);
$stmt->execute();
logEscalation($escalationId, 'c', $data);
}
/**
* Log escalation creation or update for the action log
*
* @param int|null $esc_id
* @param string $action ('a' = add, 'c' = update)
* @param array $data
*/
function logEscalation(?int $escalationId, string $action, array $data): void
{
global $centreon;
$fields = [
'esc_name' => $data['esc_name'],
'esc_alias' => $data['esc_alias'],
'first_notification' => $data['first_notification'],
'last_notification' => $data['last_notification'],
'notification_interval' => $data['notification_interval'],
'escalation_period' => $data['escalation_period'],
'escalation_options1' => isset($data['escalation_options1'])
? implode(',', array_keys($data['escalation_options1']))
: '',
'escalation_options2' => isset($data['escalation_options2'])
? implode(',', array_keys($data['escalation_options2']))
: '',
'esc_comment' => $data['esc_comment'],
'esc_cgs' => isset($data['esc_cgs'])
? implode(',', array_keys($data['esc_cgs']))
: '',
'esc_hosts' => isset($data['esc_hosts'])
? implode(',', array_keys($data['esc_hosts']))
: '',
'esc_hgs' => isset($data['esc_hgs'])
? implode(',', array_keys($data['esc_hgs']))
: '',
'esc_sgs' => isset($data['esc_sgs'])
? implode(',', array_keys($data['esc_sgs']))
: '',
'esc_hServices' => isset($data['esc_hServices'])
? implode(',', array_keys($data['esc_hServices']))
: '',
'esc_metas' => isset($data['esc_metas'])
? implode(',', array_keys($data['esc_metas']))
: '',
];
if (isset($data['host_inheritance_to_services'])) {
$fields['host_inheritance_to_services'] = $data['host_inheritance_to_services'];
}
if (isset($data['hostgroup_inheritance_to_services'])) {
$fields['hostgroup_inheritance_to_services'] = $data['hostgroup_inheritance_to_services'];
}
$centreon->CentreonLogAction->insertLog(
'escalation',
$escalationId,
$fields['esc_name'],
$action,
$fields
);
}
/**
* @param CentreonDB $pearDB
* @param array $escalationContactGroups
* @param int $escalationId
* @throws Exception
*/
function updateEscalationContactGroups(CentreonDB $pearDB, array $escalationContactGroups, int $escalationId): void
{
$stmt = $pearDB->prepare('DELETE FROM escalation_contactgroup_relation WHERE escalation_esc_id = :escalationId');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$contactGroupManager = new CentreonContactgroup($pearDB);
$queryParams = [];
$params = [];
foreach ($escalationContactGroups as $key => $contactGroupId) {
if (! is_numeric($contactGroupId)) {
$contactGroupId = $contactGroupManager->insertLdapGroup($contactGroupId) ?? null;
}
if (! $contactGroupId || ($key = filter_var($key, FILTER_VALIDATE_INT)) === false) {
continue;
}
$params[':contactGroupId' . $key] = $contactGroupId;
$queryParams[] = "(:escalationId, :contactGroupId{$key})";
}
if ($params === []) {
return;
}
$query = 'INSERT INTO escalation_contactgroup_relation (escalation_esc_id, contactgroup_cg_id) VALUES ';
$query .= implode(', ', $queryParams);
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $value) {
$stmt->bindValue($paramName, $value, PDO::PARAM_INT);
}
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
}
/**
* @param CentreonDB $pearDB
* @param array $escalationHosts
* @param int $escalationId
* @throws Exception
*/
function updateEscalationHosts(CentreonDB $pearDB, array $escalationHosts, int $escalationId): void
{
$stmt = $pearDB->prepare('DELETE FROM escalation_host_relation WHERE escalation_esc_id = :escalationId');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$queryParams = [];
$params = [];
foreach ($escalationHosts as $key => $hostId) {
if (($key = filter_var($key, FILTER_VALIDATE_INT)) === false) {
continue;
}
$params[':hostId' . $key] = $hostId;
$queryParams[] = "(:escalationId, :hostId{$key})";
}
if ($params === []) {
return;
}
$query = 'INSERT INTO escalation_host_relation (escalation_esc_id, host_host_id) VALUES ';
$query .= implode(', ', $queryParams);
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $value) {
$stmt->bindValue($paramName, $value, PDO::PARAM_INT);
}
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
}
/**
* @param CentreonDB $pearDB
* @param array $escalationHostGroups
* @param int $escalationId
* @throws Exception
*/
function updateEscalationHostGroups(CentreonDB $pearDB, array $escalationHostGroups, int $escalationId): void
{
$stmt = $pearDB->prepare('DELETE FROM escalation_hostgroup_relation WHERE escalation_esc_id = :escalationId');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$queryParams = [];
$params = [];
foreach ($escalationHostGroups as $key => $hostGroupId) {
if (($key = filter_var($key, FILTER_VALIDATE_INT)) === false) {
continue;
}
$params[':hostGroupId' . $key] = $hostGroupId;
$queryParams[] = "(:escalationId, :hostGroupId{$key})";
}
if ($params === []) {
return;
}
$query = 'INSERT INTO escalation_hostgroup_relation (escalation_esc_id, hostgroup_hg_id) VALUES ';
$query .= implode(', ', $queryParams);
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $value) {
$stmt->bindValue($paramName, $value, PDO::PARAM_INT);
}
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
}
/**
* @param CentreonDB $pearDB
* @param array $escalationServiceGroups
* @param int $escalationId
* @throws Exception
*/
function updateEscalationServiceGroups(CentreonDB $pearDB, array $escalationServiceGroups, int $escalationId): void
{
$stmt = $pearDB->prepare('DELETE FROM escalation_servicegroup_relation WHERE escalation_esc_id = :escalationId');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$queryParams = [];
$params = [];
foreach ($escalationServiceGroups as $key => $serviceGroupId) {
if (($key = filter_var($key, FILTER_VALIDATE_INT)) === false) {
continue;
}
$params[':serviceGroupId' . $key] = $serviceGroupId;
$queryParams[] = "(:escalationId, :serviceGroupId{$key})";
}
if ($params === []) {
return;
}
$query = 'INSERT INTO escalation_servicegroup_relation (escalation_esc_id, servicegroup_sg_id) VALUES ';
$query .= implode(', ', $queryParams);
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $value) {
$stmt->bindValue($paramName, $value, PDO::PARAM_INT);
}
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
}
/**
* @param CentreonDB $pearDB
* @param array $escalationServices
* @param int $escalationId
* @throws Exception
*/
function updateEscalationServices(CentreonDB $pearDB, array $escalationServices, int $escalationId): void
{
$stmt = $pearDB->prepare('DELETE FROM escalation_service_relation WHERE escalation_esc_id = :escalationId');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$queryParams = [];
$params = [];
foreach ($escalationServices as $key => $serviceData) {
if (($key = filter_var($key, FILTER_VALIDATE_INT)) === false) {
continue;
}
$exp = explode('-', $serviceData);
if (count($exp) === 2) {
$params[':serviceId' . $key] = $exp[1];
$params[':hostId' . $key] = $exp[0];
$queryParams[] = "(:escalationId, :serviceId{$key}, :hostId{$key})";
}
}
if ($params === []) {
return;
}
$query = 'INSERT INTO escalation_service_relation (escalation_esc_id, service_service_id, host_host_id) VALUES ';
$query .= implode(', ', $queryParams);
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $value) {
$stmt->bindValue($paramName, $value, PDO::PARAM_INT);
}
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
}
/**
* @param CentreonDB $pearDB
* @param array $escalationMetas
* @param int $escalationId
* @throws Exception
*/
function updateEscalationMetaServices(CentreonDB $pearDB, array $escalationMetas, int $escalationId): void
{
$stmt = $pearDB->prepare('DELETE FROM escalation_meta_service_relation WHERE escalation_esc_id = :escalationId');
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
$queryParams = [];
$params = [];
foreach ($escalationMetas as $key => $metaServiceId) {
if (($key = filter_var($key, FILTER_VALIDATE_INT)) === false) {
continue;
}
$params[':metaServiceId' . $key] = $metaServiceId;
$queryParams[] = "(:escalationId, :metaServiceId{$key})";
}
if ($params === []) {
return;
}
$query = 'INSERT INTO escalation_meta_service_relation (escalation_esc_id, meta_service_meta_id) VALUES ';
$query .= implode(', ', $queryParams);
$stmt = $pearDB->prepare($query);
foreach ($params as $paramName => $value) {
$stmt->bindValue($paramName, $value, PDO::PARAM_INT);
}
$stmt->bindValue(':escalationId', $escalationId, PDO::PARAM_INT);
$stmt->execute();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps/traps.php | centreon/www/include/configuration/configObject/traps/traps.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
require_once './class/centreonTraps.class.php';
require_once './include/common/common-Func.php';
define('TRAP_ADD', 'a');
define('TRAP_DELETE', 'd');
define('TRAP_DUPLICATE', 'm');
define('TRAP_MODIFY', 'c');
define('TRAP_WATCH', 'w');
$trapsId = filter_var(
$_GET['traps_id'] ?? $_POST['traps_id'] ?? null,
FILTER_VALIDATE_INT
);
$selectIds = filter_var_array(
$_GET['select'] ?? $_POST['select'] ?? [],
FILTER_VALIDATE_INT
);
$duplicateNbr = filter_var_array(
$_GET['dupNbr'] ?? $_POST['dupNbr'] ?? [],
FILTER_VALIDATE_INT
);
// Path to the configuration dir
$path = './include/configuration/configObject/traps/';
$trapObj = new CentreonTraps($pearDB, $oreon);
$acl = $centreon->user->access;
$aclDbName = $acl->getNameDBAcl();
$dbmon = new CentreonDB('centstorage');
$sgs = $acl->getServiceGroupAclConf(null, 'broker');
$severityObj = new CentreonCriticality($pearDB);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
switch ($o) {
case TRAP_ADD:
require_once $path . 'formTraps.php';
break;
case TRAP_WATCH:
if (is_int($trapsId)) {
require_once $path . 'formTraps.php';
} else {
require_once $path . 'listTraps.php';
}
break;
case TRAP_MODIFY:
if (is_int($trapsId)) {
require_once $path . 'formTraps.php';
} else {
require_once $path . 'listTraps.php';
}
break;
case TRAP_DUPLICATE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds) && ! in_array(false, $duplicateNbr)) {
$trapObj->duplicate($selectIds, $duplicateNbr);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listTraps.php';
break;
case TRAP_DELETE:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
if (! in_array(false, $selectIds)) {
$trapObj->delete($selectIds);
}
} else {
unvalidFormMessage();
}
require_once $path . 'listTraps.php';
break;
default:
require_once $path . 'listTraps.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps/help.php | centreon/www/include/configuration/configObject/traps/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['trapname'] = dgettext(
'help',
'Enter the trap name as specified in the MIB file and send by the SNMP master agent.'
);
$help['mode'] = dgettext(
'help',
'Choose the matching mode.'
);
$help['oid'] = dgettext('help', 'Enter the full numeric object identifier (OID) starting with .1.3.6 (.iso.org.dod).');
$help['vendor'] = dgettext('help', 'Choose a vendor from the list. The vendor must have been created beforehand.');
$help['submit_result_enabled'] = dgettext(
'help',
'Switch the submission of trap results to monitoring engine on or off.'
);
$help['trap_args'] = dgettext(
'help',
'Enter the status message to be submitted to monitoring engine. The original trap message will be '
. 'placed into the entered string at the position of the variable $*.'
);
$help['trap_status'] = dgettext(
'help',
'Choose the service state to be submitted to monitoring engine together with the status message. '
. 'This simple mode can be used if each trap can be mapped to exactly 1 monitoring engine status.'
);
$help['severity'] = dgettext('help', 'Severities are defined in the service category object.');
$help['trap_advanced'] = dgettext(
'help',
'Enable advanced matching mode for cases where a trap relates to multiple monitoring engine states and the '
. 'trap message has to be parsed.'
);
$help['trap_adv_args'] = dgettext(
'help',
'Define one or multiple regular expressions to match against the trap message and map it to the related '
. "monitoring engine service state. Use <a href='http://perldoc.perl.org/perlre.html'>perlre</a> for "
. 'the format and place the expression between two slashes.'
);
$help['reschedule_enabled'] = dgettext(
'help',
'Choose whether or not the associated service should be actively rechecked after submission of this trap.'
);
$help['command_enabled'] = dgettext(
'help',
'Choose whether or not a special command should be run by centreontrapd when this trap was received.'
);
$help['command_args'] = dgettext(
'help',
"Define the command to execute by centreontrapd's trap handler. The command must be located in the "
. 'PATH of the centreontrapd user.'
);
$help['comments'] = dgettext(
'help',
'Comment to describe per example the situation in which this trap will be send. Additionally '
. 'the format and the parameters of the trap can be described.'
);
$help['traps_routing_mode'] = dgettext('help', 'Enable/Disable routing definition');
$help['traps_routing_value'] = dgettext('help', 'Routing definition to choose host(s)');
$help['traps_routing_filter_services'] = dgettext(
'help',
'Permits to filter services of host(s). Skip if service_description not equals to the value set.'
);
$help['preexeccmd'] = dgettext(
'help',
"PREEXEC commands are executed after 'routing' and before 'matching', 'actions'"
);
$help['traps_log'] = dgettext('help', 'Whether or not traps will be inserted into database. Disabled by default');
$help['traps_exec_interval'] = dgettext('help', 'Minimum delay necessary for a trap to be processed after another one');
$help['traps_exec_interval_type'] = dgettext(
'help',
'Whether execution interval will be applied to identical OIDs or identical OIDs and hosts'
);
$help['traps_exec_method'] = dgettext('help', 'Defines the trap execution method');
$help['traps_downtime'] = dgettext(
'help',
"Skip trap if host or service is in downtime when centreontrapd proceeds. 'History' option is more accurate "
. 'but needs more powers. The option works only with centreon-broker AND central mode.'
);
$help['traps_output_transform'] = dgettext(
'help',
"Regexp for removing or change some characters in output message (Example: s/\|/-/g)."
);
$help['traps_advanced_treatment_default'] = dgettext(
'help',
'Submit or not the status to the monitoring engine, related to the rules'
);
$help['traps_timeout'] = dgettext(
'help',
'Maximum execution time of trap processing. This includes Preexec commands, submit command and special command'
);
$help['traps_customcode'] = dgettext(
'help',
"Custom Perl code. Will be executed with no change (security issue. Need to set centreontrapd secure_mode to '1')"
);
$help['services'] = dgettext('help', 'Choose a service from the list. The service must have been created beforehand.');
$help['service_templates'] = dgettext(
'help',
'Choose a service template from the list. The service template must have been created beforehand.'
);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps/listTraps.php | centreon/www/include/configuration/configObject/traps/listTraps.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
// list of enum
$tabStatus = [-1 => _('Pending'), 0 => _('OK'), 1 => _('Warning'), 2 => _('Critical'), 3 => _('Unknown')];
// list without id 0 for select2
$tabStatusFilter = [1 => _('OK'), 2 => _('Warning'), 3 => _('Critical'), 4 => _('Unknown'), 5 => _('Pending')];
$searchTraps = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchT'] ?? $_GET['searchT'] ?? null
);
$searchStatus = null;
if (! empty($_POST['status']) || ! empty($_GET['status'])) {
$searchStatus = filter_var(
$_POST['status'] ?? $_GET['status'],
FILTER_VALIDATE_INT
);
}
$searchVendor = null;
if (! empty($_POST['vendor']) || ! empty($_GET['vendor'])) {
$searchVendor = filter_var(
$_POST['vendor'] ?? $_GET['vendor'],
FILTER_VALIDATE_INT
);
}
if ($searchStatus === false || $searchVendor === false) {
throw new InvalidArgumentException('Bad Parameters');
}
if (isset($_POST['Search'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['searchTraps'] = $searchTraps;
$centreon->historySearch[$url]['searchStatus'] = $searchStatus;
$centreon->historySearch[$url]['searchVendor'] = $searchVendor;
} else {
// restoring saved values
$searchTraps = $centreon->historySearch[$url]['searchTraps'] ?? null;
$searchStatus = $centreon->historySearch[$url]['searchStatus'] ?? null;
$searchVendor = $centreon->historySearch[$url]['searchVendor'] ?? null;
}
// convert status filter to enum
$enumStatus = $searchStatus == 5 ? -1 : $searchStatus - 1;
$queryValues = [];
$rq = 'SELECT SQL_CALC_FOUND_ROWS * FROM traps WHERE 1 ';
// List of elements - Depends on different criteria
if ($searchTraps) {
$rq .= ' AND (traps_oid LIKE :trapName OR traps_name LIKE :trapName '
. 'OR manufacturer_id IN (SELECT id FROM traps_vendor WHERE alias LIKE :trapName )) ';
$queryValues[':trapName'] = '%' . $searchTraps . '%';
}
if ($searchVendor) {
$rq .= ' AND manufacturer_id = :manufacturer ';
$queryValues[':manufacturer'] = (int) $searchVendor;
}
if ($searchStatus) {
$rq .= ' AND traps_status = :status ';
$queryValues[':status'] = $enumStatus;
}
$rq .= ' ORDER BY manufacturer_id, traps_name LIMIT ' . (int) ($num * $limit) . ', ' . (int) $limit;
$stmt = $pearDB->prepare($rq);
if (isset($queryValues[':trapName'])) {
$stmt->bindValue(':trapName', $queryValues[':trapName'], PDO::PARAM_STR);
}
if (isset($queryValues[':manufacturer'])) {
$stmt->bindValue(':manufacturer', $queryValues[':manufacturer'], PDO::PARAM_INT);
}
if (isset($queryValues[':status'])) {
$stmt->bindValue(':status', $queryValues[':status'], PDO::PARAM_STR);
}
$stmt->execute();
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_desc', _('OID'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_manufacturer', _('Vendor Name'));
$tpl->assign('headerMenu_args', _('Output Message'));
$tpl->assign('headerMenu_options', _('Options'));
$form = new HTML_QuickFormCustom('form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
$attrTrapsStatus = null;
if (! empty($searchStatus)) {
$statusDefault = [$tabStatusFilter[$searchStatus] => $searchStatus];
$attrTrapsStatus = ['defaultDataset' => $statusDefault];
}
$form->addElement('select2', 'status', '', $tabStatusFilter, $attrTrapsStatus);
$vendorResult = $pearDB->query('SELECT id, name FROM traps_vendor ORDER BY name, alias');
$vendors = [];
for ($i = 0; $vendor = $vendorResult->fetch(); $i++) {
$vendors[$vendor['id']] = $vendor['name'];
}
$attrTrapsVendor = null;
if ($searchVendor) {
$vendorDefault = [$vendors[$searchVendor] => $searchVendor];
$attrTrapsVendor = ['defaultDataset' => $vendorDefault];
}
$form->addElement('select2', 'vendor', '', $vendors, $attrTrapsVendor);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
for ($i = 0; $trap = $stmt->fetch(); $i++) {
$trap = array_map(['CentreonUtils', 'escapeAll'], $trap);
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $trap['traps_id'] . ']');
$moptions .= ' ';
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr["
. $trap['traps_id'] . "]' />";
$statement = $pearDB->prepare('select alias from traps_vendor where id= :trap LIMIT 1');
$statement->bindValue(':trap', (int) $trap['manufacturer_id'], PDO::PARAM_INT);
$statement->execute();
$mnftr = $statement->fetch();
$statement->closeCursor();
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => $trap['traps_name'], 'RowMenu_link' => "?p={$p}&o=c&traps_id={$trap['traps_id']}", 'RowMenu_desc' => substr($trap['traps_oid'], 0, 40), 'RowMenu_status' => $tabStatus[($trap['traps_status'])] ?? $tabStatus[3], 'RowMenu_args' => $trap['traps_args'], 'RowMenu_manufacturer' => CentreonUtils::escapeSecure(
$mnftr['alias'],
CentreonUtils::ESCAPE_ALL
), 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$attrs2 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs2
);
$form->setDefaults(['o2' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$o1->setSelected(null);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$o2->setSelected(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchT', $searchTraps);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listTraps.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/traps/formTraps.php | centreon/www/include/configuration/configObject/traps/formTraps.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
function myDecodeTrap($arg)
{
return html_entity_decode($arg ?? '', ENT_QUOTES, 'UTF-8');
}
function myReplace()
{
global $form;
return str_replace(' ', '_', $form->getSubmitValue('traps_name'));
}
$trap = [];
$initialValues = [];
$hServices = [];
$cdata = CentreonData::getInstance();
$preexecArray = [];
$mrulesArray = [];
if (($o == TRAP_MODIFY || $o == TRAP_WATCH) && is_int($trapsId)) {
$DBRESULT = $pearDB->query("SELECT * FROM traps WHERE traps_id = '{$trapsId}' LIMIT 1");
// Set base value
$trap = array_map('myDecodeTrap', $DBRESULT->fetchRow());
$trap['severity'] = $trap['severity_id'];
$DBRESULT->closeCursor();
$preexecArray = $trapObj->getPreexecFromTrapId($trapsId);
$mrulesArray = $trapObj->getMatchingRulesFromTrapId($trapsId);
}
// Preset values of preexec commands
$cdata->addJsData('clone-values-preexec', htmlspecialchars(
json_encode($preexecArray),
ENT_QUOTES
));
$cdata->addJsData('clone-count-preexec', count($preexecArray));
// Preset values of matching rules
$cdata->addJsData('clone-values-matchingrules', htmlspecialchars(
json_encode($mrulesArray),
ENT_QUOTES
));
$cdata->addJsData('clone-count-matchingrules', count($mrulesArray));
$attrsText = ['size' => '50'];
$attrsLongText = ['size' => '120'];
$attrsTextarea = ['rows' => '10', 'cols' => '120'];
$attrsAdvSelect = ['style' => 'width: 270px; height: 100px;'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_manufacturer&action=list';
$attrManufacturer = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => false, 'linkedObject' => 'centreonManufacturer'];
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_service&action=list&s=s';
$attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => true, 'linkedObject' => 'centreonService'];
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_servicetemplate&action=list';
$attrServicetemplates = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => true, 'linkedObject' => 'centreonServicetemplates'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$trapObj->setForm($form);
if ($o == TRAP_ADD) {
$form->addElement('header', 'title', _('Add a Trap definition'));
} elseif ($o == TRAP_MODIFY) {
$form->addElement('header', 'title', _('Modify a Trap definition'));
} elseif ($o == TRAP_WATCH) {
$form->addElement('header', 'title', _('View a Trap definition'));
}
// Command information
$form->addElement('text', 'traps_name', _('Trap name'), $attrsText);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_manufacturer'
. '&action=defaultValues&target=traps&field=manufacturer_id&id=' . $trapsId;
$attrManufacturer1 = array_merge(
$attrManufacturer,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'manufacturer_id', _('Vendor Name'), [], $attrManufacturer1);
$form->addElement('textarea', 'traps_comments', _('Comments'), $attrsTextarea);
$traps_mode[] = $form->createElement('radio', 'traps_mode', null, _('Unique'), '0');
$traps_mode[] = $form->createElement('radio', 'traps_mode', null, _('Regexp'), '1');
$form->addGroup($traps_mode, 'traps_mode', _('Mode'), ' ');
$form->setDefaults(['traps_mode' => '0']);
/**
* Generic fields
*/
$form->addElement('text', 'traps_oid', _('OID'), $attrsText);
$form->addElement(
'select',
'traps_status',
_('Default Status'),
[0 => _('Ok'), 1 => _('Warning'), 2 => _('Critical'), 3 => _('Unknown')],
['id' => 'trapStatus']
);
$severities = $severityObj->getList(null, 'level', 'ASC', null, null, true);
$severityArr = [null => null];
foreach ($severities as $severity_id => $severity) {
$severityArr[$severity_id] = $severity['sc_name'] . ' (' . $severity['level'] . ')';
}
$form->addElement('select', 'severity', _('Default Severity'), $severityArr);
$form->addElement('text', 'traps_args', _('Output Message'), $attrsText);
$form->addElement(
'checkbox',
'traps_advanced_treatment',
_('Advanced matching mode'),
null,
['id' => 'traps_advanced_treatment']
);
$form->setDefaults(0);
/* *******************************************************************
* Three possibilities : - submit result
* - execute a special command
* - resubmit a scheduling force
*/
// submit result
$cbt = $form->addElement('checkbox', 'traps_submit_result_enable', _('Submit result'));
$form->setDefaults(['traps_submit_result_enable' => '1']);
// Schedule svc check forced
$form->addElement('checkbox', 'traps_reschedule_svc_enable', _('Reschedule associated services'));
// execute commande
$form->addElement('text', 'traps_execution_command', _('Special Command'), $attrsLongText);
$form->addElement('checkbox', 'traps_execution_command_enable', _('Execute special command'));
// Further informations
$form->addElement('hidden', 'traps_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$attrService1 = array_merge(
$attrServices,
['defaultDatasetRoute' => './api/internal.php?object=centreon_configuration_service&action=defaultValues'
. '&target=traps&field=services&id=' . $trapsId]
);
$form->addElement('select2', 'services', _('Linked Services'), [], $attrService1);
$query = './api/internal.php?object=centreon_configuration_servicetemplate&action=defaultValues'
. '&target=traps&field=service_templates&id=' . $trapsId;
$attrServicetemplate1 = array_merge(
$attrServicetemplates,
['defaultDatasetRoute' => $query]
);
$form->addElement('select2', 'service_templates', _('Linked Service Templates'), [], $attrServicetemplate1);
// Routing
$form->addElement(
'text',
'traps_routing_value',
_('Route definition'),
$attrsLongText
);
$form->addElement(
'text',
'traps_routing_filter_services',
_('Filter services'),
$attrsLongText
);
$form->addElement('checkbox', 'traps_routing_mode', _('Enable routing'));
// Matching rules
$cloneSetMaching = [];
$cloneSetMaching[] = $form->addElement(
'text',
'rule[#index#]',
_('String'),
['size' => '50', 'id' => 'rule_#index#', 'value' => '@OUTPUT@']
);
$cloneSetMaching[] = $form->addElement(
'text',
'regexp[#index#]',
_('Regexp'),
['size' => '50', 'id' => 'regexp_#index#', 'value' => '//']
);
$cloneSetMaching[] = $form->addElement(
'select',
'rulestatus[#index#]',
_('Status'),
[0 => _('OK'), 1 => _('Warning'), 2 => _('Critical'), 3 => _('Unknown')],
['id' => 'rulestatus_#index#', 'type' => 'select-one']
);
$cloneSetMaching[] = $form->addElement(
'select',
'ruleseverity[#index#]',
_('Severity'),
$severityArr,
['id' => 'ruleseverity_#index#', 'type' => 'select-one']
);
$form->addElement(
'text',
'traps_timeout',
_('Timeout'),
['size' => 5]
);
$form->addElement(
'text',
'traps_exec_interval',
_('Execution interval'),
['size' => 5]
);
$form->addElement(
'checkbox',
'traps_log',
_("Insert trap's information into database")
);
$form->addElement(
'text',
'traps_output_transform',
_('Output Transform'),
$attrsLongText
);
$form->addElement('textarea', 'traps_customcode', _('Custom code'), $attrsTextarea);
$form->addElement('select', 'traps_advanced_treatment_default', _('Advanced matching behavior'), [0 => _('If no match, submit default status'), 1 => _('If no match, disable submit'), 2 => _('If match, disable submit')], ['id' => 'traps_advanced_treatment']);
$excecution_type[] = $form->createElement('radio', 'traps_exec_interval_type', null, _('None'), '0');
$excecution_type[] = $form->createElement('radio', 'traps_exec_interval_type', null, _('By OID'), '1');
$excecution_type[] = $form->createElement(
'radio',
'traps_exec_interval_type',
null,
_('By OID and Host'),
'2'
);
$excecution_type[] = $form->createElement(
'radio',
'traps_exec_interval_type',
null,
_('By OID, Host and Service'),
'3'
);
$form->addGroup($excecution_type, 'traps_exec_interval_type', _('Execution type'), ' ');
$form->setDefaults(['traps_exec_interval_type' => '0']);
$excecution_method[] = $form->createElement('radio', 'traps_exec_method', null, _('Parallel'), '0');
$excecution_method[] = $form->createElement('radio', 'traps_exec_method', null, _('Sequential'), '1');
$form->addGroup($excecution_method, 'traps_exec_method', _('Execution method'), ' ');
$form->setDefaults(['traps_exec_method' => '0']);
$downtime[] = $form->createElement('radio', 'traps_downtime', null, _('None'), '0');
$downtime[] = $form->createElement('radio', 'traps_downtime', null, _('Real-Time'), '1');
$downtime[] = $form->createElement('radio', 'traps_downtime', null, _('History'), '2');
$form->addGroup($downtime, 'traps_downtime', _('Check Downtime'), ' ');
$form->setDefaults(['traps_downtime' => '0']);
// Pre exec
$cloneSet = [];
$cloneSet[] = $form->addElement(
'text',
'preexec[#index#]',
_('Preexec definition'),
['size' => '50', 'id' => 'preexec_#index#']
);
// Form Rules
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('traps_name', 'myReplace');
$form->addRule('traps_name', _('Compulsory Name'), 'required');
$form->addRule('traps_oid', _('Compulsory Name'), 'required');
$form->addRule('manufacturer_id', _('Compulsory Name'), 'required');
$form->addRule('traps_args', _('Compulsory Name'), 'required');
$form->registerRule('wellFormated', 'callback', [$trapObj, 'testOidFormat']);
$form->addRule('traps_oid', _('Bad OID Format'), 'wellFormated');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign('trap_adv_args', _('Advanced matching rules'));
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", '
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, -300, '
. 'SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
if ($o == TRAP_WATCH) {
// Just watch a Command information
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&traps_id=' . $trapsId . "'"]
);
}
$form->setDefaults($trap);
$form->freeze();
} elseif ($o == TRAP_MODIFY) {
// Modify a Command information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($trap);
} elseif ($o == TRAP_ADD) {
// Add a Command information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
}
$valid = false;
if ($form->validate()) {
$trapObj = new CentreonTraps($pearDB, $centreon, $form);
$trapParam = $form->getElement('traps_id');
if ($form->getSubmitValue('submitA')) {
$trapParam->setValue($trapObj->insert());
} elseif ($form->getSubmitValue('submitC')) {
$trapObj->update($trapParam->getValue());
}
$o = null;
$valid = true;
}
if ($valid) {
require_once $path . 'listTraps.php';
} else {
// prepare help texts
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->assign('tabTitle_1', _('Main'));
$tpl->assign('tabTitle_2', _('Relations'));
$tpl->assign('tabTitle_3', _('Advanced'));
$tpl->assign('subtitle0', _('Main information'));
$tpl->assign('subtitle0', _('Convert Trap information'));
$tpl->assign('subtitle1', _('Action 1 : Submit result to Monitoring Engine'));
$tpl->assign('subtitle2', _('Action 2 : Force rescheduling of service check'));
$tpl->assign('subtitle3', _('Action 3 : Execute a Command'));
$tpl->assign('subtitle4', _('Trap description'));
$tpl->assign('routingDefTxt', _('Route parameters'));
$tpl->assign('resourceTxt', _('Resources'));
$tpl->assign('preexecTxt', _('Pre execution commands'));
$tpl->assign('serviceTxt', _('Linked services'));
$tpl->assign('serviceTemplateTxt', _('Linked service templates'));
$tpl->assign('admin', $centreon->user->admin);
$tpl->assign('centreon_path', $centreon->optGen['oreon_path']);
$tpl->assign('cloneSet', $cloneSet);
$tpl->assign('cloneSetMaching', $cloneSetMaching);
$tpl->assign('preexeccmd_str', _('PREEXEC command'));
$tpl->display('formTraps.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/metaservice_dependency/formMetaServiceDependency.php | centreon/www/include/configuration/configObject/metaservice_dependency/formMetaServiceDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
//
// # Database retrieve information for Dependency
//
$dep = [];
$initialValues = [];
if (($o == MODIFY_DEPENDENCY || $o == WATCH_DEPENDENCY) && $dep_id) {
$DBRESULT = $pearDB->prepare('SELECT * FROM dependency WHERE dep_id = :dep_id LIMIT 1');
$DBRESULT->bindValue(':dep_id', $dep_id, PDO::PARAM_INT);
$DBRESULT->execute();
// Set base value
$dep = array_map('myDecode', $DBRESULT->fetchRow());
// Set Notification Failure Criteria
$dep['notification_failure_criteria'] = explode(',', $dep['notification_failure_criteria']);
foreach ($dep['notification_failure_criteria'] as $key => $value) {
$dep['notification_failure_criteria'][trim($value)] = 1;
}
// Set Execution Failure Criteria
$dep['execution_failure_criteria'] = explode(',', $dep['execution_failure_criteria']);
foreach ($dep['execution_failure_criteria'] as $key => $value) {
$dep['execution_failure_criteria'][trim($value)] = 1;
}
$DBRESULT->closeCursor();
}
//
// # Database retrieve information for differents elements list we need on the page
//
// Meta Service comes from DB -> Store in $metas Array
$metas = [];
$DBRESULT = $pearDB->query('SELECT meta_id, meta_name
FROM meta_service '
. $acl->queryBuilder('WHERE', 'meta_id', $metastr)
. ' ORDER BY meta_name');
while ($meta = $DBRESULT->fetchRow()) {
$metas[$meta['meta_id']] = $meta['meta_name'];
}
$DBRESULT->closeCursor();
//
// End of "database-retrieved" information
// #########################################################
// #########################################################
// Var information to format the element
//
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '10'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 150px;'];
$attrsTextarea = ['rows' => '3', 'cols' => '30'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_meta&action=list';
$attrMetas = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $route, 'multiple' => true, 'linkedObject' => 'centreonMeta'];
//
// # Form begin
//
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
if ($o == ADD_DEPENDENCY) {
$form->addElement('header', 'title', _('Add a Dependency'));
} elseif ($o == MODIFY_DEPENDENCY) {
$form->addElement('header', 'title', _('Modify a Dependency'));
} elseif ($o == WATCH_DEPENDENCY) {
$form->addElement('header', 'title', _('View a Dependency'));
}
//
// # Dependency basic information
//
$form->addElement('header', 'information', _('Information'));
$form->addElement('text', 'dep_name', _('Name'), $attrsText);
$form->addElement('text', 'dep_description', _('Description'), $attrsText);
$tab = [];
$tab[] = $form->createElement('radio', 'inherits_parent', null, _('Yes'), '1');
$tab[] = $form->createElement('radio', 'inherits_parent', null, _('No'), '0');
$form->addGroup($tab, 'inherits_parent', _('Parent relationship'), ' ');
$form->setDefaults(['inherits_parent' => '1']);
$tab = [];
$tab[] = $form->createElement(
'checkbox',
'o',
' ',
_('Ok'),
['id' => 'nOk', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'w',
' ',
_('Warning'),
['id' => 'nWarning', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unknown'),
['id' => 'nUnknown', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'c',
' ',
_('Critical'),
['id' => 'nCritical', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'p',
' ',
_('Pending'),
['id' => 'nPending', 'onClick' => 'applyNotificationRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'nNone', 'onClick' => 'applyNotificationRules(this);']
);
$form->addGroup($tab, 'notification_failure_criteria', _('Notification Failure Criteria'), ' ');
$tab = [];
$tab[] = $form->createElement(
'checkbox',
'o',
' ',
_('Ok'),
['id' => 'eOk', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'w',
' ',
_('Warning'),
['id' => 'eWarning', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unknown'),
['id' => 'eUnknown', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'c',
' ',
_('Critical'),
['id' => 'eCritical', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'p',
' ',
_('Pending'),
['id' => 'ePending', 'onClick' => 'applyExecutionRules(this);']
);
$tab[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'eNone', 'onClick' => 'applyExecutionRules(this);']
);
$form->addGroup($tab, 'execution_failure_criteria', _('Execution Failure Criteria'), ' ');
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_meta'
. '&action=defaultValues&target=dependency&field=dep_msParents&id=' . $dep_id;
$attrMeta1 = array_merge(
$attrMetas,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'dep_msParents', _('Meta Service Names'), [], $attrMeta1);
$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_meta'
. '&action=defaultValues&target=dependency&field=dep_msChilds&id=' . $dep_id;
$attrMeta2 = array_merge(
$attrMetas,
['defaultDatasetRoute' => $route]
);
$form->addElement('select2', 'dep_msChilds', _('Dependent Meta Service Names'), [], $attrMeta2);
$form->addElement('textarea', 'dep_comment', _('Comments'), $attrsTextarea);
$form->addElement('hidden', 'dep_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
//
// # Form Rules
//
$form->applyFilter('__ALL__', 'myTrim');
$form->addRule('dep_name', _('Compulsory Name'), 'required');
$form->addRule('dep_description', _('Required Field'), 'required');
$form->addRule('dep_msParents', _('Required Field'), 'required');
$form->addRule('dep_msChilds', _('Required Field'), 'required');
$form->registerRule('cycle', 'callback', 'testCycle');
$form->addRule('dep_msChilds', _('Circular Definition'), 'cycle');
$form->registerRule('exist', 'callback', 'testExistence');
$form->addRule('dep_name', _('Name is already in use'), 'exist');
$form->setRequiredNote("<font style='color: red;'>*</font> " . _('Required fields'));
$form->addRule('execution_failure_criteria', _('Required Field'), 'required');
$form->addRule('notification_failure_criteria', _('Required Field'), 'required');
//
// #End of form definition
//
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Just watch a Dependency information
if ($o == WATCH_DEPENDENCY) {
if ($centreon->user->access->page($p) != 2) {
$form->addElement(
'button',
'change',
_('Modify'),
['onClick' => "javascript:window.location.href='?p=" . $p . '&o=c&dep_id=' . $dep_id . "'"]
);
}
$form->setDefaults($dep);
$form->freeze();
} elseif ($o == MODIFY_DEPENDENCY) { // Modify a Dependency information
$subC = $form->addElement('submit', 'submitC', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults($dep);
} elseif ($o == ADD_DEPENDENCY) { // Add a Dependency information
$subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
$res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);
$form->setDefaults(['inherits_parent', '0']);
}
$tpl->assign(
'helpattr',
'TITLE, "' . _('Help') . '", CLOSEBTN, true, FIX, [this, 0, 5], BGCOLOR, "#ffff99", BORDERCOLOR, "orange", '
. 'TITLEFONTCOLOR, "black", TITLEBGCOLOR, "orange", CLOSEBTNCOLORS, ["","black", "white", "red"], WIDTH, '
. '-300, SHADOW, true, TEXTALIGN, "justify"'
);
// prepare help texts
$helptext = '';
include_once 'include/configuration/configObject/service_dependency/help.php';
foreach ($help as $key => $text) {
$helptext .= '<span style="display:none" id="help:' . $key . '">' . $text . '</span>' . "\n";
}
$tpl->assign('helptext', $helptext);
$valid = false;
if ($form->validate()) {
$depObj = $form->getElement('dep_id');
if ($form->getSubmitValue('submitA')) {
$depObj->setValue(insertMetaServiceDependencyInDB());
} elseif ($form->getSubmitValue('submitC')) {
updateMetaServiceDependencyInDB($depObj->getValue('dep_id'));
}
$o = null;
$valid = true;
}
if ($valid) {
require_once 'listMetaServiceDependency.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$renderer->setRequiredTemplate('{$label} <font color="red" size="1">*</font>');
$renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('formMetaServiceDependency.ihtml');
}
?>
<script type="text/javascript">
function applyNotificationRules(object) {
if (object.id == "nNone" && object.checked) {
document.getElementById('nOk').checked = false;
document.getElementById('nWarning').checked = false;
document.getElementById('nUnknown').checked = false;
document.getElementById('nCritical').checked = false;
document.getElementById('nPending').checked = false;
}
else {
document.getElementById('nNone').checked = false;
}
}
function applyExecutionRules(object) {
if (object.id == "eNone" && object.checked) {
document.getElementById('eOk').checked = false;
document.getElementById('eWarning').checked = false;
document.getElementById('eUnknown').checked = false;
document.getElementById('eCritical').checked = false;
document.getElementById('ePending').checked = false;
}
else {
document.getElementById('eNone').checked = false;
}
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/metaservice_dependency/listMetaServiceDependency.php | centreon/www/include/configuration/configObject/metaservice_dependency/listMetaServiceDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
$list = $_GET['list'] ?? null;
$aclCond = '';
if (! $centreon->user->admin) {
$aclCond = " AND meta_service_meta_id IN ({$metastr}) ";
}
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchMSD'] ?? $_GET['searchMSD'] ?? null
);
if (isset($_POST['searchMSD']) || isset($_GET['searchMSD'])) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $search;
} else {
// restoring saved values
$search = $centreon->historySearch[$url]['search'] ?? null;
}
// Dependency list
$rq = 'SELECT SQL_CALC_FOUND_ROWS dep_id, dep_name, dep_description FROM dependency dep';
$rq .= " WHERE ((SELECT DISTINCT COUNT(*)
FROM dependency_metaserviceParent_relation dmspr
WHERE dmspr.dependency_dep_id = dep.dep_id {$aclCond}) > 0
OR (SELECT DISTINCT COUNT(*)
FROM dependency_metaserviceChild_relation dmspr
WHERE dmspr.dependency_dep_id = dep.dep_id {$aclCond}) > 0)";
if ($search) {
$rq .= " AND (dep_name LIKE '%" . htmlentities($search, ENT_QUOTES, 'UTF-8')
. "%' OR dep_description LIKE '%" . htmlentities($search, ENT_QUOTES, 'UTF-8') . "%')";
}
$rq .= ' ORDER BY dep_name, dep_description LIMIT ' . $num * $limit . ', ' . $limit;
$dbResult = $pearDB->query($rq);
$rows = $pearDB->query('SELECT FOUND_ROWS()')->fetchColumn();
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? 'w' : 'r';
$tpl->assign('mode_access', $lvl_access);
// start header menu
$tpl->assign('headerMenu_name', _('Name'));
$tpl->assign('headerMenu_description', _('Description'));
$tpl->assign('headerMenu_options', _('Options'));
$search = tidySearchKey($search, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
for ($i = 0; $dep = $dbResult->fetch(); $i++) {
$moptions = '';
$selectedElements = $form->addElement('checkbox', 'select[' . $dep['dep_id'] . ']');
$moptions .= ' <input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) return false;'
. "\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr[" . $dep['dep_id'] . "]' />";
$elemArr[$i] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure($dep['dep_name']), 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&dep_id=' . $dep['dep_id'], 'RowMenu_description' => CentreonUtils::escapeSecure($dep['dep_description']), 'RowMenu_options' => $moptions];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'delConfirm' => _('Do you confirm the deletion ?')]
);
include './include/common/checkPagination.php';
// Toolbar select more_actions
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
</script>
<?php
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o1'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o1'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o1'].value); submit();} "
. "else if (this.form.elements['o1'].selectedIndex == 3) {"
. " setO(this.form.elements['o1'].value); submit();} "
. ''];
$form->addElement(
'select',
'o1',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs1
);
$form->setDefaults(['o1' => null]);
$o1 = $form->getElement('o1');
$o1->setValue(null);
$attrs = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. " if (this.form.elements['o2'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['o2'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['o2'].value); submit();} "
. "else if (this.form.elements['o2'].selectedIndex == 3) {"
. " setO(this.form.elements['o2'].value); submit();} "
. ''];
$form->addElement(
'select',
'o2',
null,
[null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete')],
$attrs
);
$form->setDefaults(['o2' => null]);
$o2 = $form->getElement('o2');
$o2->setValue(null);
$tpl->assign('limit', $limit);
$tpl->assign('searchMSD', $search);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listMetaServiceDependency.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/metaservice_dependency/MetaServiceDependency.php | centreon/www/include/configuration/configObject/metaservice_dependency/MetaServiceDependency.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
const ADD_DEPENDENCY = 'a';
const WATCH_DEPENDENCY = 'w';
const MODIFY_DEPENDENCY = 'c';
const DUPLICATE_DEPENDENCY = 'm';
const DELETE_DEPENDENCY = 'd';
// Path to the configuration dir
$path = './include/configuration/configObject/metaservice_dependency/';
// PHP functions
require_once $path . 'DB-Func.php';
require_once './include/common/common-Func.php';
$dep_id = filter_var(
$_GET['dep_id'] ?? $_POST['dep_id'] ?? null,
FILTER_VALIDATE_INT
);
$select = filter_var_array(
getSelectOption(),
FILTER_VALIDATE_INT
);
$dupNbr = filter_var_array(
getDuplicateNumberOption(),
FILTER_VALIDATE_INT
);
// Set the real page
if (isset($ret) && is_array($ret) && $ret['topology_page'] != '' && $p != $ret['topology_page']) {
$p = $ret['topology_page'];
}
$acl = $oreon->user->access;
$metastr = $acl->getMetaServiceString();
switch ($o) {
case ADD_DEPENDENCY:
case WATCH_DEPENDENCY:
case MODIFY_DEPENDENCY:
require_once $path . 'formMetaServiceDependency.php';
break;
case DUPLICATE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
multipleMetaServiceDependencyInDB(
is_array($select) ? $select : [],
is_array($dupNbr) ? $dupNbr : []
);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetaServiceDependency.php';
break;
case DELETE_DEPENDENCY:
purgeOutdatedCSRFTokens();
if (isCSRFTokenValid()) {
purgeCSRFToken();
deleteMetaServiceDependencyInDB(is_array($select) ? $select : []);
} else {
unvalidFormMessage();
}
require_once $path . 'listMetaServiceDependency.php';
break;
default:
require_once $path . 'listMetaServiceDependency.php';
break;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/metaservice_dependency/DB-Func.php | centreon/www/include/configuration/configObject/metaservice_dependency/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($oreon)) {
exit();
}
function testExistence($name = null)
{
global $pearDB;
global $form;
CentreonDependency::purgeObsoleteDependencies($pearDB);
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('dep_id');
}
$query = "SELECT dep_name, dep_id FROM dependency WHERE dep_name = '"
. htmlentities($name, ENT_QUOTES, 'UTF-8') . "'";
$dbResult = $pearDB->query($query);
$dep = $dbResult->fetch();
// Modif case
if ($dbResult->rowCount() >= 1 && $dep['dep_id'] == $id) {
return true;
} // Duplicate entry
return ! ($dbResult->rowCount() >= 1 && $dep['dep_id'] != $id);
}
function testCycle($childs = null)
{
global $pearDB;
global $form;
$parents = [];
$childs = [];
if (isset($form)) {
$parents = $form->getSubmitValue('dep_msParents');
$childs = $form->getSubmitValue('dep_msChilds');
$childs = array_flip($childs);
}
foreach ($parents as $parent) {
if (array_key_exists($parent, $childs)) {
return false;
}
}
return true;
}
function deleteMetaServiceDependencyInDB($dependencies = [])
{
global $pearDB;
foreach ($dependencies as $key => $value) {
$dbResult = $pearDB->query("DELETE FROM dependency WHERE dep_id = '" . $key . "'");
}
}
function multipleMetaServiceDependencyInDB($dependencies = [], $nbrDup = [])
{
foreach ($dependencies as $key => $value) {
global $pearDB;
$dbResult = $pearDB->query("SELECT * FROM dependency WHERE dep_id = '" . $key . "' LIMIT 1");
$row = $dbResult->fetch();
$row['dep_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if ($key2 == 'dep_name') {
$dep_name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$val
? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL')
: $val .= ($value2 != null ? ("'" . $value2 . "'") : 'NULL');
}
if (testExistence($dep_name)) {
$rq = $val ? 'INSERT INTO dependency VALUES (' . $val . ')' : null;
$pearDB->query($rq);
$dbResult = $pearDB->query('SELECT MAX(dep_id) FROM dependency');
$maxId = $dbResult->fetch();
if (isset($maxId['MAX(dep_id)'])) {
$query = 'SELECT DISTINCT meta_service_meta_id FROM dependency_metaserviceParent_relation '
. "WHERE dependency_dep_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$statement = $pearDB->prepare('INSERT INTO dependency_metaserviceParent_relation '
. 'VALUES (:maxId, :metaId)');
while ($ms = $dbResult->fetch()) {
$statement->bindValue(':maxId', (int) $maxId['MAX(dep_id)'], PDO::PARAM_INT);
$statement->bindValue(':metaId', (int) $ms['meta_service_meta_id'], PDO::PARAM_INT);
$statement->execute();
}
$dbResult->closeCursor();
$query = 'SELECT DISTINCT meta_service_meta_id FROM dependency_metaserviceChild_relation '
. "WHERE dependency_dep_id = '" . $key . "'";
$dbResult = $pearDB->query($query);
$childStatement = $pearDB->prepare('INSERT INTO dependency_metaserviceChild_relation '
. 'VALUES (:maxId, :metaId)');
while ($ms = $dbResult->fetch()) {
$childStatement->bindValue(':maxId', (int) $maxId['MAX(dep_id)'], PDO::PARAM_INT);
$childStatement->bindValue(':metaId', (int) $ms['meta_service_meta_id'], PDO::PARAM_INT);
$childStatement->execute();
}
$dbResult->closeCursor();
}
}
}
}
}
function updateMetaServiceDependencyInDB($dep_id = null)
{
if (! $dep_id) {
exit();
}
updateMetaServiceDependency($dep_id);
updateMetaServiceDependencyMetaServiceParents($dep_id);
updateMetaServiceDependencyMetaServiceChilds($dep_id);
}
function insertMetaServiceDependencyInDB()
{
$dep_id = insertMetaServiceDependency();
updateMetaServiceDependencyMetaServiceParents($dep_id);
updateMetaServiceDependencyMetaServiceChilds($dep_id);
return $dep_id;
}
/**
* Create a metaservice dependency
*
* @return int
*/
function insertMetaServiceDependency(): int
{
global $form, $pearDB, $centreon;
$resourceValues = sanitizeResourceParameters($form->getSubmitValues());
$statement = $pearDB->prepare(
'INSERT INTO `dependency`
(dep_name, dep_description, inherits_parent, execution_failure_criteria,
notification_failure_criteria, dep_comment)
VALUES (:depName, :depDescription, :inheritsParent, :executionFailure,
:notificationFailure, :depComment)'
);
$statement->bindValue(':depName', $resourceValues['dep_name'], PDO::PARAM_STR);
$statement->bindValue(':depDescription', $resourceValues['dep_description'], PDO::PARAM_STR);
$statement->bindValue(':inheritsParent', $resourceValues['inherits_parent'], PDO::PARAM_STR);
$statement->bindValue(':executionFailure', $resourceValues['execution_failure_criteria'], PDO::PARAM_STR);
$statement->bindValue(':notificationFailure', $resourceValues['notification_failure_criteria'], PDO::PARAM_STR);
$statement->bindValue(':depComment', $resourceValues['dep_comment'], PDO::PARAM_STR);
$statement->execute();
$dbResult = $pearDB->query('SELECT MAX(dep_id) FROM dependency');
$depId = $dbResult->fetch();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($resourceValues);
$centreon->CentreonLogAction->insertLog(
'metaservice dependency',
$depId['MAX(dep_id)'],
$resourceValues['dep_name'],
'a',
$fields
);
return (int) $depId['MAX(dep_id)'];
}
/**
* Update a metaservice dependency
*
* @param null|int $depId
*/
function updateMetaServiceDependency($depId = null): void
{
if (! $depId) {
exit();
}
global $form, $pearDB, $centreon;
$resourceValues = sanitizeResourceParameters($form->getSubmitValues());
$statement = $pearDB->prepare(
'UPDATE `dependency`
SET dep_name = :depName,
dep_description = :depDescription,
inherits_parent = :inheritsParent,
execution_failure_criteria = :executionFailure,
notification_failure_criteria = :notificationFailure,
dep_comment = :depComment
WHERE dep_id = :depId'
);
$statement->bindValue(':depName', $resourceValues['dep_name'], PDO::PARAM_STR);
$statement->bindValue(':depDescription', $resourceValues['dep_description'], PDO::PARAM_STR);
$statement->bindValue(':inheritsParent', $resourceValues['inherits_parent'], PDO::PARAM_STR);
$statement->bindValue(':executionFailure', $resourceValues['execution_failure_criteria'], PDO::PARAM_STR);
$statement->bindValue(':notificationFailure', $resourceValues['notification_failure_criteria'], PDO::PARAM_STR);
$statement->bindValue(':depComment', $resourceValues['dep_comment'], PDO::PARAM_STR);
$statement->bindValue(':depId', $depId, PDO::PARAM_INT);
$statement->execute();
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($resourceValues);
$centreon->CentreonLogAction->insertLog(
'metaservice dependency',
$depId,
$resourceValues['dep_name'],
'c',
$fields
);
}
/**
* sanitize resources parameter for Create / Update a meta service dependency
*
* @param array<string, mixed> $resources
* @return array<string, mixed>
*/
function sanitizeResourceParameters(array $resources): array
{
$sanitizedParameters = [];
$sanitizedParameters['dep_name'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_name']);
if (empty($sanitizedParameters['dep_name'])) {
throw new InvalidArgumentException(_("Dependency name can't be empty"));
}
$sanitizedParameters['dep_description'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_description']);
if (empty($sanitizedParameters['dep_description'])) {
throw new InvalidArgumentException(_("Dependency description can't be empty"));
}
$resources['inherits_parent']['inherits_parent'] == 1
? $sanitizedParameters['inherits_parent'] = '1'
: $sanitizedParameters['inherits_parent'] = '0';
$sanitizedParameters['execution_failure_criteria'] = HtmlAnalyzer::sanitizeAndRemoveTags(
implode(
',',
array_keys($resources['execution_failure_criteria'])
)
);
$sanitizedParameters['notification_failure_criteria'] = HtmlAnalyzer::sanitizeAndRemoveTags(
implode(
',',
array_keys($resources['notification_failure_criteria'])
)
);
$sanitizedParameters['dep_comment'] = HtmlAnalyzer::sanitizeAndRemoveTags($resources['dep_comment']);
return $sanitizedParameters;
}
function updateMetaServiceDependencyMetaServiceParents($dep_id = null)
{
if (! $dep_id) {
exit();
}
global $form;
global $pearDB;
$rq = 'DELETE FROM dependency_metaserviceParent_relation ';
$rq .= "WHERE dependency_dep_id = '" . $dep_id . "'";
$pearDB->query($rq);
$ret = [];
$ret = CentreonUtils::mergeWithInitialValues($form, 'dep_msParents');
$counter = count($ret);
for ($i = 0; $i < $counter; $i++) {
$rq = 'INSERT INTO dependency_metaserviceParent_relation ';
$rq .= '(dependency_dep_id, meta_service_meta_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $dep_id . "', '" . $ret[$i] . "')";
$pearDB->query($rq);
}
}
function updateMetaServiceDependencyMetaServiceChilds($dep_id = null)
{
if (! $dep_id) {
exit();
}
global $form;
global $pearDB;
$rq = 'DELETE FROM dependency_metaserviceChild_relation ';
$rq .= "WHERE dependency_dep_id = '" . $dep_id . "'";
$pearDB->query($rq);
$ret = [];
$ret = CentreonUtils::mergeWithInitialValues($form, 'dep_msChilds');
$counter = count($ret);
for ($i = 0; $i < $counter; $i++) {
$rq = 'INSERT INTO dependency_metaserviceChild_relation ';
$rq .= '(dependency_dep_id, meta_service_meta_id) ';
$rq .= 'VALUES ';
$rq .= "('" . $dep_id . "', '" . $ret[$i] . "')";
$pearDB->query($rq);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact/listContact.php | centreon/www/include/configuration/configObject/contact/listContact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($centreon)) {
exit();
}
/**
* allowed access
*/
const WRITE = 'w';
const READ = 'r';
/**
* specific action available to admins
*/
const LDAP_SYNC = 'sync';
include_once './class/centreonUtils.class.php';
include './include/common/autoNumLimit.php';
// Create Timeperiod Cache
$tpCache = ['' => ''];
$dbResult = $pearDB->query('SELECT tp_name, tp_id FROM timeperiod');
while ($data = $dbResult->fetch()) {
$tpCache[$data['tp_id']] = $data['tp_name'];
}
unset($data);
$dbResult->closeCursor();
$selectedContact = filter_var(
$_GET['selectedContact'] ?? null,
FILTER_VALIDATE_INT
);
$searchContact = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['searchC'] ?? $_GET['searchC'] ?? null
);
$search = HtmlAnalyzer::sanitizeAndRemoveTags(
$_POST['Search'] ?? $_GET['Search'] ?? null
);
$contactGroup = filter_var(
$_POST['contactGroup'] ?? $_GET['contactGroup'] ?? 0,
FILTER_VALIDATE_INT
);
if ($search) {
// saving filters values
$centreon->historySearch[$url] = [];
$centreon->historySearch[$url]['search'] = $searchContact;
$centreon->historySearch[$url]['contactGroup'] = $contactGroup;
} else {
// restoring saved values
$searchContact = $centreon->historySearch[$url]['search'] ?? null;
$contactGroup = $centreon->historySearch[$url]['contactGroup'] ?? 0;
}
$clauses = [];
if ($searchContact) {
$clauses = ['contact_name' => ['LIKE', '%' . $searchContact . '%'], 'contact_alias' => ['OR', 'LIKE', '%' . $searchContact . '%']];
}
$join = [];
if (! empty($contactGroup)) {
$join = [['table' => 'contactgroup_contact_relation', 'condition' => 'contact_contact_id = contact_id']];
$clauses['contactgroup_cg_id'] = $searchContact ? [') AND (', '=', $contactGroup] : ['=', $contactGroup];
}
$aclOptions = ['fields' => ['contact_id', 'timeperiod_tp_id', 'timeperiod_tp_id2', 'contact_name', 'contact_alias', 'contact_lang', 'contact_oreon', 'contact_host_notification_options', 'contact_service_notification_options', 'contact_activate', 'contact_email', 'contact_admin', 'contact_register', 'contact_auth_type', 'contact_ldap_required_sync', 'blocking_time'], 'keys' => ['contact_id'], 'order' => ['contact_name'], 'conditions' => $clauses, 'join' => $join];
$contacts = $acl->getContactAclConf($aclOptions);
$rows = count($contacts);
include './include/common/checkPagination.php';
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Access level
$lvl_access = ($centreon->user->access->page($p) == 1) ? WRITE : READ;
$tpl->assign('mode_access', $lvl_access);
// massive contacts data synchronization request using the event handler
$chosenContact = [];
if ($centreon->user->admin && $selectedContact && $o === 'sync') {
$chosenContact[$selectedContact] = 1;
synchronizeContactWithLdap($chosenContact);
}
// start header menu
$tpl->assign('headerMenu_name', _('Full Name'));
$tpl->assign('headerMenu_desc', _('Alias / Login'));
$tpl->assign('headerMenu_email', _('Email'));
$tpl->assign('headerMenu_hostNotif', _('Host Notification Period'));
$tpl->assign('headerMenu_svNotif', _('Services Notification Period'));
$tpl->assign('headerMenu_lang', _('Language'));
$tpl->assign('headerMenu_status', _('Status'));
$tpl->assign('headerMenu_access', _('Access'));
$tpl->assign('headerMenu_accessTooltip', _("Contacts with the 'Reach Centreon Front-end' option enabled"));
$tpl->assign('headerMenu_admin', _('Admin'));
$tpl->assign('headerMenu_options', _('Options'));
// header title displayed only to admins
if ($centreon->user->admin) {
$tpl->assign('headerMenu_refreshLdap', _('Refresh'));
$tpl->assign('headerMenu_unblock', _('Unblock'));
$tpl->assign('headerMenu_refreshLdapTitleTooltip', _('To manually request a LDAP synchronization of a contact'));
}
// Contact list
$aclOptions['pages'] = $num * $limit . ', ' . $limit;
$contacts = $acl->getContactAclConf($aclOptions);
$searchContact = tidySearchKey($searchContact, $advanced_search);
$form = new HTML_QuickFormCustom('select_form', 'POST', '?p=' . $p);
$contactGrRoute = './api/internal.php?object=centreon_configuration_contactgroup&action=list';
$attrContactgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $contactGrRoute, 'multiple' => false, 'defaultDataset' => $contactGroup, 'linkedObject' => 'centreonContactgroup'];
$form->addElement('select2', 'contactGroup', '', [], $attrContactgroups);
// Different style between each lines
$style = 'one';
$attrBtnSuccess = ['class' => 'btc bt_success', 'onClick' => "window.history.replaceState('', '', '?p=" . $p . "');"];
$form->addElement('submit', 'Search', _('Search'), $attrBtnSuccess);
$contactTypeIcon = [1 => returnSvg('www/img/icons/admin.svg', 'var(--icons-fill-color)', 22, 22), 2 => returnSvg('www/img/icons/user.svg', 'var(--icons-fill-color)', 22, 22), 3 => returnSvg('www/img/icons/user-template.svg', 'var(--icons-fill-color)', 22, 22)];
$contactTypeIconTitle = [1 => _('This user is an administrator.'), 2 => _('This user is a simple user.'), 3 => _('This is a contact template.')];
// refresh LDAP icon and tooltip
$refreshLdapHelp = [0 => _("This user isn't linked to a LDAP"), 1 => _('Manually request to synchronize this contact with his LDAP'), 2 => _('Already requested, please wait the CRON execution or for the user to login')];
// setting a default value for non admin users
$refreshLdapBadge = [0 => ''];
// Fill a tab with a multidimensional Array we put in $tpl
$elemArr = [];
$centreonToken = createCSRFToken();
// Get the count of blocked contacts
$blockedContactsCount = count(array_filter(array_column($contacts, 'blocking_time')));
foreach ($contacts as $contact) {
if ($centreon->user->get_id() == $contact['contact_id']) {
$selectedElements = $form->addElement(
'checkbox',
'select[' . $contact['contact_id'] . ']',
'',
'',
'disabled'
);
} else {
$selectedElements = $form->addElement('checkbox', 'select[' . $contact['contact_id'] . ']');
}
$moptions = '';
if ($contact['contact_id'] != $centreon->user->get_id()) {
if ($contact['contact_activate']) {
$moptions .= "<a href='main.php?p=" . $p . '&contact_id=' . $contact['contact_id']
. '&o=u&limit=' . $limit . '&num=' . $num . '&search=' . $searchContact
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/disabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Disabled') . "'></a> ";
} else {
$moptions .= "<a href='main.php?p=" . $p . '&contact_id=' . $contact['contact_id']
. '&o=s&limit=' . $limit . '&num=' . $num . '&search=' . $searchContact
. '¢reon_token=' . $centreonToken
. "'><img src='img/icons/enabled.png' class='ico-14 margin_right' border='0' alt='"
. _('Enabled') . "'></a> ";
}
} else {
$moptions .= ' ';
}
$moptions .= ' ';
$moptions .= '<input onKeypress="if(event.keyCode > 31 && (event.keyCode < 45 || event.keyCode > 57)) '
. 'event.returnValue = false; if(event.which > 31 && (event.which < 45 || event.which > 57)) '
. "return false;\" maxlength=\"3\" size=\"3\" value='1' style=\"margin-bottom:0px;\" name='dupNbr["
. $contact['contact_id'] . "]' />";
$blockedUserIcon = "
<a href='./main.get.php?p=" . $p . '&o=un&contact_id=' . $contact['contact_id'] . '¢reon_token=' . $centreonToken . "' class='unblockUserLink' onclick=\"if(confirm('" . _('Do you really want to unblock this user?') . "')) {
window.location.href = this.href;
}\" >
<img src='img/icons/lock_closed.png' class='ico-22 margin_auto' border='0'>
</a>";
$contact_type = 0;
if ($contact['contact_register']) {
$contact_type = $contact['contact_admin'] == 1 ? 1 : 2;
} else {
$contact_type = 3;
}
// linking the user to its LDAP badge
$isLinkedToLdap = 0;
// options displayed only to admins for contacts linked to an LDAP
if ($centreon->user->admin && $contact['contact_auth_type'] === 'ldap') {
// synchronization is already required
if ($contact['contact_ldap_required_sync'] === '1') {
$isLinkedToLdap = 2;
$refreshLdapBadge[2]
= "<span class='ico-18'>"
. returnSvg(
'www/img/icons/refresh.svg',
'var(--icons-disabled-fill-color)',
18,
18
)
. '</span>';
} else {
$isLinkedToLdap = 1;
$refreshLdapBadge[1]
= "<span class='ico-18' onclick='submitSync(" . $p . ', ' . $contact['contact_id'] . ")'>"
. returnSvg(
'www/img/icons/refresh.svg',
'var(--icons-fill-color)',
18,
18
)
. '</span>';
}
}
$elemArr[] = ['MenuClass' => 'list_' . $style, 'RowMenu_select' => $selectedElements->toHtml(), 'RowMenu_name' => CentreonUtils::escapeSecure(
html_entity_decode($contact['contact_name'], ENT_QUOTES, 'UTF-8'),
CentreonUtils::ESCAPE_ILLEGAL_CHARS
), 'RowMenu_ico' => $contactTypeIcon[$contact_type] ?? '', 'RowMenu_ico_title' => $contactTypeIconTitle[$contact_type] ?? '', 'RowMenu_type' => $contact_type, 'RowMenu_link' => 'main.php?p=' . $p . '&o=c&contact_id=' . $contact['contact_id'], 'RowMenu_desc' => CentreonUtils::escapeSecure(
html_entity_decode($contact['contact_alias'], ENT_QUOTES, 'UTF-8'),
CentreonUtils::ESCAPE_ILLEGAL_CHARS
), 'RowMenu_email' => $contact['contact_email'], 'RowMenu_hostNotif' => html_entity_decode(
$tpCache[($contact['timeperiod_tp_id'] ?? '')],
ENT_QUOTES,
'UTF-8'
) . ' (' . ($contact['contact_host_notification_options'] ?? '') . ')', 'RowMenu_svNotif' => html_entity_decode(
$tpCache[($contact['timeperiod_tp_id2'] ?? '')],
ENT_QUOTES,
'UTF-8'
) . ' (' . ($contact['contact_service_notification_options'] ?? '') . ')', 'RowMenu_lang' => $contact['contact_lang'], 'RowMenu_access' => $contact['contact_oreon'] ? _('Enabled') : _('Disabled'), 'RowMenu_admin' => $contact['contact_admin'] ? _('Yes') : _('No'), 'RowMenu_status' => $contact['contact_activate'] ? _('Enabled') : _('Disabled'), 'RowMenu_badge' => $contact['contact_activate'] ? 'service_ok' : 'service_critical', 'RowMenu_refreshLdap' => $isLinkedToLdap ? $refreshLdapBadge[$isLinkedToLdap] : '', 'RowMenu_refreshLdapHelp' => $isLinkedToLdap ? $refreshLdapHelp[$isLinkedToLdap] : '', 'RowMenu_options' => $moptions, 'RowMenu_unblock' => $contact['blocking_time'] !== null ? $blockedUserIcon : '-'];
$style = $style != 'two' ? 'two' : 'one';
}
$tpl->assign('isAdmin', $centreon->user->admin);
$tpl->assign('blockedContactsCount', $blockedContactsCount);
$tpl->assign('elemArr', $elemArr);
// Different messages we put in the template
$tpl->assign(
'msg',
['addL' => 'main.php?p=' . $p . '&o=a', 'addT' => _('Add'), 'ldap_importL' => 'main.php?p=' . $p . '&o=li', 'ldap_importT' => _('LDAP Import'), 'view_notif' => _('View contact notifications')]
);
// Display import ldap users button if ldap is configured
$res = $pearDB->query(
'SELECT count(ar_id) as count_ldap '
. 'FROM auth_ressource '
);
$row = $res->fetch();
if ($row['count_ldap'] > 0) {
$tpl->assign('ldap', '1');
}
?>
<script type="text/javascript">
function setO(_i) {
document.forms['form'].elements['o'].value = _i;
}
// ask for confirmation when requesting to resynchronize contact data from the LDAP
function submitSync(p, contactId) {
// msg = localized message to be displayed in the confirmation popup
let msg = "<?= _('If the contact is connected, all his instances will be closed. Are you sure you want to '
. 'request a data synchronization at the next login of this Contact ?'); ?>";
if (confirm(msg)) {
$.ajax({
url: './api/internal.php?object=centreon_ldap_synchro&action=requestLdapSynchro',
type: 'POST',
async: false,
data: {contactId: contactId},
success: function(data) {
if (data === true) {
window.location.href = "?p=" + p;
}
}
});
}
}
</script>
<?php
// Manage options
foreach (['o1', 'o2'] as $option) {
$attrs1 = ['onchange' => 'javascript: '
. ' var bChecked = isChecked(); '
. "if (this.form.elements['" . $option . "'].selectedIndex != 0 && !bChecked) {"
. " alert('" . _('Please select one or more items') . "'); return false;} "
. "if (this.form.elements['" . $option . "'].selectedIndex == 1 && confirm('"
. _('Do you confirm the duplication ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 2 && confirm('"
. _('Do you confirm the deletion ?') . "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 3 || this.form.elements['"
. $option . "'].selectedIndex == 4 || this.form.elements['" . $option . "'].selectedIndex == 5){"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 6 && confirm('"
. _('The chosen contact(s) will be disconnected. Do you confirm the LDAP synchronization request ?')
. "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "else if (this.form.elements['" . $option . "'].selectedIndex == 7 && confirm('"
. _('The user(s) will be unblocked. Do you confirm the request?')
. "')) {"
. " setO(this.form.elements['" . $option . "'].value); submit();} "
. "this.form.elements['" . $option . "'].selectedIndex = 0"];
$formOptions = [null => _('More actions...'), 'm' => _('Duplicate'), 'd' => _('Delete'), 'mc' => _('Mass Change'), 'ms' => _('Enable'), 'mu' => _('Disable')];
// adding a specific option available only for admin users
if ($centreon->user->admin) {
$formOptions['sync'] = _('Synchronize LDAP');
}
// adding a specific option available only for admin users and if at least one user is blocked
if ($centreon->user->admin && $blockedContactsCount) {
$formOptions['mun'] = _('Unblock');
}
$form->addElement(
'select',
$option,
null,
$formOptions,
$attrs1
);
$form->setDefaults([$option => null]);
$o1 = $form->getElement($option);
$o1->setValue(null);
$o1->setSelected(null);
}
$tpl->assign('limit', $limit);
$tpl->assign('searchC', $searchContact);
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->display('listContact.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact/ldapImportContact.php | centreon/www/include/configuration/configObject/contact/ldapImportContact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($oreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
$attrsText = ['size' => '80'];
$attrsText2 = ['size' => '5'];
// Form begin
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
$form->addElement('header', 'title', _('LDAP Import'));
// Command information
$form->addElement('header', 'options', _('LDAP Servers'));
$form->addElement('text', 'ldap_search_filter', _('Search Filter'), $attrsText);
$form->addElement('header', 'result', _('Search Result'));
$form->addElement('header', 'ldap_search_result_output', _('Result'));
$link = 'LdapSearch()';
$form->addElement('button', 'ldap_search_button', _('Search'), ['class' => 'btc bt_success', 'onClick' => $link]);
$form->addElement('hidden', 'contact_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
$tpl->assign(
'ldap_search_filter_help',
_('Active Directory :') . ' (&(objectClass=user)(samaccounttype=805306368)(objectCategory=person)(cn=*))<br />'
. _('Lotus Domino :') . ' (&(objectClass=person)(cn=*))<br />' . _('OpenLDAP :') . ' (&(objectClass=person)(cn=*))'
);
$tpl->assign('ldap_search_filter_help_title', _('Filter Examples'));
$tpl->assign(
'javascript',
'<script type="text/javascript" src="./include/common/javascript/ContactAjaxLDAP/ajaxLdapSearch.js"></script>'
);
$query = "SELECT ar.ar_id, ar_name, REPLACE(ari_value, '%s', '*') as filter "
. 'FROM auth_ressource ar '
. 'LEFT JOIN auth_ressource_info ari ON ari.ar_id = ar.ar_id '
. "WHERE ari.ari_name = 'user_filter' AND ar.ar_enable = '1' "
. 'ORDER BY ar_name';
$res = $pearDB->query($query);
$ldapConfList = '';
while ($row = $res->fetch()) {
if ($res->rowCount() == 1) {
$ldapConfList .= "<input type='checkbox' name='ldapConf[" . $row['ar_id'] . "]'/ checked='true'> "
. $row['ar_name'];
} else {
$ldapConfList .= "<input type='checkbox' name='ldapConf[" . $row['ar_id'] . "]'/> " . $row['ar_name'];
}
$ldapConfList .= '<br/>';
$ldapConfList .= _('Filter') . ": <input size='80' type='text' value='" . $row['filter']
. "' name='ldap_search_filter[" . $row['ar_id'] . "]'/>";
$ldapConfList .= '<br/><br/>';
}
// List available contacts to choose which one we want to import
if ($o == 'li') {
$subA = $form->addElement('submit', 'submitA', _('Import'), ['class' => 'btc bt_success']);
}
$valid = false;
if ($form->validate()) {
if (isset($_POST['contact_select']['select']) && $form->getSubmitValue('submitA')) {
// extracting the chosen contacts Id from the POST
$selectedUsers = $_POST['contact_select']['select'];
unset($_POST['contact_select']['select']);
// removing the useless data sent
$arrayToReturn = [];
foreach ($_POST['contact_select'] as $key => $subKey) {
$arrayToReturn[$key] = array_intersect_key($_POST['contact_select'][$key], $selectedUsers);
}
// restoring the filtered $_POST['contact_select']['select'] as it's needed in some DB-Func.php functions
$arrayToReturn['select'] = $selectedUsers;
$_POST['contact_select'] = $arrayToReturn;
unset($selectedUsers, $arrayToReturn);
insertLdapContactInDB($_POST['contact_select']);
}
$form->freeze();
$valid = true;
}
if ($valid) {
require_once $path . 'listContact.php';
} else {
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('ldapServers', _('Import from LDAP servers'));
$tpl->assign('ldapConfList', $ldapConfList);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('o', $o);
$tpl->display('ldapImportContact.ihtml');
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact/help.php | centreon/www/include/configuration/configObject/contact/help.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
$help = [];
$help['mc_update'] = dgettext(
'help',
'Choose the update mode for the below field: incremental adds the selected values, replacement overwrites '
. 'the original values.'
);
// General Information
$help['contact_name'] = dgettext(
'help',
'The full name is used to identify the contact in contact group definitions and in notifications.'
);
$help['alias'] = dgettext('help', 'The alias is a short name used as login name in Centreon.');
$help['email'] = dgettext(
'help',
'Specify the primary email address for the contact here. Additional (email) addresses can be defined '
. 'under additional information of the contact. Depending on the notification command used, the email '
. 'address can be used to send out email notifications.'
);
$help['pager'] = dgettext(
'help',
'Specify a pager number or an address at a pager gateway here. Any format is possible as long as it '
. 'is supported by the notification command.'
);
$help['contactgroups'] = dgettext(
'help',
'Link the contact to the contactgroup(s) the user should belong to. This is an alternative way '
. 'to specifying the members in contactgroup definitions.'
);
$help['contact_enable_notifications'] = dgettext(
'help',
'Enable notification form for this user. If you select "no" , this contact will never be generated into '
. 'configuration files.'
);
$help['host_notification_options'] = dgettext(
'help',
'Define the host states for which notifications can be sent out to this contact. If you specify None as '
. 'an option, the contact will not receive any type of host notifications.'
);
$help['host_notification_period'] = dgettext(
'help',
'Specify the time period during which the contact can be notified about host problems or recoveries. '
. 'You can think of this as an "on call" time for host notifications for the contact.'
);
$help['host_notification_commands'] = dgettext(
'help',
'Define one or more commands used to notify the contact of a host problem or recovery. All notification '
. 'commands are executed when the contact needs to be notified.'
);
$help['service_notification_options'] = dgettext(
'help',
'Define the service states for which notifications can be sent out to this contact. If you specify '
. 'None as an option, the contact will not receive any type of service notifications.'
);
$help['service_notification_period'] = dgettext(
'help',
'Specify the time period during which the contact can be notified about service problems or recoveries. '
. 'You can think of this as an "on call" time for service notifications for the contact.'
);
$help['service_notification_commands'] = dgettext(
'help',
'Define one ore more commands used to notify the contact of a service problem or recovery. '
. 'All notification commands are executed when the contact needs to be notified.'
);
$help['ldap_dn'] = dgettext('help', 'Enter the LDAP Distinguished Name (DN) which identifies this user.');
$help['ldap_group'] = dgettext('help', 'LDAP groups of user, for informative purpose.');
// Centreon specific authentication
$help['centreon_login'] = dgettext('help', 'Specify if the contact is allowed to login into centreon.');
$help['current_password'] = dgettext('help', "For security reasons, to be able to change this user's password, you (the currently logged-in user) must verify your identity by entering your own password.");
$help['password'] = dgettext('help', 'Define the password for the centreon login here.');
$help['password2'] = dgettext('help', 'Enter the password again.');
$help['language'] = dgettext('help', 'Define the default language for the user for the centreon front-end here.');
$help['default_page'] = dgettext(
'help',
'Define the default page for this user (displayed when they log in). '
. 'ACLs must be defined so the user can access the page'
);
$help['admin'] = dgettext(
'help',
'Specify if the user has administrative permissions. Administrators are not restricted by access '
. 'control list (ACL) settings.'
);
$help['autologin_key'] = dgettext(
'help',
'Token used for autologin. Refer to the Centreon documentation to know more about its usage.'
);
$help['auth_type'] = dgettext(
'help',
'Specify the source for user credentials. Choose between Centreon and LDAP, whereas LDAP is only '
. 'available when configured in Administration Options.'
);
$help['location'] = dgettext(
'help',
'Select the timezone, in which the user resides, from the list. The timezones are listed as time difference '
. 'to Greenwich Mean Time (GMT) in hours.'
);
$help['reach_api'] = dgettext('help', 'Allow this user to access to Centreon Rest API with its account.');
$help['reach_api_rt'] = dgettext('help', 'Allow this user to access to Centreon Rest API Realtime with its account.');
// Additional Information
$help['addressx'] = dgettext(
'help',
'Addresses 1-6 are optional and used to define additional "addresses" for the contact. '
. 'These addresses can be anything - cell phone numbers, instant messaging addresses, etc. - the format '
. 'must be supported by your notification plugins.'
);
// unsupported in Centreon
$help['host_notifications_enabled'] = dgettext(
'help',
'This directive is used to determine whether or not the contact will receive notifications about host '
. 'problems and recoveries.'
);
$help['service_notifications_enabled'] = dgettext(
'help',
'This directive is used to determine whether or not the contact will receive notifications about service '
. 'problems and recoveries.'
);
$help['can_submit_commands'] = dgettext(
'help',
'This directive is used to determine whether or not the contact can submit external commands to '
. 'monitoring engine from the CGIs.'
);
$help['retain_status_information'] = dgettext(
'help',
'This directive is used to determine whether or not status-related information about '
. 'the contact is retained across program restarts. This is only useful if you have enabled state '
. 'retention using the retain_state_information directive.'
);
$help['retain_nonstatus_information'] = dgettext(
'help',
'This directive is used to determine whether or not non-status information about the contact is retained across '
. 'program restarts. This is only useful if you have enabled state retention using '
. 'the retain_state_information directive.'
);
$help['aclgroups'] = dgettext('help', 'ACL groups of user.');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact/displayNotification.php | centreon/www/include/configuration/configObject/contact/displayNotification.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
if (! isset($oreon)) {
exit();
}
require_once _CENTREON_PATH_ . 'www/class/centreonNotification.class.php';
// Connect to Database
$pearDBO = new CentreonDB('centstorage');
/**
* Get user list
*/
$contact = ['' => null];
$DBRESULT = $pearDB->query('SELECT contact_id, contact_alias FROM contact ORDER BY contact_alias');
while ($ct = $DBRESULT->fetchRow()) {
$contact[$ct['contact_id']] = $ct['contact_alias'];
}
$DBRESULT->closeCursor();
// Object init
$mediaObj = new CentreonMedia($pearDB);
$host_method = new CentreonHost($pearDB);
$oNotification = new CentreonNotification($pearDB);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// start header menu
$tpl->assign('headerMenu_host', _('Hosts'));
$tpl->assign('headerMenu_service', _('Services'));
$tpl->assign('headerMenu_host_esc', _('Escalated Hosts'));
$tpl->assign('headerMenu_service_esc', _('Escalated Services'));
// Different style between each lines
$style = 'one';
$groups = "''";
$contactId = isset($_POST['contact']) ? (int) htmlentities($_POST['contact'], ENT_QUOTES, 'UTF-8') : 0;
$formData = ['contact' => $contactId];
// Create select form
$form = new HTML_QuickFormCustom('select_form', 'GET', '?p=' . $p);
$form->addElement('select', 'contact', _('Contact'), $contact, ['id' => 'contact', 'onChange' => 'submit();']);
$form->setDefaults($formData);
// Host escalations
$elemArrHostEsc = [];
if ($contactId) {
$hostEscResources = $oNotification->getNotifications(2, $contactId);
}
if (isset($hostEscResources)) {
foreach ($hostEscResources as $hostId => $hostName) {
$elemArrHostEsc[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icons/host.png', 'RowMenu_host' => myDecode($hostName)];
$style = $style != 'two' ? 'two' : 'one';
}
}
$tpl->assign('elemArrHostEsc', $elemArrHostEsc);
// Service escalations
$elemArrSvcEsc = [];
if ($contactId) {
$svcEscResources = $oNotification->getNotifications(3, $contactId);
}
if (isset($svcEscResources)) {
foreach ($svcEscResources as $hostId => $hostTab) {
foreach ($hostTab as $serviceId => $tab) {
$elemArrSvcEsc[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icons/host.png', 'RowMenu_host' => myDecode($tab['host_name']), 'RowMenu_service' => myDecode($tab['service_description'])];
$style = $style != 'two' ? 'two' : 'one';
}
}
}
$tpl->assign('elemArrSvcEsc', $elemArrSvcEsc);
// Hosts
$elemArrHost = [];
if ($contactId) {
$hostResources = $oNotification->getNotifications(0, $contactId);
}
if (isset($hostResources)) {
foreach ($hostResources as $hostId => $hostName) {
$elemArrHost[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icons/host.png', 'RowMenu_host' => myDecode($hostName)];
$style = $style != 'two' ? 'two' : 'one';
}
}
$tpl->assign('elemArrHost', $elemArrHost);
// Services
$elemArrSvc = [];
if ($contactId) {
$svcResources = $oNotification->getNotifications(1, $contactId);
}
if (isset($svcResources)) {
foreach ($svcResources as $hostId => $hostTab) {
foreach ($hostTab as $serviceId => $tab) {
$elemArrSvc[] = ['MenuClass' => 'list_' . $style, 'RowMenu_hico' => './img/icons/host.png', 'RowMenu_host' => myDecode($tab['host_name']), 'RowMenu_service' => myDecode($tab['service_description'])];
$style = $style != 'two' ? 'two' : 'one';
}
}
}
$tpl->assign('elemArrSvc', $elemArrSvc);
$labels = ['host_escalation' => _('Host escalations'), 'service_escalation' => _('Service escalations'), 'host_notifications' => _('Host notifications'), 'service_notifications' => _('Service notifications')];
// Apply a template definition
$renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
$form->accept($renderer);
$tpl->assign('form', $renderer->toArray());
$tpl->assign('msgSelect', _('Please select a user in order to view his notifications'));
$tpl->assign('p', $p);
$tpl->assign('contact', $contactId);
$tpl->assign('labels', $labels);
$tpl->display('displayNotification.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact/formContact.php | centreon/www/include/configuration/configObject/contact/formContact.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
require_once __DIR__ . '/../../../../class/centreonContact.class.php';
use Adaptation\Log\LoggerPassword;
use Centreon\Infrastructure\Event\EventDispatcher;
if (! isset($centreon)) {
exit();
}
if (! $centreon->user->admin && $contactId) {
$aclOptions = ['fields' => ['contact_id', 'contact_name'], 'keys' => ['contact_id'], 'get_row' => 'contact_name', 'conditions' => ['contact_id' => $contactId]];
$contacts = $acl->getContactAclConf($aclOptions);
if (! count($contacts)) {
$msg = new CentreonMsg();
$msg->setImage('./img/icons/warning.png');
$msg->setTextStyle('bold');
$msg->setText(_('You are not allowed to access this contact'));
return null;
}
}
$cgs = $acl->getContactGroupAclConf(
['fields' => ['cg_id', 'cg_name'], 'keys' => ['cg_id'], 'get_row' => 'cg_name', 'order' => ['cg_name']]
);
require_once _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.class.php';
$initialValues = [];
// Check if this server is a Remote Server to hide some part of form
$dbResult = $pearDB->query("SELECT i.value FROM informations i WHERE i.key = 'isRemote'");
$result = $dbResult->fetch();
if ($result === false) {
$isRemote = false;
} else {
$isRemote = array_map('myDecode', $result);
$isRemote = $isRemote['value'] === 'yes';
}
$dbResult->closeCursor();
/**
* Get the Security Policy for automatic generation password.
*/
try {
$passwordSecurityPolicy = (new CentreonContact($pearDB))->getPasswordSecurityPolicy();
$encodedPasswordPolicy = json_encode($passwordSecurityPolicy, JSON_THROW_ON_ERROR);
} catch (PDOException|JsonException $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while retrieving password security policy: ' . $e->getMessage(),
exception: $e
);
return false;
}
$cct = [];
if (($o == MODIFY_CONTACT || $o == WATCH_CONTACT) && $contactId) {
/**
* Init Tables informations
*/
$cct['contact_hostNotifCmds'] = [];
$cct['contact_svNotifCmds'] = [];
$cct['contact_cgNotif'] = [];
$dbResult = $pearDB->prepare('SELECT * FROM contact WHERE contact_id = :contactId LIMIT 1');
$dbResult->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$dbResult->execute();
$cct = array_map('myDecode', $dbResult->fetch());
$cct['contact_passwd'] = null;
$dbResult->closeCursor();
/**
* Set Host Notification Options
*/
$tmp = explode(',', $cct['contact_host_notification_options']);
foreach ($tmp as $key => $value) {
$cct['contact_hostNotifOpts'][trim($value)] = 1;
}
/**
* Set Service Notification Options
*/
$tmp = explode(',', $cct['contact_service_notification_options']);
foreach ($tmp as $key => $value) {
$cct['contact_svNotifOpts'][trim($value)] = 1;
}
$DBRESULT->closeCursor();
/**
* Get DLAP auth informations
*/
$DBRESULT = $pearDB->query("SELECT * FROM `options` WHERE `key` = 'ldap_auth_enable'");
while ($ldap_auths = $DBRESULT->fetchRow()) {
$ldap_auth[$ldap_auths['key']] = myDecode($ldap_auths['value']);
}
$DBRESULT->closeCursor();
/**
* Get ACL informations for this user
*/
$DBRESULT = $pearDB->query("SELECT acl_group_id
FROM `acl_group_contacts_relations`
WHERE `contact_contact_id` = '" . intval($contactId) . "'");
for ($i = 0; $data = $DBRESULT->fetchRow(); $i++) {
if (! $centreon->user->admin && ! isset($allowedAclGroups[$data['acl_group_id']])) {
$initialValues['contact_acl_groups'][] = $data['acl_group_id'];
} else {
$cct['contact_acl_groups'][$i] = $data['acl_group_id'];
}
}
$DBRESULT->closeCursor();
}
/**
* Get Langs
*/
$langs = [];
$langs = getLangs();
if ($o == MASSIVE_CHANGE) {
array_unshift($langs, null);
}
/**
* Contact Groups come from DB -> Store in $notifCcts Array
*/
$notifCgs = [];
$cg = new CentreonContactgroup($pearDB);
$notifCgs = $cg->getListContactgroup(false);
if (
$centreon->optGen['ldap_auth_enable'] == 1
&& ! empty($cct['contact_id'])
&& $cct['contact_auth_type'] === 'ldap'
&& ! empty($cct['ar_id'])
&& ! empty($cct['contact_ldap_dn'])
) {
$ldap = new CentreonLDAP($pearDB, null, $cct['ar_id']);
if ($ldap->connect() !== false) {
$cgLdap = $ldap->listGroupsForUser($cct['contact_ldap_dn']);
}
}
/**
* Contacts Templates
*/
$strRestrinction = isset($contactId) ? " AND contact_id != '" . intval($contactId) . "'" : '';
$contactTpl = [null => ' '];
$DBRESULT = $pearDB->query("SELECT contact_id, contact_name
FROM contact
WHERE contact_register = '0' {$strRestrinction}
ORDER BY contact_name");
while ($contacts = $DBRESULT->fetchRow()) {
$contactTpl[$contacts['contact_id']] = $contacts['contact_name'];
}
$DBRESULT->closeCursor();
/**
* Template / Style for Quickform input
*/
$attrsText = ['size' => '30'];
$attrsText2 = ['size' => '60'];
$attrsTextDescr = ['size' => '80'];
$attrsTextMail = ['size' => '90'];
$attrsAdvSelect = ['style' => 'width: 300px; height: 100px;'];
$attrsTextarea = ['rows' => '15', 'cols' => '100'];
$eTemplate = '<table><tr><td><div class="ams">{label_2}</div>{unselected}</td><td align="center">{add}<br /><br />'
. '<br />{remove}</td><td><div class="ams">{label_3}</div>{selected}</td></tr></table>';
$timeRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod&action=list';
$attrTimeperiods = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $timeRoute, 'multiple' => false, 'linkedObject' => 'centreonTimeperiod'];
$attrCommands = ['datasourceOrigin' => 'ajax', 'multiple' => true, 'linkedObject' => 'centreonCommand'];
$contactRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup&action=list&type=local';
$attrContactgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $contactRoute, 'multiple' => true, 'linkedObject' => 'centreonContactgroup'];
$aclRoute = './include/common/webServices/rest/internal.php?object=centreon_administration_aclgroup&action=list';
$attrAclgroups = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $aclRoute, 'multiple' => true, 'linkedObject' => 'centreonAclGroup'];
$form = new HTML_QuickFormCustom('Form', 'post', '?p=' . $p);
// Smarty template initialization
$tpl = SmartyBC::createSmartyTemplate($path);
// Auth type of the user connected
$authTypeConnectedUser = $centreon->user->authType;
$tpl->assign('authTypeConnectedUser', $authTypeConnectedUser);
// Auth type of the contact edited
if ($o == MODIFY_CONTACT || $o == WATCH_CONTACT) {
$authTypeContact = $cct['contact_auth_type'];
} else {
$authTypeContact = CentreonAuth::AUTH_TYPE_LOCAL;
}
$tpl->assign('authTypeContact', $authTypeContact);
if ($o == ADD_CONTACT) {
$form->addElement('header', 'title', _('Add a User'));
$eventDispatcher->notify(
'contact.form',
EventDispatcher::EVENT_DISPLAY,
[
'form' => $form,
'tpl' => $tpl,
'contact_id' => $contactId,
]
);
} elseif ($o == MODIFY_CONTACT) {
$form->addElement('header', 'title', _('Modify a User'));
$eventDispatcher->notify(
'contact.form',
EventDispatcher::EVENT_READ,
[
'form' => $form,
'tpl' => $tpl,
'contact_id' => $contactId,
]
);
} elseif ($o == WATCH_CONTACT) {
$form->addElement('header', 'title', _('View a User'));
$eventDispatcher->notify(
'contact.form',
EventDispatcher::EVENT_READ,
[
'form' => $form,
'tpl' => $tpl,
'contact_id' => $contactId,
]
);
} elseif ($o == MASSIVE_CHANGE) {
$form->addElement('header', 'title', _('Mass Change'));
$eventDispatcher->notify(
'contact.form',
EventDispatcher::EVENT_DISPLAY,
[
'form' => $form,
'tpl' => $tpl,
'contact_id' => $contactId,
]
);
}
/**
* Contact basic information
*/
$form->addElement('header', 'information', _('General Information'));
$form->addElement('header', 'additional', _('Additional Information'));
$form->addElement('header', 'centreon', _('Centreon Authentication'));
$form->addElement('header', 'acl', _('Access lists'));
/**
* No possibility to change name and alias, because there's no interest
*/
/**
* Don't change contact name and alias in massif change
* Don't change contact name, alias or autologin key in massive change
*/
if ($o != MASSIVE_CHANGE) {
/**
* Contact name attributes
*/
$attrsTextDescr['id'] = 'contact_name';
$attrsTextDescr['data-testid'] = 'contact_name';
$form->addElement('text', 'contact_name', _('Full Name'), $attrsTextDescr);
/**
* Contact alias attributes
*/
$attrsText['id'] = 'contact_alias';
$attrsText['data-testid'] = 'contact_alias';
$form->addElement('text', 'contact_alias', _('Alias / Login'), $attrsText);
/**
* Contact email attributes
*/
$attrsTextMail['id'] = 'contact_email';
$attrsTextMail['data-testid'] = 'contact_email';
$form->addElement('text', 'contact_email', _('Email'), $attrsTextMail);
/**
* Contact Pager attributes
*/
$attrsText['id'] = 'contact_pager';
$attrsText['data-testid'] = 'contact_pager';
$form->addElement('text', 'contact_pager', _('Pager'), $attrsText);
}
/**
* Contact template used
*/
$form->addElement(
'select',
'contact_template_id',
_('Contact template used'),
$contactTpl,
[
'id' => 'contact_template_id',
'data-testid' => 'contact_template_id',
]
);
$form->addElement('header', 'furtherAddress', _('Additional Addresses'));
for ($i = 0; $i < 6; $i++) {
$attrsText['id'] = 'contact_address' . ($i + 1);
$attrsText['data-testid'] = 'contact_address' . ($i + 1);
$form->addElement('text', 'contact_address' . ($i + 1), _('Address' . ($i + 1)), $attrsText);
}
/**
* Contact Groups Field
*/
$form->addElement('header', 'groupLinks', _('Group Relations'));
if ($o == MASSIVE_CHANGE) {
$mc_mod_cg = [];
$mc_mod_cg[] = $form->createElement('radio', 'mc_mod_cg', null, _('Incremental'), '0');
$mc_mod_cg[] = $form->createElement('radio', 'mc_mod_cg', null, _('Replacement'), '1');
$form->addGroup($mc_mod_cg, 'mc_mod_cg', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_cg' => '0']);
}
$defaultDatasetRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_contactgroup'
. '&action=defaultValues&target=contact&field=contact_cgNotif&id=' . $contactId;
$attrContactgroup1 = array_merge(
$attrContactgroups,
['defaultDatasetRoute' => $defaultDatasetRoute]
);
$form->addElement(
'select2',
'contact_cgNotif',
_('Linked to Contact Groups'),
[],
$attrContactgroup1
);
/**
* Contact Centreon information
*/
$form->addElement('header', 'oreon', _('Centreon'));
$tab = [];
$tab[] = $form->createElement(
'radio',
'contact_oreon',
null,
_('Yes'),
'1',
[
'id' => 'contact_oreon_yes',
'data-testid' => 'contact_oreon_yes',
]
);
$tab[] = $form->createElement(
'radio',
'contact_oreon',
null,
_('No'),
'0',
[
'id' => 'contact_oreon_no',
'data-testid' => 'contact_oreon_no',
]
);
$form->addGroup($tab, 'contact_oreon', _('Reach Centreon Front-end'), ' ');
$autologinEnabled = ($contactId == $centreon->user->user_id || $centreon->user->admin);
if (
$o !== MASSIVE_CHANGE
&& $authTypeConnectedUser === CentreonAuth::AUTH_TYPE_LOCAL
&& $authTypeContact !== CentreonAuth::AUTH_TYPE_LDAP
) {
// Password Management
if ($o === MODIFY_CONTACT) {
$form->addElement(
'password',
'current_password',
_('Your current password'),
[
'size' => '30',
'autocomplete' => 'off',
'id' => 'current_password',
]
);
}
$form->addElement(
'password',
'contact_passwd',
_('Password'),
[
'size' => '30',
'autocomplete' => 'new-password',
'id' => 'passwd1',
'data-testid' => 'passwd1',
'onkeypress' => 'resetPwdType(this);',
]
);
$form->addElement(
'password',
'contact_passwd2',
_('Confirm Password'),
[
'size' => '30',
'autocomplete' => 'new-password',
'id' => 'passwd2',
'data-testid' => 'passwd2',
'onkeypress' => 'resetPwdType(this);',
]
);
$form->addElement(
'button',
'contact_gen_passwd',
_('Generate'),
[
'onclick' => "generatePassword('passwd', '{$encodedPasswordPolicy}');",
'id' => 'contact_gen_passwd',
'data-testid' => 'contact_gen_passwd',
]
);
// Autologin Management
if (($o === ADD_CONTACT || $o === MODIFY_CONTACT) && $autologinEnabled) {
$form->addElement(
'text',
'contact_autologin_key',
_('Autologin Key'),
[
'size' => '90',
'id' => 'aKey',
'data-testid' => 'aKey',
]
);
$form->addElement(
'button',
'contact_gen_akey',
_('Generate'),
[
'onclick' => "generatePassword('aKey', '{$encodedPasswordPolicy}');",
'id' => 'generateAutologinKeyButton',
'data-testid' => 'generateAutologinKeyButton',
]
);
}
}
// ------------------------ Topoogy ----------------------------
$pages = [null => ''];
$aclUser = $centreon->user->lcaTStr;
if (! empty($aclUser)) {
$acls = array_flip(explode(',', $aclUser));
/**
* Transform [1, 2, 101, 202, 10101, 20201] to :
*
* 1
* 101
* 10101
* 2
* 202
* 20201
*/
$createTopologyTree = function (array $topologies): array {
ksort($topologies, \SORT_ASC);
$parentsLvl = [];
// Classify topologies by parents
foreach (array_keys($topologies) as $page) {
if (strlen($page) === 1) {
// MENU level 1
if (! array_key_exists($page, $parentsLvl)) {
$parentsLvl[$page] = [];
}
} elseif (strlen($page) === 3) {
// MENU level 2
$parentLvl1 = substr($page, 0, 1);
if (! array_key_exists($parentLvl1, $parentsLvl)) {
$parentsLvl[$parentLvl1] = [];
}
if (! array_key_exists($page, $parentsLvl[$parentLvl1])) {
$parentsLvl[$parentLvl1][$page] = [];
}
} elseif (strlen($page) === 5) {
// MENU level 3
$parentLvl1 = substr($page, 0, 1);
$parentLvl2 = substr($page, 0, 3);
if (! array_key_exists($parentLvl1, $parentsLvl)) {
$parentsLvl[$parentLvl1] = [];
}
if (! array_key_exists($parentLvl2, $parentsLvl[$parentLvl1])) {
$parentsLvl[$parentLvl1][$parentLvl2] = [];
}
if (! in_array($page, $parentsLvl[$parentLvl1][$parentLvl2])) {
$parentsLvl[$parentLvl1][$parentLvl2][] = $page;
}
}
}
return $parentsLvl;
};
/**
* Check if at least one child can be shown
*/
$oneChildCanBeShown = function () use (&$childrenLvl3, &$translatedPages): bool {
foreach ($childrenLvl3 as $topologyPage) {
if ($translatedPages[$topologyPage]['show']) {
return true;
}
}
return false;
};
$topologies = $createTopologyTree($acls);
/**
* Retrieve the name of all topologies available for this user
*/
$aclTopologies = $pearDB->query(
'SELECT topology_page, topology_name, topology_show '
. 'FROM topology '
. "WHERE topology_page IN ({$aclUser})"
);
$translatedPages = [];
while ($topology = $aclTopologies->fetch(PDO::FETCH_ASSOC)) {
$translatedPages[$topology['topology_page']] = [
'i18n' => _($topology['topology_name']),
'show' => ((int) $topology['topology_show'] === 1),
];
}
/**
* Create flat tree for menu with the topologies names
* [item1Id] = menu1 > submenu1 > item1
* [item2Id] = menu2 > submenu2 > item2
*/
foreach ($topologies as $parentLvl1 => $childrenLvl2) {
$parentNameLvl1 = $translatedPages[$parentLvl1]['i18n'];
foreach ($childrenLvl2 as $parentLvl2 => $childrenLvl3) {
$parentNameLvl2 = $translatedPages[$parentLvl2]['i18n'];
$isThirdLevelMenu = false;
$parentLvl3 = null;
if ($oneChildCanBeShown()) {
/**
* There is at least one child that can be shown then we can
* process the third level
*/
foreach ($childrenLvl3 as $parentLvl3) {
if ($translatedPages[$parentLvl3]['show']) {
$parentNameLvl3 = $translatedPages[$parentLvl3]['i18n'];
if ($parentNameLvl2 === $parentNameLvl3) {
/**
* The name between lvl2 and lvl3 are equals.
* We keep only lvl1 and lvl3
*/
$pages[$parentLvl3] = $parentNameLvl1 . ' > '
. $parentNameLvl3;
} else {
$pages[$parentLvl3] = $parentNameLvl1 . ' > '
. $parentNameLvl2 . ' > '
. $parentNameLvl3;
}
}
}
$isThirdLevelMenu = true;
}
// select parent from level 2 if level 3 is missing
$pageId = $parentLvl3 ?? $parentLvl2;
if (! $isThirdLevelMenu && $translatedPages[$pageId]['show']) {
/**
* We show only first and second level
*/
$pages[$pageId]
= $parentNameLvl1 . ' > ' . $parentNameLvl2;
}
}
}
}
$form->addElement(
'select',
'contact_lang',
_('Default Language'),
$langs,
[
'id' => 'contact_lang',
'data-testid' => 'contact_lang',
]
);
$form->addElement('select', 'default_page', _('Default page'), $pages);
$form->addElement(
'select',
'contact_type_msg',
_('Mail Type'),
[null => null, 'txt' => 'txt', 'html' => 'html', 'pdf' => 'pdf']
);
if ($centreon->user->admin) {
$tab = [];
$tab[] = $form->createElement(
'radio',
'contact_admin',
null,
_('Yes'),
'1',
['id' => 'contact_admin_yes', 'data-testid' => 'contact_admin_yes']
);
$tab[] = $form->createElement(
'radio',
'contact_admin',
null,
_('No'),
'0',
['id' => 'contact_admin_no', 'data-testid' => 'contact_admin_no']
);
$form->addGroup($tab, 'contact_admin', _('Admin'), ' ');
$tab = [];
$tab[] = $form->createElement(
'radio',
'reach_api',
null,
_('Yes'),
'1',
['id' => 'reach_api_yes', 'data-testid' => 'reach_api_yes']
);
$tab[] = $form->createElement(
'radio',
'reach_api',
null,
_('No'),
'0',
['id' => 'reach_api_no', 'data-testid' => 'reach_api_no']
);
$form->addGroup($tab, 'reach_api', _('Reach API Configuration'), ' ');
$tab = [];
$tab[] = $form->createElement(
'radio',
'reach_api_rt',
null,
_('Yes'),
'1',
['id' => 'reach_api_rt_yes', 'data-testid' => 'reach_api_rt_yes']
);
$tab[] = $form->createElement(
'radio',
'reach_api_rt',
null,
_('No'),
'0',
['id' => 'reach_api_rt_no', 'data-testid' => 'reach_api_rt_no']
);
$form->addGroup($tab, 'reach_api_rt', _('Reach API Realtime'), ' ');
}
/**
* ACL configurations
*/
if ($o == MASSIVE_CHANGE) {
$mc_mod_cg = [];
$mc_mod_cg[] = $form->createElement('radio', 'mc_mod_acl', null, _('Incremental'), '0');
$mc_mod_cg[] = $form->createElement('radio', 'mc_mod_acl', null, _('Replacement'), '1');
$form->addGroup($mc_mod_cg, 'mc_mod_acl', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_acl' => '0']);
}
$defaultDatasetRoute = './include/common/webServices/rest/internal.php?object=centreon_administration_aclgroup'
. '&action=defaultValues&target=contact&field=contact_acl_groups&id=' . $contactId;
$attrAclgroup1 = array_merge(
$attrAclgroups,
['defaultDatasetRoute' => $defaultDatasetRoute]
);
$form->addElement(
'select2',
'contact_acl_groups',
_('Access list groups'),
[],
$attrAclgroup1,
);
/**
* Include GMT Class
*/
require_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php';
$CentreonGMT = new CentreonGMT();
$availableDatasetRoute = './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_timezone&action=list';
$defaultDatasetRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timezone'
. '&action=defaultValues&target=contact&field=contact_location&id=' . $contactId;
$attrTimezones = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => $availableDatasetRoute, 'defaultDatasetRoute' => $defaultDatasetRoute, 'multiple' => false, 'linkedObject' => 'centreonGMT'];
$form->addElement(
'select2',
'contact_location',
_('Timezone / Location'),
[],
$attrTimezones
);
$contactAuthTypeSelect = $o != MASSIVE_CHANGE ? [] : [null => null];
$contactAuthTypeSelect['local'] = 'Centreon';
if ($centreon->optGen['ldap_auth_enable'] == 1) {
$contactAuthTypeSelect['ldap'] = 'LDAP';
/**
* LDAP Distinguished Name attributes
*/
$attrsText2['id'] = 'contact_ldap_dn';
$attrsText2['data-testid'] = 'contact_ldap_dn';
$dnElement = $form->addElement('text', 'contact_ldap_dn', _('LDAP DN (Distinguished Name)'), $attrsText2);
if (! $centreon->user->admin) {
$dnElement->freeze();
}
}
if ($o != MASSIVE_CHANGE) {
$form->setDefaults([
'contact_oreon' => ['contact_oreon' => '1'],
'contact_admin' => ['contact_admin' => '0'],
'reach_api' => ['reach_api' => '0'],
'reach_api_rt' => ['reach_api_rt' => '0'],
]);
}
$form->addElement(
'select',
'contact_auth_type',
_('Authentication Source'),
$contactAuthTypeSelect,
[
'id' => 'contact_auth_type',
'data-testid' => 'contact_auth_type',
]
);
/**
* Notification informations
*/
$form->addElement('header', 'notification', _('Notification'));
$tab = [];
$tab[] = $form->createElement(
'radio',
'contact_enable_notifications',
null,
_('Yes'),
'1',
['data-testid' => 'contact_enable_notifications_yes']
);
$tab[] = $form->createElement(
'radio',
'contact_enable_notifications',
null,
_('No'),
'0',
['data-testid' => 'contact_enable_notifications_no']
);
$tab[] = $form->createElement(
'radio',
'contact_enable_notifications',
null,
_('Default'),
'2',
[
'id' => 'contact_enable_notifications_default',
'data-testid' => 'contact_enable_notifications_default',
]
);
$form->addGroup($tab, 'contact_enable_notifications', _('Enable Notifications'), ' ');
if ($o != MASSIVE_CHANGE) {
$form->setDefaults(['contact_enable_notifications' => '2']);
}
/** * *****************************
* Host notifications
*/
$form->addElement('header', 'hostNotification', _('Host'));
$hostNotifOpt[] = $form->createElement(
'checkbox',
'd',
' ',
_('Down'),
['id' => 'hDown', 'onClick' => 'uncheckAllH(this);', 'data-testid' => 'hDown']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unreachable'),
['id' => 'hUnreachable', 'onClick' => 'uncheckAllH(this);', 'data-testid' => 'hUnreachable']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'r',
' ',
_('Recovery'),
['id' => 'hRecovery', 'onClick' => 'uncheckAllH(this);', 'data-testid' => 'hRecovery']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'f',
' ',
_('Flapping'),
['id' => 'hFlapping', 'onClick' => 'uncheckAllH(this);', 'data-testid' => 'hFlapping']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
's',
' ',
_('Downtime Scheduled'),
['id' => 'hScheduled', 'onClick' => 'uncheckAllH(this);', 'data-testid' => 'hScheduled']
);
$hostNotifOpt[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'hNone', 'onClick' => 'javascript:uncheckAllH(this);', 'data-testid' => 'hNone']
);
$form->addGroup($hostNotifOpt, 'contact_hostNotifOpts', _('Host Notification Options'), ' ');
$defaultDatasetRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_timeperiod'
. '&action=defaultValues&target=contact&field=timeperiod_tp_id&id=' . $contactId;
$attrTimeperiod1 = array_merge(
$attrTimeperiods,
['defaultDatasetRoute' => $defaultDatasetRoute]
);
$form->addElement(
'select2',
'timeperiod_tp_id',
_('Host Notification Period'),
[],
$attrTimeperiod1
);
unset($hostNotifOpt);
if ($o == MASSIVE_CHANGE) {
$mc_mod_hcmds = [];
$mc_mod_hcmds[] = $form->createElement('radio', 'mc_mod_hcmds', null, _('Incremental'), '0');
$mc_mod_hcmds[] = $form->createElement('radio', 'mc_mod_hcmds', null, _('Replacement'), '1');
$form->addGroup($mc_mod_hcmds, 'mc_mod_hcmds', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_hcmds' => '0']);
}
$defaultDatasetRoute = './include/common/webServices/rest/internal.php?object=centreon_configuration_command'
. '&action=defaultValues&target=contact&field=contact_hostNotifCmds&id=' . $contactId;
$availableDatasetRoute = './include/common/webServices/rest/internal.php'
. '?object=centreon_configuration_command&action=list&t=1';
$attrCommand1 = array_merge(
$attrCommands,
['defaultDatasetRoute' => $defaultDatasetRoute, 'availableDatasetRoute' => $availableDatasetRoute]
);
$form->addElement(
'select2',
'contact_hostNotifCmds',
_('Host Notification Commands'),
[],
$attrCommand1
);
/** * *****************************
* Service notifications
*/
$form->addElement('header', 'serviceNotification', _('Service'));
$svNotifOpt[] = $form->createElement(
'checkbox',
'w',
' ',
_('Warning'),
['id' => 'sWarning', 'onClick' => 'uncheckAllS(this);', 'data-testid' => 'sWarning']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'u',
' ',
_('Unknown'),
['id' => 'sUnknown', 'onClick' => 'uncheckAllS(this);', 'data-testid' => 'sUnknown']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'c',
' ',
_('Critical'),
['id' => 'sCritical', 'onClick' => 'uncheckAllS(this);', 'data-testid' => 'sCritical']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'r',
' ',
_('Recovery'),
['id' => 'sRecovery', 'onClick' => 'uncheckAllS(this);', 'data-testid' => 'sRecovery']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'f',
' ',
_('Flapping'),
['id' => 'sFlapping', 'onClick' => 'uncheckAllS(this);', 'data-testid' => 'sFlapping']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
's',
' ',
_('Downtime Scheduled'),
['id' => 'sScheduled', 'onClick' => 'uncheckAllS(this);', 'data-testid' => 'sScheduled']
);
$svNotifOpt[] = $form->createElement(
'checkbox',
'n',
' ',
_('None'),
['id' => 'sNone', 'onClick' => 'uncheckAllS(this);', 'data-testid' => 'sNone']
);
$form->addGroup($svNotifOpt, 'contact_svNotifOpts', _('Service Notification Options'), ' ');
$defaultAttrTimeperiod2Route = './include/common/webServices/rest/internal.php?'
. 'object=centreon_configuration_timeperiod&action=defaultValues&target=contact&field=timeperiod_tp_id2&id='
. $contactId;
$attrTimeperiod2 = array_merge(
$attrTimeperiods,
['defaultDatasetRoute' => $defaultAttrTimeperiod2Route]
);
$form->addElement(
'select2',
'timeperiod_tp_id2',
_('Service Notification Period'),
[],
$attrTimeperiod2
);
if ($o == MASSIVE_CHANGE) {
$mc_mod_svcmds = [];
$mc_mod_svcmds[] = $form->createElement('radio', 'mc_mod_svcmds', null, _('Incremental'), '0');
$mc_mod_svcmds[] = $form->createElement('radio', 'mc_mod_svcmds', null, _('Replacement'), '1');
$form->addGroup($mc_mod_svcmds, 'mc_mod_svcmds', _('Update mode'), ' ');
$form->setDefaults(['mc_mod_svcmds' => '0']);
}
$defaultattrCommand2Route = './include/common/webServices/rest/internal.php?object=centreon_configuration_command'
. '&action=defaultValues&target=contact&field=contact_svNotifCmds&id=' . $contactId;
$availableCommand2Route = './include/common/webServices/rest/internal.php?'
. 'object=centreon_configuration_command&action=list&t=1';
$attrCommand2 = array_merge(
$attrCommands,
['defaultDatasetRoute' => $defaultattrCommand2Route, 'availableDatasetRoute' => $availableCommand2Route]
);
$form->addElement(
'select2',
'contact_svNotifCmds',
_('Service Notification Commands'),
[],
$attrCommand2
);
/**
* Further informations
*/
$form->addElement('header', 'furtherInfos', _('Additional Information'));
$cctActivation[] = $form->createElement(
'radio',
'contact_activate',
null,
_('Enabled'),
'1',
['id' => 'contact_activate_enable', 'data-testid' => 'contact_activate_enable']
);
$cctActivation[] = $form->createElement(
'radio',
'contact_activate',
null,
_('Disabled'),
'0',
['id' => 'contact_activate_disable', 'data-testid' => 'contact_activate_disable']
);
$form->addGroup($cctActivation, 'contact_activate', _('Status'), ' ');
$form->setDefaults(['contact_activate' => '1']);
if ($o == MODIFY_CONTACT && $centreon->user->get_id() == $cct['contact_id']) {
$form->freeze('contact_activate');
}
$form->addElement('hidden', 'contact_register');
$form->setDefaults(['contact_register' => '1']);
/**
* Comments attributes
*/
$attrsTextarea['id'] = 'contact_comment';
$attrsTextarea['data-testid'] = 'contact_comment';
$form->addElement('textarea', 'contact_comment', _('Comments'), $attrsTextarea);
$form->addElement('hidden', 'contact_id');
$redirect = $form->addElement('hidden', 'o');
$redirect->setValue($o);
$init = $form->addElement('hidden', 'initialValues');
$init->setValue(serialize($initialValues));
if (is_array($select)) {
$select_str = null;
foreach ($select as $key => $value) {
$select_str .= $key . ',';
}
$select_pear = $form->addElement('hidden', 'select');
$select_pear->setValue($select_str);
}
/**
* Form Rules
*/
function myReplace()
{
global $form;
$ret = $form->getSubmitValues();
return str_replace(' ', '_', $ret['contact_name']);
}
$form->applyFilter('__ALL__', 'myTrim');
$form->applyFilter('contact_name', 'myReplace');
$from_list_menu = false;
if ($o != MASSIVE_CHANGE) {
$ret = $form->getSubmitValues();
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/include/configuration/configObject/contact/DB-Func.php | centreon/www/include/configuration/configObject/contact/DB-Func.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Adaptation\Log\LoggerPassword;
use App\Kernel;
use Centreon\Domain\Log\Logger;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
if (! isset($centreon)) {
exit();
}
require_once __DIR__ . '/../../../../../bootstrap.php';
require_once __DIR__ . '/../../../../class/centreonAuth.class.php';
require_once __DIR__ . '/../../../../class/centreonContact.class.php';
/**
* @param null $name
* @return bool
*/
function testContactExistence($name = null)
{
global $pearDB, $form, $centreon;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('contact_id');
}
$contactName = $centreon->checkIllegalChar($name);
$query = <<<'SQL'
SELECT contact_name, contact_id FROM contact WHERE contact_name = :contact_name
SQL;
$contact = $pearDB->fetchAssociative(
$query,
QueryParameters::create([
QueryParameter::string('contact_name', $contactName),
])
);
if ($contact && $contact['contact_id'] === (int) $id) {
return true;
}
return ! ($contact && $contact['contact_id'] !== (int) $id);
}
/**
* @param null $alias
* @return bool
*/
function testAliasExistence($alias = null)
{
global $pearDB, $form;
$id = null;
if (isset($form)) {
$id = $form->getSubmitValue('contact_id');
}
$query = "SELECT contact_alias, contact_id FROM contact WHERE contact_alias = '"
. htmlentities($alias, ENT_QUOTES, 'UTF-8') . "'";
$dbResult = $pearDB->query($query);
$contact = $dbResult->fetch();
if ($dbResult->rowCount() >= 1 && $contact['contact_id'] == $id) {
return true;
}
return ! ($dbResult->rowCount() >= 1 && $contact['contact_id'] != $id);
}
/**
* @param null $ct_id
* @return bool
*/
function keepOneContactAtLeast($ct_id = null)
{
global $pearDB, $form, $centreon;
if (isset($ct_id)) {
$contact_id = $ct_id;
} elseif (isset($_GET['contact_id'])) {
$contact_id = htmlentities($_GET['contact_id'], ENT_QUOTES, 'UTF-8');
} else {
$contact_id = $form->getSubmitValue('contact_id');
}
if (isset($form)) {
$cct_oreon = $form->getSubmitValue('contact_oreon');
$cct_activate = $form->getSubmitValue('contact_activate');
} else {
$cct_oreon = 0;
$cct_activate = 0;
}
if ($contact_id == $centreon->user->get_id()) {
return false;
}
// Get activated contacts
$dbResult = $pearDB->query("SELECT COUNT(*) AS nbr_valid
FROM contact
WHERE contact_activate = '1'
AND contact_oreon = '1'
AND contact_id <> '" . $pearDB->escape($contact_id) . "'");
$contacts = $dbResult->fetch();
if ($contacts['nbr_valid'] == 0) {
if ($cct_oreon == 0 || $cct_activate == 0) {
return false;
}
}
return true;
}
/**
* Enable contacts
* @param $contact_id
* @param $contact_arr
*/
function enableContactInDB($contact_id = null, $contact_arr = [])
{
global $pearDB, $centreon;
if (! $contact_id && ! count($contact_arr)) {
return;
}
if ($contact_id) {
$contact_arr = [$contact_id => '1'];
}
foreach ($contact_arr as $key => $value) {
$pearDB->query("UPDATE contact SET contact_activate = '1' WHERE contact_id = '" . (int) $key . "'");
$query = "SELECT contact_name FROM `contact` WHERE `contact_id` = '" . (int) $key . "' LIMIT 1";
$dbResult2 = $pearDB->query($query);
$row = $dbResult2->fetch();
$centreon->CentreonLogAction->insertLog('contact', $key, $row['contact_name'], 'enable');
}
}
/**
* Disable Contacts
* @param $contact_id
* @param $contact_arr
*/
function disableContactInDB($contact_id = null, $contact_arr = [])
{
global $pearDB, $centreon;
if (! $contact_id && ! count($contact_arr)) {
return;
}
if ($contact_id) {
$contact_arr = [$contact_id => '1'];
}
foreach ($contact_arr as $key => $value) {
if (keepOneContactAtLeast($key)) {
$pearDB->query("UPDATE contact SET contact_activate = '0' WHERE contact_id = '" . (int) $key . "'");
$query = "SELECT contact_name FROM `contact` WHERE `contact_id` = '" . (int) $key . "' LIMIT 1";
$dbResult2 = $pearDB->query($query);
$row = $dbResult2->fetch();
$centreon->CentreonLogAction->insertLog('contact', $key, $row['contact_name'], 'disable');
}
}
}
/**
* Unblock contacts in the database
*
* @param int|array<int, string>|null $contact Contact ID, array of contact IDs or null to unblock all contacts
*/
function unblockContactInDB(int|array|null $contact = null): void
{
global $pearDB, $centreon;
if ($contact === null || $contact === []) {
return;
}
if (is_int($contact)) {
$contact = [$contact => '1'];
}
$bindContactIds = [];
foreach (array_keys($contact) as $contactId) {
$bindContactIds[':contact_' . $contactId] = $contactId;
}
// implode ids for IN() clause
$idPlaceholders = implode(', ', array_keys($bindContactIds));
// retrieve the users and add log
$updateQuery = "UPDATE contact SET blocking_time = null WHERE contact_id IN ({$idPlaceholders})";
$updateStatement = $pearDB->prepare($updateQuery);
foreach ($bindContactIds as $token => $value) {
$updateStatement->bindValue($token, $value, PDO::PARAM_INT);
}
$updateStatement->execute();
// retrieve the users and add log
$selectQuery = "SELECT contact_id, contact_name FROM contact WHERE contact_id IN ({$idPlaceholders})";
$selectStatement = $pearDB->prepare($selectQuery);
foreach ($bindContactIds as $token => $value) {
$selectStatement->bindValue($token, $value, PDO::PARAM_INT);
}
$selectStatement->execute();
while ($row = $selectStatement->fetch()) {
$centreon->CentreonLogAction->insertLog('contact', $row['contact_id'], $row['contact_name'], 'unblock');
}
}
/**
* Delete Contacts
* @param array $contacts
*/
function deleteContactInDB($contacts = [])
{
global $pearDB, $centreon;
// getting the contact name for the logs
$contactNameStmt = $pearDB->prepare(
'SELECT contact_name FROM `contact` WHERE `contact_id` = :contactId LIMIT 1'
);
$contactTokenStmt = $pearDB->prepare(
'SELECT token FROM `security_authentication_tokens` WHERE `user_id` = :contactId'
);
$deleteTokenStmt = $pearDB->prepare(
'DELETE FROM `security_token` WHERE `token` = :token'
);
$deleteContactStmt = $pearDB->prepare(
'DELETE FROM contact WHERE contact_id = :contactId'
);
$pearDB->beginTransaction();
try {
foreach ($contacts as $key => $value) {
$contactNameStmt->bindValue(':contactId', (int) $key, PDO::PARAM_INT);
$contactNameStmt->execute();
$row = $contactNameStmt->fetch();
$contactTokenStmt->bindValue(':contactId', (int) $key, PDO::PARAM_INT);
$contactTokenStmt->execute();
while ($rowContact = $contactTokenStmt->fetch()) {
$deleteTokenStmt->bindValue(':token', $rowContact['token'], PDO::PARAM_STR);
$deleteTokenStmt->execute();
}
$deleteContactStmt->bindValue(':contactId', (int) $key, PDO::PARAM_INT);
$deleteContactStmt->execute();
$centreon->CentreonLogAction->insertLog('contact', $key, $row['contact_name'], 'd');
}
$pearDB->commit();
} catch (PDOException $e) {
$pearDB->rollBack();
}
}
/**
* Synchronize LDAP with contacts' data
* Used for massive sync request
* @param array $contacts
*/
function synchronizeContactWithLdap(array $contacts = []): void
{
global $pearDB;
$centreonLog = new CentreonLog();
// checking if at least one LDAP configuration is still enabled
$ldapEnable = $pearDB->query(
"SELECT `value` FROM `options` WHERE `key` = 'ldap_auth_enable'"
);
$rowLdapEnable = $ldapEnable->fetch();
if ($rowLdapEnable['value'] === '1') {
// getting the contact name for the logs
$contactNameStmt = $pearDB->prepare(
'SELECT contact_name, `ar_id`
FROM `contact`
WHERE `contact_id` = :contactId
AND `ar_id` IS NOT NULL'
);
// requiring a manual synchronization at next login of the contact
$stmtRequiredSync = $pearDB->prepare(
'UPDATE contact
SET `contact_ldap_required_sync` = "1"
WHERE contact_id = :contactId'
);
// checking if the contact is currently logged in Centreon
$activeSession = $pearDB->prepare(
'SELECT session_id FROM `session` WHERE user_id = :contactId'
);
// disconnecting the active user from centreon
$logoutContact = $pearDB->prepare(
'DELETE FROM session WHERE session_id = :userSessionId'
);
$successfullySync = [];
$pearDB->beginTransaction();
try {
foreach ($contacts as $key => $value) {
$contactNameStmt->bindValue(':contactId', (int) $key, PDO::PARAM_INT);
$contactNameStmt->execute();
$rowContact = $contactNameStmt->fetch();
if (! $rowContact['ar_id']) {
// skipping chosen contacts not bound to an LDAP
continue;
}
$stmtRequiredSync->bindValue(':contactId', (int) $key, PDO::PARAM_INT);
$stmtRequiredSync->execute();
$activeSession->bindValue(':contactId', (int) $key, PDO::PARAM_INT);
$activeSession->execute();
// disconnecting every session logged in using this contact data
while ($rowSession = $activeSession->fetch()) {
$logoutContact->bindValue(':userSessionId', $rowSession['session_id'], PDO::PARAM_STR);
$logoutContact->execute();
}
$successfullySync[] = $rowContact['contact_name'];
}
$pearDB->commit();
foreach ($successfullySync as $key => $value) {
$centreonLog->insertLog(
3, // ldap.log
'LDAP MULTI SYNC : Successfully planned LDAP synchronization for ' . $value
);
}
} catch (PDOException $e) {
$pearDB->rollBack();
throw new Exception('Bad Request : ' . $e);
}
} else {
// unable to plan the manual LDAP request of the contacts
$centreonLog->insertLog(
3,
'LDAP MANUAL SYNC : No LDAP configuration is enabled'
);
}
}
/**
* Duplicate a list of contact
*
* @param array $contacts list of contact ids to duplicate
* @param array $nbrDup Number of duplication per contact id
* @return array List of the new contact ids
*/
function multipleContactInDB($contacts = [], $nbrDup = [])
{
global $pearDB, $centreon;
$newContactIds = [];
foreach ($contacts as $key => $value) {
$newContactIds[$key] = [];
$statement = $pearDB->prepare(
'SELECT `contact`.*, cp.password, cp.creation_date
FROM contact
LEFT JOIN contact_password cp ON cp.contact_id = contact.contact_id
WHERE `contact`.contact_id = :contactId LIMIT 1'
);
$statement->bindValue(':contactId', (int) $key, PDO::PARAM_INT);
$statement->execute();
$row = $statement->fetch();
if ($row === false) {
return;
}
$row['contact_id'] = null;
for ($i = 1; $i <= $nbrDup[$key]; $i++) {
$val = null;
foreach ($row as $key2 => $value2) {
$value2 = is_int($value2) ? (string) $value2 : $value2;
if (in_array($key2, ['creation_date', 'password']) === false) {
if ($key2 == 'contact_name') {
$contact_name = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
if ($key2 == 'contact_alias') {
$contact_alias = $value2 . '_' . $i;
$value2 = $value2 . '_' . $i;
}
$val ? $val .= ($value2 != null ? (", '" . $value2 . "'") : ', NULL') : $val
.= ($value2 != null ? ("'" . $value2 . "'") : 'NULL');
if ($key2 != 'contact_id') {
$fields[$key2] = $value2;
}
if (isset($contact_name)) {
$fields['contact_name'] = $contact_name;
}
if (isset($contact_alias)) {
$fields['contact_alias'] = $contact_alias;
}
}
}
if (isset($row['contact_name'])) {
$row['contact_name'] = $centreon->checkIllegalChar($row['contact_name']);
}
if (testContactExistence($contact_name) && testAliasExistence($contact_alias)) {
$rq = $val ? 'INSERT INTO contact VALUES (' . $val . ')' : null;
$pearDB->query($rq);
$lastId = $pearDB->lastInsertId();
if (isset($lastId)) {
/**
* Don't insert password for a contact_template.
*/
if ($row['password'] !== null) {
$contact = new CentreonContact($pearDB);
$contact->addPasswordByContactId((int) $lastId, $row['password']);
$statement = $pearDB->prepare(
'UPDATE contact_password
SET creation_date = :creationDate
WHERE contact_id = :contactId'
);
$statement->bindValue(':creationDate', $row['creation_date'], PDO::PARAM_INT);
$statement->bindValue(':contactId', (int) $lastId, PDO::PARAM_INT);
$statement->execute();
}
$newContactIds[$key][] = $lastId;
// ACL update
$query = 'SELECT DISTINCT acl_group_id FROM acl_group_contacts_relations '
. 'WHERE contact_contact_id = ' . (int) $key;
$dbResult = $pearDB->query($query);
$fields['contact_aclRelation'] = '';
$query = 'INSERT INTO acl_group_contacts_relations VALUES (:contact_id, :acl_group_id)';
$statement = $pearDB->prepare($query);
while ($aclRelation = $dbResult->fetch()) {
$statement->bindValue(':contact_id', (int) $lastId, PDO::PARAM_INT);
$statement->bindValue(
':acl_group_id',
(int) $aclRelation['acl_group_id'],
PDO::PARAM_INT
);
$statement->execute();
$fields['contact_aclRelation'] .= $aclRelation['acl_group_id'] . ',';
}
$fields['contact_aclRelation'] = trim($fields['contact_aclRelation'], ',');
// Command update
$query = 'SELECT DISTINCT command_command_id FROM contact_hostcommands_relation '
. "WHERE contact_contact_id = '" . (int) $key . "'";
$dbResult = $pearDB->query($query);
$fields['contact_hostNotifCmds'] = '';
$query = 'INSERT INTO contact_hostcommands_relation VALUES (:contact_id, :command_command_id)';
$statement = $pearDB->prepare($query);
while ($hostCmd = $dbResult->fetch()) {
$statement->bindValue(':contact_id', (int) $lastId, PDO::PARAM_INT);
$statement->bindValue(
':command_command_id',
(int) $hostCmd['command_command_id'],
PDO::PARAM_INT
);
$statement->execute();
$fields['contact_hostNotifCmds'] .= $hostCmd['command_command_id'] . ',';
}
$fields['contact_hostNotifCmds'] = trim($fields['contact_hostNotifCmds'], ',');
// Commands update
$query = 'SELECT DISTINCT command_command_id FROM contact_servicecommands_relation '
. "WHERE contact_contact_id = '" . (int) $key . "'";
$dbResult = $pearDB->query($query);
$fields['contact_svNotifCmds'] = '';
$query = 'INSERT INTO contact_servicecommands_relation
VALUES (:contact_id, :command_command_id)';
$statement = $pearDB->prepare($query);
while ($serviceCmd = $dbResult->fetch()) {
$statement->bindValue(':contact_id', (int) $lastId, PDO::PARAM_INT);
$statement->bindValue(
':command_command_id',
(int) $serviceCmd['command_command_id'],
PDO::PARAM_INT
);
$statement->execute();
$fields['contact_svNotifCmds'] .= $serviceCmd['command_command_id'] . ',';
}
$fields['contact_svNotifCmds'] = trim($fields['contact_svNotifCmds'], ',');
// Contact groups
$query = 'SELECT DISTINCT contactgroup_cg_id FROM contactgroup_contact_relation '
. "WHERE contact_contact_id = '" . (int) $key . "'";
$dbResult = $pearDB->query($query);
$fields['contact_cgNotif'] = '';
$query = 'INSERT INTO contactgroup_contact_relation VALUES (:contact_id, :contactgroup_cg_id)';
$statement = $pearDB->prepare($query);
while ($cg = $dbResult->fetch()) {
$statement->bindValue(':contact_id', (int) $lastId, PDO::PARAM_INT);
$statement->bindValue(':contactgroup_cg_id', (int) $cg['contactgroup_cg_id'], PDO::PARAM_INT);
$statement->execute();
$fields['contact_cgNotif'] .= $cg['contactgroup_cg_id'] . ',';
}
$fields['contact_cgNotif'] = trim($fields['contact_cgNotif'], ',');
$centreon->CentreonLogAction->insertLog(
'contact',
$lastId,
$contact_name,
'a',
$fields
);
}
}
}
}
return $newContactIds;
}
/**
* @throws RepositoryException
*/
function updateContactInDB(mixed $contact_id, bool $from_MC = false, bool $isRemote = false): void
{
global $form;
$contact_id = (int) $contact_id;
if (! $contact_id > 0) {
throw new RepositoryException(
message: 'Invalid contact ID provided to update contact from contact page',
context: ['contact_id' => $contact_id]
);
}
$ret = $form->getSubmitValues();
// Global function to use
if ($from_MC) {
updateContact_MC($contact_id);
} else {
updateContact($contact_id);
}
// Function for updating host commands
// 1 - MC with deletion of existing cmds
// 2 - MC with addition of new cmds
// 3 - Normal update
if (isset($ret['mc_mod_hcmds']['mc_mod_hcmds']) && $ret['mc_mod_hcmds']['mc_mod_hcmds']) {
updateContactHostCommands($contact_id);
} elseif (isset($ret['mc_mod_hcmds']['mc_mod_hcmds']) && ! $ret['mc_mod_hcmds']['mc_mod_hcmds']) {
updateContactHostCommands_MC($contact_id);
} else {
updateContactHostCommands($contact_id);
}
// Function for updating service commands
// 1 - MC with deletion of existing cmds
// 2 - MC with addition of new cmds
// 3 - Normal update
if (isset($ret['mc_mod_svcmds']['mc_mod_svcmds']) && $ret['mc_mod_svcmds']['mc_mod_svcmds']) {
updateContactServiceCommands($contact_id);
} elseif (isset($ret['mc_mod_svcmds']['mc_mod_svcmds']) && ! $ret['mc_mod_svcmds']['mc_mod_svcmds']) {
updateContactServiceCommands_MC($contact_id);
} else {
updateContactServiceCommands($contact_id);
}
// Function for updating contact groups
// 1 - MC with deletion of existing cg
// 2 - MC with addition of new cg
// 3 - Normal update
if (! $isRemote) {
if (isset($ret['mc_mod_cg']['mc_mod_cg']) && $ret['mc_mod_cg']['mc_mod_cg']) {
updateContactContactGroup($contact_id);
} elseif (isset($ret['mc_mod_cg']['mc_mod_cg']) && ! $ret['mc_mod_cg']['mc_mod_cg']) {
updateContactContactGroup_MC($contact_id);
} else {
updateContactContactGroup($contact_id);
}
}
/**
* ACL
*/
if (isset($ret['mc_mod_acl']['mc_mod_acl']) && $ret['mc_mod_acl']['mc_mod_acl']) {
updateAccessGroupLinks($contact_id);
} elseif (isset($ret['mc_mod_acl']['mc_mod_acl']) && ! $ret['mc_mod_acl']['mc_mod_acl']) {
updateAccessGroupLinks_MC($contact_id, $ret['mc_mod_acl']['mc_mod_acl']);
} else {
updateAccessGroupLinks($contact_id);
}
}
/**
* @param array $ret
* @return mixed
*/
function insertContactInDB($ret = [])
{
$contact_id = insertContact($ret);
updateContactHostCommands($contact_id, $ret);
updateContactServiceCommands($contact_id, $ret);
updateContactContactGroup($contact_id, $ret);
updateAccessGroupLinks($contact_id);
return $contact_id;
}
/**
* @param array $ret
* @return mixed
*/
function insertContact($ret = [])
{
global $form, $pearDB, $centreon, $dependencyInjector;
if (! count($ret)) {
$ret = $form->getSubmitValues();
}
$ret['contact_name'] = $centreon->checkIllegalChar($ret['contact_name']);
if (isset($ret['contact_oreon']['contact_oreon']) && $ret['contact_oreon']['contact_oreon'] === '1') {
$ret['reach_api_rt']['reach_api_rt'] = '1';
}
// Filter fields to only include whitelisted fields for non-admin users
if (! $centreon->user->admin) {
$ret = filterNonAdminFields($ret);
}
$bindParams = sanitizeFormContactParameters($ret);
$params = [];
foreach (array_keys($bindParams) as $token) {
$params[] = ltrim($token, ':');
}
$rq = 'INSERT INTO `contact` ( contact_id, ';
$rq .= implode(', ', $params) . ')';
$rq .= ' VALUES (NULL, ' . implode(', ', array_keys($bindParams)) . ' )';
$stmt = $pearDB->prepare($rq);
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$stmt->bindValue($token, $value, $paramType);
}
}
$stmt->execute();
$dbResult = $pearDB->query('SELECT MAX(contact_id) FROM contact');
$contactId = $dbResult->fetch();
if (isset($ret['contact_passwd']) && ! empty($ret['contact_passwd'])) {
$ret['contact_passwd'] = password_hash($ret['contact_passwd'], CentreonAuth::PASSWORD_HASH_ALGORITHM);
$ret['contact_passwd2'] = $ret['contact_passwd'];
$contact = new CentreonContact($pearDB);
$contact->addPasswordByContactId($contactId['MAX(contact_id)'], $ret['contact_passwd']);
}
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$centreon->CentreonLogAction->insertLog(
'contact',
$contactId['MAX(contact_id)'],
$ret['contact_name'],
'a',
$fields
);
return $contactId['MAX(contact_id)'];
}
/**
* @throws RepositoryException
*/
function updateContact(int $contactId): void
{
global $form, $pearDB, $centreon;
if (! $contactId > 0) {
throw new RepositoryException(
message: 'Invalid contact ID provided to update contact from contact page for contact id ' . $contactId,
context: ['contact_id' => $contactId]
);
}
$ret = $form->getSubmitValues();
// Filter fields to only include whitelisted fields for non-admin users
if (! $centreon->user->admin) {
$ret = filterNonAdminFields($ret, $centreon->user->user_id == $contactId);
}
// Remove illegal chars in data sent by the user
$ret['contact_name'] = CentreonUtils::escapeSecure($ret['contact_name'], CentreonUtils::ESCAPE_ILLEGAL_CHARS);
$ret['contact_alias'] = CentreonUtils::escapeSecure($ret['contact_alias'], CentreonUtils::ESCAPE_ILLEGAL_CHARS);
try {
$bindParams = sanitizeFormContactParameters($ret);
} catch (InvalidArgumentException $e) {
throw new RepositoryException(
message: 'Error while sanitizing contact parameters for update from contact page for contact id ' . $contactId,
context: ['contact_id' => $contactId],
previous: $e,
);
}
try {
// Build Query with only setted values.
$rq = 'UPDATE contact SET ';
foreach (array_keys($bindParams) as $token) {
$rq .= ltrim($token, ':') . ' = ' . $token . ', ';
}
$rq = rtrim($rq, ', ');
$rq .= ' WHERE contact_id = :contactId';
$stmt = $pearDB->prepare($rq);
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$stmt->bindValue($token, $value, $paramType);
}
}
$stmt->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
throw new RepositoryException(
message: 'Database error while updating contact from contact page for contact id ' . $contactId,
context: ['contact_id' => $contactId],
previous: $e,
);
}
$userIdConnected = (int) $centreon->user->get_id();
if (! $userIdConnected > 0) {
throw new RepositoryException(
message: 'Fetching connected user ID failed during contact update from contact page for contact id ' . $contactId,
context: ['contact_id' => $contactId],
);
}
if (isset($ret['contact_lang']) && $contactId === $userIdConnected) {
$centreon->user->set_lang($ret['contact_lang']);
}
if (isset($ret['contact_passwd']) && $ret['contact_passwd'] !== '') {
$ret['contact_passwd'] = password_hash($ret['contact_passwd'], CentreonAuth::PASSWORD_HASH_ALGORITHM);
$ret['contact_passwd2'] = $ret['contact_passwd'];
try {
$contact = new CentreonContact($pearDB);
$contact->renewPasswordByContactId($contactId, $ret['contact_passwd']);
LoggerPassword::create()->success(
initiatorId: $userIdConnected,
targetId: $contactId,
);
} catch (PDOException $e) {
LoggerPassword::create()->warning(
reason: 'password update failed',
initiatorId: $userIdConnected,
targetId: $contactId,
exception: $e,
);
throw new RepositoryException(
message: 'Unable to update password for contact id ' . $contactId,
previous: $e
);
}
}
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
try {
$centreon->CentreonLogAction->insertLog('contact', $contactId, $ret['contact_name'], 'c', $fields);
} catch (PDOException $e) {
throw new RepositoryException(
message: 'Database error while logging update of contact from contact page for contact id ' . $contactId,
context: ['contact_id' => $contactId],
previous: $e,
);
}
}
/**
* @throws RepositoryException
*/
function updateContact_MC(int $contact_id): void
{
global $form, $pearDB, $centreon;
if (! $contact_id > 0) {
throw new RepositoryException(
message: 'Invalid contact ID provided to update contact by massive change for contact id ' . $contact_id,
context: ['contact_id' => $contact_id]
);
}
$ret = $form->getSubmitValues();
// Remove all parameters that have an empty value in order to keep
// the contact properties that have not been modified
foreach ($ret as $name => $value) {
if (is_string($value) && empty($value)) {
unset($ret[$name]);
}
}
// Filter fields to only include whitelisted fields for non-admin users
if (! $centreon->user->admin) {
$ret = filterNonAdminFields($ret, $centreon->user->user_id == $contact_id);
}
try {
$bindParams = sanitizeFormContactParameters($ret);
} catch (InvalidArgumentException $e) {
throw new RepositoryException(
message: 'Error while sanitizing contact parameters for massive change update for contact id ' . $contact_id,
context: ['contact_id' => $contact_id],
previous: $e,
);
}
try {
$query = 'UPDATE contact SET ';
foreach (array_keys($bindParams) as $token) {
$query .= ltrim($token, ':') . ' = ' . $token . ', ';
}
$query = rtrim($query, ', ');
$query .= ' WHERE contact_id = :contactId';
$stmt = $pearDB->prepare($query);
foreach ($bindParams as $token => $bindValues) {
foreach ($bindValues as $paramType => $value) {
$stmt->bindValue($token, $value, $paramType);
}
}
$stmt->bindValue(':contactId', $contact_id, PDO::PARAM_INT);
$stmt->execute();
// Prepare Log
$query = "SELECT contact_name FROM `contact` WHERE contact_id='" . $contact_id . "' LIMIT 1";
$dbResult2 = $pearDB->query($query);
$row = $dbResult2->fetch();
} catch (PDOException $e) {
throw new RepositoryException(
message: 'Database error while updating contact by massive change for contact id ' . $contact_id,
context: ['contact_id' => $contact_id],
previous: $e,
);
}
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
try {
$centreon->CentreonLogAction->insertLog('contact', $contact_id, $row['contact_name'], 'mc', $fields);
} catch (PDOException $e) {
throw new RepositoryException(
message: 'Database error while logging update of contact by massive change for contact id ' . $contact_id,
context: ['contact_id' => $contact_id],
previous: $e,
);
}
}
/**
* @param int $contactId
* @param array $fields
* @return bool
*/
function updateContactHostCommands(int $contactId, array $fields = []): bool
{
global $form, $pearDB;
$kernel = Kernel::createForWeb();
/** @var Logger $logger */
$logger = $kernel->getContainer()->get(Logger::class);
if ($contactId <= 0) {
$logger->error(
"contactId must be an integer greater than 0, given value for contactId : {$contactId}",
['file' => __FILE__, 'line' => __LINE__, 'function' => __FUNCTION__, 'contactId' => $contactId]
);
return false;
}
try {
$pearDB->delete(
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.