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/widgets/service-monitoring/index.php | centreon/www/widgets/service-monitoring/index.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 '../require.php';
require_once '../widget-error-handling.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit();
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_input(
INPUT_GET,
'widgetId',
FILTER_VALIDATE_INT,
['options' => ['default' => 0]],
);
try {
if ($widgetId <= 0) {
throw new InvalidArgumentException('Widget ID must be a positive integer');
}
$configurationDatabase = $dependencyInjector['configuration_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$autoRefresh = filter_var($preferences['refresh_interval'], FILTER_VALIDATE_INT);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
$variablesThemeCSS = match ($centreon->user->theme) {
'light' => 'Generic-theme',
'dark' => 'Centreon-Dark',
default => throw new Exception('Unknown user theme : ' . $centreon->user->theme),
};
$theme = $variablesThemeCSS === 'Generic-theme'
? $variablesThemeCSS . '/Variables-css'
: $variablesThemeCSS;
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error fetching data for service-monitoring widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/service-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, '/');
$template->assign('widgetId', $widgetId);
$template->assign('preferences', $preferences);
$template->assign('autoRefresh', $autoRefresh);
$bMoreViews = 0;
if ($preferences['more_views']) {
$bMoreViews = $preferences['more_views'];
}
$template->assign('more_views', $bMoreViews);
$template->assign('theme', $variablesThemeCSS);
$template->display('index.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/service-monitoring/src/export.php | centreon/www/widgets/service-monitoring/src/export.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\ValueObject\QueryParameter;
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="services-monitoring.csv"');
require_once '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonACL.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonService.class.php';
require_once $centreon_path . 'www/class/centreonMedia.class.php';
require_once $centreon_path . 'www/class/centreonCriticality.class.php';
session_start();
if (! isset($_SESSION['centreon'], $_GET['widgetId'], $_GET['list'])) {
// As the header is already defined, if one of these parameters is missing, an empty CSV is exported
exit();
}
$configurationDatabase = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $configurationDatabase) == 0) {
exit();
}
// Init Objects
$criticality = new CentreonCriticality($configurationDatabase);
$media = new CentreonMedia($configurationDatabase);
$centreon = $_SESSION['centreon'];
$widgetId = filter_input(
INPUT_GET,
'widgetId',
FILTER_VALIDATE_INT,
['options' => ['default' => 0]],
);
/**
* Sanitize and concatenate selected resources for the query
*/
// Check returned combinations
if (str_contains($_GET['list'], ',')) {
$resources = explode(',', $_GET['list']);
} else {
$resources[] = $_GET['list'];
}
// Check combinations consistency and split them in an [hostId, serviceId] array
$exportList = [];
foreach ($resources as $resource) {
if (str_contains($resource, '\;')) {
continue;
}
$exportList[] = explode(';', $resource);
}
$mainQueryParameters = [];
$hostQuery = '';
$serviceQuery = '';
// Prepare the query concatenation and the bind values
$firstResult = true;
$mainQueryParameters = [];
foreach ($exportList as $key => $Id) {
if (
! isset($exportList[$key][1])
|| (int) $exportList[$key][0] === 0
|| (int) $exportList[$key][1] === 0
) {
// skip missing serviceId in combinations or non consistent data
continue;
}
if ($firstResult === false) {
$hostQuery .= ', ';
$serviceQuery .= ', ';
}
$hostQuery .= ':' . $key . 'hId' . $exportList[$key][0];
$mainQueryParameters[] = QueryParameter::int(
$key . 'hId' . $exportList[$key][0],
(int) $exportList[$key][0]
);
$serviceQuery .= ':' . $key . 'sId' . $exportList[$key][1];
$mainQueryParameters[] = QueryParameter::int(
$key . 'sId' . $exportList[$key][1],
(int) $exportList[$key][1]
);
$firstResult = false;
}
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$aStateType = [
'1' => 'H',
'0' => 'S',
];
$stateLabels = [
0 => 'Ok',
1 => 'Warning',
2 => 'Critical',
3 => 'Unknown',
4 => 'Pending',
];
// Build Query
$query = <<<'SQL'
SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
h.host_id,
h.name AS hostname,
h.alias AS hostalias,
s.latency,
s.execution_time,
h.state AS h_state,
s.service_id,
s.description,
s.state AS s_state,
h.state_type AS state_type,
s.last_hard_state,
s.output,
s.scheduled_downtime_depth AS s_scheduled_downtime_depth,
s.acknowledged AS s_acknowledged,
s.notify AS s_notify,
s.active_checks AS s_active_checks,
s.passive_checks AS s_passive_checks,
h.scheduled_downtime_depth AS h_scheduled_downtime_depth,
h.acknowledged AS h_acknowledged,
h.notify AS h_notify,
h.active_checks AS h_active_checks,
h.passive_checks AS h_passive_checks,
s.last_check,
s.last_state_change,
s.last_hard_state_change,
s.check_attempt,
s.max_check_attempts,
h.action_url AS h_action_url,
h.notes_url AS h_notes_url,
s.action_url AS s_action_url,
s.notes_url AS s_notes_url,
cv2.value AS criticality_id,
cv.value AS criticality_level
FROM hosts h
INNER JOIN services s
ON h.host_id = s.host_id
LEFT JOIN customvariables cv
ON cv.service_id = s.service_id
AND cv.host_id = s.host_id
AND cv.name = 'CRITICALITY_LEVEL'
LEFT JOIN customvariables cv2
ON cv2.service_id = s.service_id
AND cv2.host_id = s.host_id
AND cv2.name = 'CRITICALITY_ID';
SQL;
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acls->getAccessGroups()->getIds();
['parameters' => $accessGroupParameters, 'placeholderList' => $accessGroupList] = createMultipleBindParameters(
$accessGroups,
'access_group',
QueryParameterTypeEnum::INTEGER
);
$query .= <<<SQL
INNER JOIN centreon_acl acl
ON h.host_id = acl.host_id
AND s.service_id = acl.service_id
AND acl.group_id IN ({$accessGroupList})
SQL;
$mainQueryParameters = [...$accessGroupParameters, ...$mainQueryParameters];
}
$query .= <<<'SQL'
WHERE h.name NOT LIKE '_Module_%'
AND s.enabled = 1
AND h.enabled = 1
SQL;
if ($firstResult === false) {
$query .= " AND h.host_id IN ({$hostQuery}) AND s.service_id IN ({$serviceQuery}) ";
}
if (isset($preferences['host_name_search']) && $preferences['host_name_search'] != '') {
$tab = explode(' ', $preferences['host_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('host_name', $search);
$hostNameCondition = 'h.name ' . CentreonUtils::operandToMysqlFormat($op) . ' :host_name ';
$query = CentreonUtils::conditionBuilder($query, $hostNameCondition);
}
}
if (isset($preferences['service_description_search']) && $preferences['service_description_search'] != '') {
$tab = explode(' ', $preferences['service_description_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('service_description', $search);
$serviceDescriptionCondition = 's.description '
. CentreonUtils::operandToMysqlFormat($op) . ' :service_description ';
$query = CentreonUtils::conditionBuilder($query, $serviceDescriptionCondition);
}
}
$stateTab = [];
if (isset($preferences['svc_ok']) && $preferences['svc_ok']) {
$stateTab[] = 0;
}
if (isset($preferences['svc_warning']) && $preferences['svc_warning']) {
$stateTab[] = 1;
}
if (isset($preferences['svc_critical']) && $preferences['svc_critical']) {
$stateTab[] = 2;
}
if (isset($preferences['svc_unknown']) && $preferences['svc_unknown']) {
$stateTab[] = 3;
}
if (isset($preferences['svc_pending']) && $preferences['svc_pending']) {
$stateTab[] = 4;
}
if (isset($preferences['hide_down_host']) && $preferences['hide_down_host']) {
$query = CentreonUtils::conditionBuilder($query, ' h.state != 1 ');
}
if (isset($preferences['hide_unreachable_host']) && $preferences['hide_unreachable_host']) {
$query = CentreonUtils::conditionBuilder($query, ' h.state != 2 ');
}
if ($stateTab !== []) {
$query = CentreonUtils::conditionBuilder($query, ' s.state IN (' . implode(',', $stateTab) . ')');
}
if (isset($preferences['acknowledgement_filter']) && $preferences['acknowledgement_filter']) {
if ($preferences['acknowledgement_filter'] == 'ack') {
$query = CentreonUtils::conditionBuilder($query, ' s.acknowledged = 1');
} elseif ($preferences['acknowledgement_filter'] == 'nack') {
$query = CentreonUtils::conditionBuilder(
$query,
' s.acknowledged = 0 AND h.acknowledged = 0 AND h.scheduled_downtime_depth = 0 '
);
}
}
if (isset($preferences['notification_filter']) && $preferences['notification_filter']) {
if ($preferences['notification_filter'] == 'enabled') {
$query = CentreonUtils::conditionBuilder($query, ' s.notify = 1');
} elseif ($preferences['notification_filter'] == 'disabled') {
$query = CentreonUtils::conditionBuilder($query, ' s.notify = 0');
}
}
if (isset($preferences['downtime_filter']) && $preferences['downtime_filter']) {
if ($preferences['downtime_filter'] == 'downtime') {
$query = CentreonUtils::conditionBuilder($query, ' s.scheduled_downtime_depth > 0 ');
} elseif ($preferences['downtime_filter'] == 'ndowntime') {
$query = CentreonUtils::conditionBuilder($query, ' s.scheduled_downtime_depth = 0 ');
}
}
if (isset($preferences['state_type_filter']) && $preferences['state_type_filter']) {
if ($preferences['state_type_filter'] == 'hardonly') {
$query = CentreonUtils::conditionBuilder($query, ' s.state_type = 1 ');
} elseif ($preferences['state_type_filter'] == 'softonly') {
$query = CentreonUtils::conditionBuilder($query, ' s.state_type = 0 ');
}
}
if (isset($preferences['hostgroup']) && $preferences['hostgroup']) {
$results = explode(',', $preferences['hostgroup']);
$queryHG = '';
foreach ($results as $result) {
if ($queryHG != '') {
$queryHG .= ', ';
}
$queryHG .= ':id_' . $result;
$mainQueryParameters[] = QueryParameter::int('id_' . $result, (int) $result);
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.host_id IN (
SELECT host_host_id
FROM `' . $conf_centreon['db'] . '`.hostgroup_relation
WHERE hostgroup_hg_id IN (' . $queryHG . ')
)'
);
}
if (isset($preferences['servicegroup']) && $preferences['servicegroup']) {
$resultsSG = explode(',', $preferences['servicegroup']);
$querySG = '';
foreach ($resultsSG as $resultSG) {
if ($querySG != '') {
$querySG .= ', ';
}
$querySG .= ':id_' . $resultSG;
$mainQueryParameters[] = QueryParameter::int('id_' . $resultSG, (int) $resultSG);
}
$query = CentreonUtils::conditionBuilder(
$query,
' s.service_id IN (
SELECT DISTINCT service_id
FROM services_servicegroups
WHERE servicegroup_id IN (' . $querySG . ')
)'
);
}
if (! empty($preferences['criticality_filter'])) {
$tab = explode(',', $preferences['criticality_filter']);
$labels = [];
foreach ($tab as $p) {
$labels[] = ':id_' . $p;
$mainQueryParameters[] = QueryParameter::int('id_' . $p, (int) $p);
}
$query = CentreonUtils::conditionBuilder(
$query,
'cv2.value IN (' . implode(',', $labels) . ')'
);
}
if (isset($preferences['output_search']) && $preferences['output_search'] != '') {
$tab = explode(' ', $preferences['output_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('service_output', $search);
$serviceOutputCondition = ' s.output ' . CentreonUtils::operandToMysqlFormat($op) . ' :service_output ';
$query = CentreonUtils::conditionBuilder($query, $serviceOutputCondition);
}
}
$orderby = ' hostname ASC , description ASC';
// Define allowed columns and directions
$allowedOrderColumns = [
'host_id',
'hostname',
'hostalias',
'latency',
'execution_time',
'h_state',
'service_id',
'description',
's_state',
'state_type',
'last_hard_state',
'output',
's_scheduled_downtime_depth',
's_acknowledged',
's_notify',
'perfdata',
's_active_checks',
's_passive_checks',
'h_scheduled_downtime_depth',
'h_acknowledged',
'h_notify',
'h_active_checks',
'h_passive_checks',
'last_check',
'last_state_change',
'last_hard_state_change',
'check_attempt',
'max_check_attempts',
'h_action_url',
'h_notes_url',
's_action_url',
's_notes_url',
'criticality_id',
'criticality_level',
'icon_image',
];
$allowedDirections = ['ASC', 'DESC'];
if (isset($preferences['order_by']) && trim($preferences['order_by']) !== '') {
$aOrder = explode(' ', trim($preferences['order_by']));
$column = $aOrder[0] ?? '';
$direction = isset($aOrder[1]) ? strtoupper($aOrder[1]) : 'ASC';
if (in_array($column, $allowedOrderColumns, true) && in_array($direction, $allowedDirections, true)) {
$orderby = $column . ' ' . $direction;
}
}
$query .= ' ORDER BY ' . $orderby;
$data = [];
$outputLength = $preferences['output_length'] ?? 50;
$commentLength = $preferences['comment_length'] ?? 50;
$hostObj = new CentreonHost($configurationDatabase);
$svcObj = new CentreonService($configurationDatabase);
foreach ($realtimeDatabase->iterateAssociative($query, QueryParameters::create($mainQueryParameters)) as $row) {
foreach ($row as $key => $value) {
if ($key == 'last_check') {
$gmt = new CentreonGMT();
$gmt->getMyGMTFromSession(session_id());
$value = $gmt->getDate('Y-m-d H:i:s', $value);
} elseif ($key == 'last_state_change' || $key == 'last_hard_state_change') {
$value = time() - $value;
$value = CentreonDuration::toString($value);
} elseif ($key == 's_state') {
$value = $stateLabels[$value];
} elseif ($key == 'check_attempt') {
$value = $value . '/' . $row['max_check_attempts'] . ' (' . $aStateType[$row['state_type']] . ')';
} elseif (($key == 'h_action_url' || $key == 'h_notes_url') && $value) {
$value = urlencode($hostObj->replaceMacroInString($row['hostname'], $value));
} elseif (($key == 's_action_url' || $key == 's_notes_url') && $value) {
$value = $hostObj->replaceMacroInString($row['hostname'], $value);
$value = urlencode($svcObj->replaceMacroInString($row['service_id'], $value));
} elseif ($key == 'criticality_id' && $value != '') {
$critData = $criticality->getData($row['criticality_id'], 1);
$value = $critData['sc_name'];
}
$data[$row['host_id'] . '_' . $row['service_id']][$key] = $value;
}
if (isset($preferences['display_last_comment']) && $preferences['display_last_comment']) {
$commentQuery = <<<'SQL'
SELECT
1 AS REALTIME,
data
FROM comments
WHERE host_id = :host_id
AND service_id = :service_id
ORDER BY entry_time DESC LIMIT 1
SQL;
$commentQueryParameters = [
QueryParameter::int('host_id', $row['host_id']),
QueryParameter::int('service_id', $row['service_id']),
];
$data[$row['host_id'] . '_' . $row['service_id']]['comment'] = '-';
foreach ($realtimeDatabase->iterateAssociative($commentQuery, QueryParameters::create($commentQueryParameters)) as $comment) {
$data[$row['host_id'] . '_' . $row['service_id']]['comment'] = substr($comment['data'], 0, $commentLength);
}
}
$data[$row['host_id'] . '_' . $row['service_id']]['encoded_description'] = urlencode(
$data[$row['host_id'] . '_' . $row['service_id']]['description']
);
$data[$row['host_id'] . '_' . $row['service_id']]['encoded_hostname'] = urlencode(
$data[$row['host_id'] . '_' . $row['service_id']]['hostname']
);
}
$autoRefresh = (isset($preferences['refresh_interval']) && (int) $preferences['refresh_interval'] > 0)
? (int) $preferences['refresh_interval']
: 30;
$lines = [];
foreach ($data as $lineData) {
$lines[0] = [];
$line = [];
// Export if set in preferences : severities
if ($preferences['display_severities']) {
$lines[0][] = 'Severity';
$line[] = $lineData['criticality_id'];
}
// Export if set in preferences : name column
if ($preferences['display_host_name'] && $preferences['display_host_alias']) {
$lines[0][] = 'Host Name - Host Alias';
$line[] = $lineData['hostname'] . ' - ' . $lineData['hostalias'];
} elseif ($preferences['display_host_alias']) {
$lines[0][] = 'Host Alias';
$line[] = $lineData['hostalias'];
} else {
$lines[0][] = 'Host Name';
$line[] = $lineData['hostname'];
}
// Export if set in preferences : service description
if ($preferences['display_svc_description']) {
$lines[0][] = 'Description';
$line[] = $lineData['description'];
}
// Export if set in preferences : output
if ($preferences['display_output']) {
$lines[0][] = 'Output';
$line[] = $lineData['output'];
}
// Export if set in preferences : status
if ($preferences['display_status']) {
$lines[0][] = 'Status';
$line[] = $lineData['s_state'];
}
// Export if set in preferences : last check
if ($preferences['display_last_check']) {
$lines[0][] = 'Last Check';
$line[] = $lineData['last_check'];
}
// Export if set in preferences : duration
if ($preferences['display_duration']) {
$lines[0][] = 'Duration';
$line[] = $lineData['last_state_change'];
}
// Export if set in preferences : hard state duration
if ($preferences['display_hard_state_duration']) {
$lines[0][] = 'Hard State Duration';
$line[] = $lineData['last_hard_state_change'];
}
// Export if set in preferences : Tries
if ($preferences['display_tries']) {
$lines[0][] = 'Attempt';
$line[] = $lineData['check_attempt'];
}
// Export if set in preferences : Last comment
if ($preferences['display_last_comment']) {
$lines[0][] = 'Last comment';
$line[] = $lineData['comment'];
}
// Export if set in preferences : Latency
if ($preferences['display_latency']) {
$lines[0][] = 'Latency';
$line[] = $lineData['latency'];
}
// Export if set in preferences : Latency
if ($preferences['display_execution_time']) {
$lines[0][] = 'Execution time';
$line[] = $lineData['execution_time'];
}
$lines[] = $line;
}
// open raw memory as file so no temp files needed, you might run out of memory though
$memoryFile = fopen('php://memory', 'w');
// loop over the input array
foreach ($lines as $line) {
// generate csv lines from the inner arrays
fputcsv($memoryFile, $line, ';');
}
// reset the file pointer to the start of the file
fseek($memoryFile, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="services-monitoring.csv";');
// make php send the generated csv lines to the browser
fpassthru($memoryFile);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/service-monitoring/src/sendCmd.php | centreon/www/widgets/service-monitoring/src/sendCmd.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 '../../require.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonService.class.php';
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
session_start();
try {
if (
! isset($_SESSION['centreon'])
|| ! isset($_POST['cmdType'])
|| ! isset($_POST['selection'])
|| ! isset($_POST['author'])
|| ! isset($_POST['cmd'])
) {
throw new Exception('Missing data');
}
$db = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $db) == 0) {
throw new Exception('Invalid session');
}
$type = filter_input(INPUT_POST, 'cmdType', FILTER_SANITIZE_STRING, ['options' => ['default' => '']]);
$cmd = filter_input(INPUT_POST, 'cmd', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$centreon = $_SESSION['centreon'];
$selections = explode(',', $_POST['selection']);
$oreon = $centreon;
$externalCmd = new CentreonExternalCommand($centreon);
$hostObj = new CentreonHost($db);
$svcObj = new CentreonService($db);
$command = '';
$author = filter_input(INPUT_POST, 'author', FILTER_SANITIZE_STRING, ['options' => ['default' => '']]);
$comment = '';
if (isset($_POST['comment'])) {
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING, ['options' => ['default' => '']]);
}
if ($type === 'ack') {
$persistent = 0;
$sticky = 0;
$notify = 0;
if (isset($_POST['persistent'])) {
$persistent = 1;
}
if (isset($_POST['sticky'])) {
$sticky = 2;
}
if (isset($_POST['notify'])) {
$notify = 1;
}
$command = "ACKNOWLEDGE_HOST_PROBLEM;%s;{$sticky};{$notify};{$persistent};{$author};{$comment}";
$commandSvc = "ACKNOWLEDGE_SVC_PROBLEM;%s;%s;{$sticky};{$notify};{$persistent};{$author};{$comment}";
if (isset($_POST['forcecheck'])) {
$forceCmd = 'SCHEDULE_FORCED_HOST_CHECK;%s;' . time();
$forceCmdSvc = 'SCHEDULE_FORCED_SVC_CHECK;%s;%s;' . time();
}
} elseif ($type === 'downtime') {
$fixed = 0;
if (isset($_POST['fixed'])) {
$fixed = 1;
}
$duration = 0;
if (isset($_POST['dayduration'])) {
$duration += ($_POST['dayduration'] * 86400);
}
if (isset($_POST['hourduration'])) {
$duration += ($_POST['hourduration'] * 3600);
}
if (isset($_POST['minuteduration'])) {
$duration += ($_POST['minuteduration'] * 60);
}
if (! isset($_POST['start_time']) || ! isset($_POST['end_time'])) {
throw new Exception('Missing downtime start/end');
}
[$tmpHstart, $tmpMstart] = array_map('trim', explode(':', $_POST['start_time']));
[$tmpHend, $tmpMend] = array_map('trim', explode(':', $_POST['end_time']));
$dateStart = $_POST['alternativeDateStart'];
$start = $dateStart . ' ' . $tmpHstart . ':' . $tmpMstart;
$start = CentreonUtils::getDateTimeTimestamp($start);
$dateEnd = $_POST['alternativeDateEnd'];
$end = $dateEnd . ' ' . $tmpHend . ':' . $tmpMend;
$end = CentreonUtils::getDateTimeTimestamp($end);
$command = "SCHEDULE_HOST_DOWNTIME;%s;{$start};{$end};{$fixed};0;{$duration};{$author};{$comment}";
$commandSvc = "SCHEDULE_SVC_DOWNTIME;%s;%s;{$start};{$end};{$fixed};0;{$duration};{$author};{$comment}";
} else {
throw new Exception('Unknown command');
}
if ($command !== '') {
$externalCommandMethod = 'set_process_command';
if (method_exists($externalCmd, 'setProcessCommand')) {
$externalCommandMethod = 'setProcessCommand';
}
foreach ($selections as $selection) {
$tmp = explode(';', $selection);
if (count($tmp) != 2) {
throw new Exception('Incorrect id format');
}
$hostId = filter_var($tmp[0], FILTER_VALIDATE_INT) ?: 0;
$svcId = filter_var($tmp[1], FILTER_VALIDATE_INT) ?: 0;
if ($hostId !== 0 && $svcId !== 0) {
$hostname = $hostObj->getHostName($hostId);
$svcDesc = $svcObj->getServiceDesc($svcId);
$pollerId = $hostObj->getHostPollerId($hostId);
if ($cmd === 70 || $cmd === 74) {
$externalCmd->{$externalCommandMethod}(sprintf($commandSvc, $hostname, $svcDesc), $pollerId);
if (isset($forceCmdSvc)) {
$externalCmd->{$externalCommandMethod}(sprintf($forceCmdSvc, $hostname, $svcDesc), $pollerId);
}
} else {
$externalCmd->{$externalCommandMethod}(sprintf($command, $hostname), $pollerId);
}
if (isset($forceCmd)) {
$externalCmd->{$externalCommandMethod}(sprintf($forceCmd, $hostname), $pollerId);
}
if (isset($_POST['processServices'])) {
$services = $svcObj->getServiceId(null, $hostname);
foreach ($services as $svcDesc => $svcId) {
$externalCmd->{$externalCommandMethod}(sprintf($commandSvc, $hostname, $svcDesc), $pollerId);
if (isset($forceCmdSvc)) {
$externalCmd->{$externalCommandMethod}(sprintf($forceCmdSvc, $hostname, $svcDesc), $pollerId);
}
}
}
}
}
$externalCmd->write();
}
} catch (Exception $e) {
echo $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/widgets/service-monitoring/src/action.php | centreon/www/widgets/service-monitoring/src/action.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 '../../require.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonService.class.php';
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
session_start();
try {
if (
! isset($_SESSION['centreon'])
|| ! isset($_REQUEST['cmd'])
|| ! isset($_REQUEST['selection'])
) {
throw new Exception('Missing data');
}
$db = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $db) == 0) {
throw new Exception('Invalid session');
}
$centreon = $_SESSION['centreon'];
$oreon = $centreon;
$cmd = filter_input(INPUT_GET, 'cmd', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$wId = filter_input(INPUT_GET, 'wid', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$selections = explode(',', $_REQUEST['selection']);
$externalCmd = new CentreonExternalCommand($centreon);
$hostObj = new CentreonHost($db);
$svcObj = new CentreonService($db);
$successMsg = _('External Command successfully submitted... Exiting window...');
$result = 0;
$defaultDuration = 7200;
$defaultScale = 's';
if (! empty($centreon->optGen['monitoring_dwt_duration'])) {
$defaultDuration = $centreon->optGen['monitoring_dwt_duration'];
if (! empty($centreon->optGen['monitoring_dwt_duration_scale'])) {
$defaultScale = $centreon->optGen['monitoring_dwt_duration_scale'];
}
}
if ($cmd == 72 || $cmd == 75 || $cmd == 70 || $cmd == 74) {
// Smarty template initialization
$path = $centreon_path . 'www/widgets/service-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign('stickyLabel', _('Sticky'));
$template->assign('persistentLabel', _('Persistent'));
$template->assign('authorLabel', _('Author'));
$template->assign('notifyLabel', _('Notify'));
$template->assign('commentLabel', _('Comment'));
$template->assign('forceCheckLabel', _('Force active checks'));
$template->assign('fixedLabel', _('Fixed'));
$template->assign('durationLabel', _('Duration'));
$template->assign('startLabel', _('Start'));
$template->assign('endLabel', _('End'));
$template->assign('selection', $_REQUEST['selection']);
$template->assign('author', $centreon->user->alias);
$template->assign('cmd', $cmd);
if ($cmd == 72 || $cmd == 70) {
$template->assign('ackHostSvcLabel', _('Acknowledge services of hosts'));
$title = $cmd == 72 ? _('Host Acknowledgement') : _('Service Acknowledgement');
$template->assign('defaultMessage', sprintf(_('Acknowledged by %s'), $centreon->user->alias));
// Default ack options
$persistent_checked = '';
if (! empty($centreon->optGen['monitoring_ack_persistent'])) {
$persistent_checked = 'checked';
}
$template->assign('persistent_checked', $persistent_checked);
$sticky_checked = '';
if (! empty($centreon->optGen['monitoring_ack_sticky'])) {
$sticky_checked = 'checked';
}
$template->assign('sticky_checked', $sticky_checked);
$notify_checked = '';
if (! empty($centreon->optGen['monitoring_ack_notify'])) {
$notify_checked = 'checked';
}
$template->assign('notify_checked', $notify_checked);
$process_service_checked = '';
if (! empty($centreon->optGen['monitoring_ack_svc'])) {
$process_service_checked = 'checked';
}
$template->assign('process_service_checked', $process_service_checked);
$force_active_checked = '';
if (! empty($centreon->optGen['monitoring_ack_active_checks'])) {
$force_active_checked = 'checked';
}
$template->assign('force_active_checked', $force_active_checked);
$template->assign('titleLabel', $title);
$template->assign('submitLabel', _('Acknowledge'));
$template->display('acknowledge.ihtml');
} elseif ($cmd == 75 || $cmd == 74) {
$template->assign('downtimeHostSvcLabel', _('Set downtime on services of hosts'));
$title = $cmd == 75 ? _('Host Downtime') : _('Service Downtime');
// Default downtime options
$process_service_checked = '';
$fixed_checked = '';
if (! empty($centreon->optGen['monitoring_dwt_fixed'])) {
$fixed_checked = 'checked';
}
$template->assign('fixed_checked', $fixed_checked);
if (! empty($centreon->optGen['monitoring_dwt_svc'])) {
$process_service_checked = 'checked';
}
$template->assign('process_service_checked', $process_service_checked);
$template->assign('defaultMessage', sprintf(_('Downtime set by %s'), $centreon->user->alias));
$template->assign('titleLabel', $title);
$template->assign('submitLabel', _('Set Downtime'));
$template->assign('sDurationLabel', _('seconds'));
$template->assign('mDurationLabel', _('minutes'));
$template->assign('hDurationLabel', _('hours'));
$template->assign('dDurationLabel', _('days'));
$template->assign('defaultDuration', $defaultDuration);
$template->assign($defaultScale . 'DefaultScale', 'selected');
$template->display('downtime.ihtml');
}
} else {
$command = '';
$isSvcCommand = false;
switch ($cmd) {
// service: schedule check
case 3:
$command = 'SCHEDULE_SVC_CHECK;%s;' . time();
$isSvcCommand = true;
break;
// service: schedule forced check
case 4:
$command = 'SCHEDULE_FORCED_SVC_CHECK;%s;' . time();
$isSvcCommand = true;
break;
// service: remove ack
case 71:
$command = 'REMOVE_SVC_ACKNOWLEDGEMENT;%s';
$isSvcCommand = true;
break;
// service: enable notif
case 80:
$command = 'ENABLE_SVC_NOTIFICATIONS;%s';
$isSvcCommand = true;
break;
// service: enable notif
case 81:
$command = 'DISABLE_SVC_NOTIFICATIONS;%s';
$isSvcCommand = true;
break;
// service: enable check
case 90:
$command = 'ENABLE_SVC_CHECK;%s';
$isSvcCommand = true;
break;
// service: disable check
case 91:
$command = 'DISABLE_SVC_CHECK;%s';
$isSvcCommand = true;
break;
// host: remove ack
case 73:
$command = 'REMOVE_HOST_ACKNOWLEDGEMENT;%s';
break;
// host: enable notif
case 82:
$command = 'ENABLE_HOST_NOTIFICATIONS;%s';
break;
// host: disable notif
case 83:
$command = 'DISABLE_HOST_NOTIFICATIONS;%s';
break;
// host: enable check
case 92:
$command = 'ENABLE_HOST_CHECK;%s';
break;
// host: disable check
case 93:
$command = 'DISABLE_HOST_CHECK;%s';
break;
default:
throw new Exception('Unknown command');
break;
}
if ($command != '') {
$externalCommandMethod = 'set_process_command';
if (method_exists($externalCmd, 'setProcessCommand')) {
$externalCommandMethod = 'setProcessCommand';
}
$hostArray = [];
foreach ($selections as $selection) {
$tmp = explode(';', $selection);
if (count($tmp) != 2) {
throw new Exception('Incorrect id format');
}
$hostId = filter_var($tmp[0], FILTER_VALIDATE_INT) ?: 0;
$svcId = filter_var($tmp[1], FILTER_VALIDATE_INT) ?: 0;
if ($hostId !== 0 && $svcId !== 0) {
$hostname = $hostObj->getHostName($hostId);
$svcDesc = $svcObj->getServiceDesc($svcId);
$cmdParam = $isSvcCommand === true ? $hostname . ';' . $svcDesc : $hostname;
$externalCmd->{$externalCommandMethod}(
sprintf(
$command,
$cmdParam
),
$hostObj->getHostPollerId($hostId)
);
}
}
$externalCmd->write();
}
$result = 1;
}
} catch (Exception $e) {
echo $e->getMessage() . '<br/>';
}
?>
<div id='result'></div>
<script type='text/javascript'>
var result = <?php echo $result; ?>;
var successMsg = "<?php echo $successMsg; ?>";
var wId = "<?php echo $wId; ?>";
var widgetName = 'widget_' + viewId + '_' + wId;
jQuery(function () {
if (result) {
jQuery("#result").html(successMsg);
setTimeout('closeBox()', 2000);
setTimeout('reloadFrame(widgetName)', 2500);
}
jQuery("#submit").click(function () {
sendCmd();
setTimeout('reloadFrame(widgetName)', 2500);
});
jQuery("#submit").button();
toggleDurationField();
jQuery("[name=fixed]").click(function () {
toggleDurationField();
});
//initializing datepicker and timepicker
jQuery(".timepicker").each(function () {
if (!$(this).val()) {
$(this).val(moment().tz(localStorage.getItem('realTimezone')
? localStorage.getItem('realTimezone')
: moment.tz.guess()).format("HH:mm")
);
}
});
jQuery("#start_time, #end_time").timepicker();
initDatepicker();
turnOnEvents();
updateDateAndTime();
});
function closeBox()
{
jQuery('#widgetPopin').centreonPopin('close');
}
function reloadFrame(widgetName) {
document.getElementsByName(widgetName)[0].contentWindow.location.reload(true);
}
function sendCmd()
{
fieldResult = true;
if (jQuery("#comment") && !jQuery("#comment").val()) {
fieldResult = false;
}
if (fieldResult == false) {
jQuery("#result").html("<font color=red><b>Please fill all mandatory fields.</b></font>");
return false;
}
jQuery.ajax({
type: "POST",
url: "./widgets/service-monitoring/src/sendCmd.php",
data: jQuery("#Form").serialize(),
success: function () {
jQuery("#result").html(successMsg);
setTimeout('closeBox()', 2000);
}
});
}
function toggleDurationField()
{
if (jQuery("[name=fixed]").is(':checked')) {
jQuery("[name=duration]").attr('disabled', true);
jQuery("[name=duration_scale]").attr('disabled', true);
} else {
jQuery("[name=duration]").removeAttr('disabled');
jQuery("[name=duration_scale]").removeAttr('disabled');
}
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/service-monitoring/src/toolbar.php | centreon/www/widgets/service-monitoring/src/toolbar.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 '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_POST['widgetId'])) {
echo 'Session Errors';
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/service-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$centreon = $_SESSION['centreon'];
$widgetId = filter_input(INPUT_POST, 'widgetId', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$db = $dependencyInjector['configuration_db'];
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$admin = $centreon->user->admin;
$canDoAction = false;
if ($admin) {
$canDoAction = true;
}
$actions = "<option value='0'>-- " . _('More actions') . ' -- </option>';
if ($canDoAction || $centreon->user->access->checkAction('service_schedule_check')) {
$actions .= "<option value='3'>" . _('Service: Schedule Immediate Check') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('service_schedule_forced_check')) {
$actions .= "<option value='4'>" . _('Service: Schedule Immediate Forced Check') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('service_acknowledgement')) {
$actions .= "<option value='70'>" . _('Service: Acknowledge') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('service_disacknowledgement')) {
$actions .= "<option value='71'>" . _('Service: Remove Acknowledgement') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('service_schedule_downtime')) {
$actions .= "<option value='74'>" . _('Service: Set Downtime') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('service_notifications')) {
$actions .= "<option value='80'>" . _('Service: Enable Notification') . '</option>';
$actions .= "<option value='81'>" . _('Service: Disable Notification') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('service_checks')) {
$actions .= "<option value='90'>" . _('Service: Enable Check') . '</option>';
$actions .= "<option value='91'>" . _('Service: Disable Check') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_acknowledgement')) {
$actions .= "<option value='72'>" . _('Host: Acknowledge') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_disacknowledgement')) {
$actions .= "<option value='73'>" . _('Host: Remove Acknowledgement') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_schedule_downtime')) {
$actions .= "<option value='75'>" . _('Host: Set Downtime') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_notifications')) {
$actions .= "<option value='82'>" . _('Host: Enable Host Notification') . '</option>';
$actions .= "<option value='83'>" . _('Host: Disable Host Notification') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_checks')) {
$actions .= "<option value='92'>" . _('Host: Enable Host Check') . '</option>';
$actions .= "<option value='93'>" . _('Host: Disable Host Check') . '</option>';
}
$template->assign('widgetId', $widgetId);
$template->assign('actions', $actions);
$template->display('toolbar.ihtml');
?>
<script type="text/javascript" src="../../include/common/javascript/centreon/popin.js"></script>
<script type='text/javascript'>
var tab = new Array();
var actions = "<?php echo $actions; ?>";
var wid = "<?php echo $widgetId; ?>";
jQuery(function () {
jQuery(".toolbar").change(function () {
if (jQuery(this).val() != 0) {
var checkValues = jQuery("input:checked")
.map(function () {
var tmp = jQuery(this).attr('id').split("_");
return tmp[1];
})
.get().join(",");
if (checkValues != '') {
var url = "./widgets/service-monitoring/src/action.php?selection=" + checkValues +
"&cmd=" + jQuery(this).val() + "&wid=" + wid;
parent.jQuery('#widgetPopin').parent().remove();
var popin = parent.jQuery('<div id="widgetPopin">');
popin.centreonPopin({
open: true,
url: url,
onClose: () => {
checkValues.split(',').forEach((value) => {
localStorage.removeItem('w_sm_selection_' + value);
});
}
});
} else {
alert("<?php echo _('Please select one or more items'); ?>");
}
jQuery(this).val(0);
}
});
});
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/service-monitoring/src/index.php | centreon/www/widgets/service-monitoring/src/index.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\ValueObject\QueryParameter;
require_once '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonService.class.php';
require_once $centreon_path . 'www/class/centreonMedia.class.php';
require_once $centreon_path . 'www/class/centreonCriticality.class.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId']) || ! isset($_REQUEST['page'])) {
exit;
}
/**
* @var CentreonDB $configurationDatabase
*/
$configurationDatabase = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $configurationDatabase) == 0) {
exit();
}
// Smarty template initialization
$template = SmartyBC::createSmartyTemplate($centreon_path . 'www/widgets/service-monitoring/src/', './');
// Init Objects
$criticality = new CentreonCriticality($configurationDatabase);
$media = new CentreonMedia($configurationDatabase);
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
$widgetId = filter_input(
INPUT_GET,
'widgetId',
FILTER_VALIDATE_INT,
['options' => ['default' => 0]],
);
$page = filter_input(
INPUT_GET,
'page',
FILTER_VALIDATE_INT,
['options' => ['default' => 0]],
);
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
/**
* @var array{
* host_name_search: string,
* service_description_search: string,
* svc_ok: string,
* hide_down_host: string,
* hide_unreachable_host: string,
* svc_warning: string,
* svc_critical: string,
* svc_unknown: string,
* svc_pending: string,
* criticality_filter: string,
* acknowledgement_filter: string,
* notification_filter: string,
* downtime_filter: string,
* state_type_filter: string,
* poller: string,
* hostgroup: string,
* servicegroup: string,
* entries: string,
* output_search: string,
* display_severities: string,
* display_host_name: string,
* display_host_alias: string,
* display_chart_icon: string,
* display_svc_description: string,
* display_output: string,
* output_length: string,
* display_status: string,
* display_last_check: string,
* display_duration: string,
* display_hard_state_duration: string,
* display_tries: string,
* display_last_comment: string,
* display_latency: string,
* display_execution_time: string,
* comment_length: string,
* order_by: string,
* order_by2: string,
* refresh_interval: string,
* more_views: string
* } $preferences
*/
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$autoRefresh = (isset($preferences['refresh_interval']) && (int) $preferences['refresh_interval'] > 0)
? (int) $preferences['refresh_interval']
: 30;
$stateSColors = [
0 => '#88b917',
1 => '#ff9a13',
2 => '#e00b3d',
3 => '#818285',
4 => '#2ad1d4',
];
$stateHColors = [
0 => '#88b917',
1 => '#e00b3d',
2 => '#82CFD8',
4 => '#2ad1d4',
];
$stateLabels = [
0 => 'Ok',
1 => 'Warning',
2 => 'Critical',
3 => 'Unknown',
4 => 'Pending',
];
$aStateType = [
'1' => 'H',
'0' => 'S',
];
$mainQueryParameters = [];
$querySelect = <<<'SQL'
SELECT DISTINCT
1 AS REALTIME,
h.host_id,
h.name AS hostname,
h.alias AS hostalias,
s.latency,
s.execution_time,
h.state AS h_state,
s.service_id,
s.description,
s.state AS s_state,
s.state_type AS state_type,
s.last_hard_state,
s.output,
s.scheduled_downtime_depth AS s_scheduled_downtime_depth,
s.acknowledged AS s_acknowledged,
s.notify AS s_notify,
s.perfdata,
s.active_checks AS s_active_checks,
s.passive_checks AS s_passive_checks,
h.scheduled_downtime_depth AS h_scheduled_downtime_depth,
h.acknowledged AS h_acknowledged,
h.notify AS h_notify,
h.active_checks AS h_active_checks,
h.passive_checks AS h_passive_checks,
s.last_check,
s.last_state_change,
s.last_hard_state_change,
s.check_attempt,
s.max_check_attempts,
h.action_url AS h_action_url,
h.notes_url AS h_notes_url,
s.action_url AS s_action_url,
s.notes_url AS s_notes_url,
cv2.value AS criticality_id,
cv.value AS criticality_level,
h.icon_image
SQL;
$baseQuery = <<<'SQL'
FROM hosts h
INNER JOIN instances i
ON h.instance_id = i.instance_id
INNER JOIN services s
ON s.host_id = h.host_id
LEFT JOIN customvariables cv
ON s.service_id = cv.service_id
AND s.host_id = cv.host_id
AND cv.name = 'CRITICALITY_LEVEL'
LEFT JOIN customvariables cv2
ON s.service_id = cv2.service_id
AND s.host_id = cv2.host_id
AND cv2.name = 'CRITICALITY_ID'
SQL;
if (! empty($preferences['acknowledgement_filter']) && $preferences['acknowledgement_filter'] == 'ackByMe') {
$baseQuery .= <<<'SQL'
INNER JOIN acknowledgements ack
ON s.service_id = ack.service_id
SQL;
}
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acls->getAccessGroups()->getIds();
['parameters' => $accessGroupParameters, 'placeholderList' => $accessGroupList] = createMultipleBindParameters(
$accessGroups,
'access_group',
QueryParameterTypeEnum::INTEGER
);
$baseQuery .= <<<SQL
INNER JOIN centreon_acl acl
ON h.host_id = acl.host_id
AND s.service_id = acl.service_id
AND acl.group_id IN ({$accessGroupList})
SQL;
$mainQueryParameters = [...$accessGroupParameters, ...$mainQueryParameters];
}
$baseQuery .= <<<'SQL'
WHERE h.name NOT LIKE '_Module_%'
AND s.enabled = 1
AND h.enabled = 1
SQL;
if (isset($preferences['host_name_search']) && $preferences['host_name_search'] != '') {
$tab = explode(' ', $preferences['host_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('host_name_search', $search);
$hostNameCondition = 'h.name ' . CentreonUtils::operandToMysqlFormat($op) . ' :host_name_search ';
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $hostNameCondition);
}
}
if (isset($preferences['service_description_search']) && $preferences['service_description_search'] != '') {
$tab = explode(' ', $preferences['service_description_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('service_description', $search);
$serviceDescriptionCondition = 's.description '
. CentreonUtils::operandToMysqlFormat($op) . ' :service_description ';
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $serviceDescriptionCondition);
}
}
$stateTab = [];
if (isset($preferences['svc_ok']) && $preferences['svc_ok']) {
$stateTab[] = 0;
}
if (isset($preferences['svc_warning']) && $preferences['svc_warning']) {
$stateTab[] = 1;
}
if (isset($preferences['svc_critical']) && $preferences['svc_critical']) {
$stateTab[] = 2;
}
if (isset($preferences['svc_unknown']) && $preferences['svc_unknown']) {
$stateTab[] = 3;
}
if (isset($preferences['svc_pending']) && $preferences['svc_pending']) {
$stateTab[] = 4;
}
if (isset($preferences['hide_down_host']) && $preferences['hide_down_host']) {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' h.state != 1 ');
}
if (isset($preferences['hide_unreachable_host']) && $preferences['hide_unreachable_host']) {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' h.state != 2 ');
}
if ($stateTab !== []) {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.state IN (' . implode(',', $stateTab) . ')');
}
if (isset($preferences['acknowledgement_filter']) && $preferences['acknowledgement_filter']) {
if ($preferences['acknowledgement_filter'] == 'ack') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.acknowledged = 1');
} elseif ($preferences['acknowledgement_filter'] == 'ackByMe') {
$mainQueryParameters[] = QueryParameter::string('ack_author', $centreon->user->alias);
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.acknowledged = 1 AND ack.author = :ack_author');
} elseif ($preferences['acknowledgement_filter'] == 'nack') {
$baseQuery = CentreonUtils::conditionBuilder(
$baseQuery,
' s.acknowledged = 0 AND h.acknowledged = 0 AND h.scheduled_downtime_depth = 0 '
);
}
}
if (isset($preferences['notification_filter']) && $preferences['notification_filter']) {
if ($preferences['notification_filter'] == 'enabled') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.notify = 1');
} elseif ($preferences['notification_filter'] == 'disabled') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.notify = 0');
}
}
if (isset($preferences['downtime_filter']) && $preferences['downtime_filter']) {
if ($preferences['downtime_filter'] == 'downtime') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.scheduled_downtime_depth > 0 ');
} elseif ($preferences['downtime_filter'] == 'ndowntime') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.scheduled_downtime_depth = 0 ');
}
}
if (isset($preferences['state_type_filter']) && $preferences['state_type_filter']) {
if ($preferences['state_type_filter'] == 'hardonly') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.state_type = 1 ');
} elseif ($preferences['state_type_filter'] == 'softonly') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' s.state_type = 0 ');
}
}
if (isset($preferences['poller']) && $preferences['poller']) {
$mainQueryParameters[] = QueryParameter::int('instance_id', $preferences['poller']);
$instanceIdCondition = ' i.instance_id = :instance_id';
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $instanceIdCondition);
}
if (isset($preferences['hostgroup']) && $preferences['hostgroup']) {
$results = explode(',', $preferences['hostgroup']);
$queryHG = '';
foreach ($results as $result) {
if ($queryHG != '') {
$queryHG .= ', ';
}
$queryHG .= ':id_' . $result;
$mainQueryParameters[] = QueryParameter::int('id_' . $result, (int) $result);
}
$baseQuery = CentreonUtils::conditionBuilder(
$baseQuery,
' s.host_id IN (
SELECT host_host_id
FROM `' . $conf_centreon['db'] . '`.hostgroup_relation
WHERE hostgroup_hg_id IN (' . $queryHG . ')
)'
);
}
if (isset($preferences['servicegroup']) && $preferences['servicegroup']) {
$resultsSG = explode(',', $preferences['servicegroup']);
$querySG = '';
foreach ($resultsSG as $resultSG) {
if ($querySG != '') {
$querySG .= ', ';
}
$querySG .= ':id_' . $resultSG;
$mainQueryParameters[] = QueryParameter::int('id_' . $resultSG, (int) $resultSG);
}
$baseQuery = CentreonUtils::conditionBuilder(
$baseQuery,
' s.service_id IN (
SELECT DISTINCT service_id
FROM services_servicegroups
WHERE servicegroup_id IN (' . $querySG . ')
)'
);
}
if (! empty($preferences['criticality_filter'])) {
$tab = explode(',', $preferences['criticality_filter']);
$labels = [];
foreach ($tab as $p) {
$labels[] = ':id_' . $p;
$mainQueryParameters[] = QueryParameter::int('id_' . $p, (int) $p);
}
$baseQuery = CentreonUtils::conditionBuilder(
$baseQuery,
'cv2.value IN (' . implode(',', $labels) . ')'
);
}
if (isset($preferences['output_search']) && $preferences['output_search'] != '') {
$tab = explode(' ', $preferences['output_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('service_output', $search);
$serviceOutputCondition = 's.output ' . CentreonUtils::operandToMysqlFormat($op) . ' :service_output ';
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $serviceOutputCondition);
}
}
$orderByClause = 'hostname ASC ';
// Define allowed columns and directions
$allowedOrderColumns = [
'host_id',
'hostname',
'hostalias',
'latency',
'execution_time',
'h_state',
'service_id',
'description',
's_state',
'state_type',
'last_hard_state',
'output',
's_scheduled_downtime_depth',
's_acknowledged',
's_notify',
'perfdata',
's_active_checks',
's_passive_checks',
'h_scheduled_downtime_depth',
'h_acknowledged',
'h_notify',
'h_active_checks',
'h_passive_checks',
'last_check',
'last_state_change',
'last_hard_state_change',
'check_attempt',
'max_check_attempts',
'h_action_url',
'h_notes_url',
's_action_url',
's_notes_url',
'criticality_id',
'criticality_level',
'icon_image',
];
$allowedDirections = ['ASC', 'DESC'];
$countQuery = 'SELECT COUNT(*) ' . $baseQuery;
$nbRows = (int) $realtimeDatabase->fetchOne($countQuery, QueryParameters::create($mainQueryParameters));
if (isset($preferences['order_by']) && trim($preferences['order_by']) != '') {
$aOrder = explode(' ', trim($preferences['order_by']));
$column = $aOrder[0] ?? '';
$direction = isset($aOrder[1]) ? strtoupper($aOrder[1]) : 'ASC';
if (in_array($column, $allowedOrderColumns, true) && in_array($direction, $allowedDirections, true)) {
if (in_array($column, ['last_state_change', 'last_hard_state_change'], true)) {
$direction = ($direction === 'DESC') ? 'ASC' : 'DESC';
}
$orderByClause = $column . ' ' . $direction;
}
if (isset($preferences['order_by2']) && trim($preferences['order_by2']) !== '') {
$aOrder2 = explode(' ', trim($preferences['order_by2']));
$column2 = $aOrder2[0] ?? '';
$direction2 = isset($aOrder2[1]) ? strtoupper($aOrder2[1]) : 'ASC';
if (in_array($column2, $allowedOrderColumns, true) && in_array($direction2, $allowedDirections, true)) {
$orderByClause .= ', ' . $column2 . ' ' . $direction2;
}
}
}
if (trim($orderByClause)) {
$baseQuery .= 'ORDER BY ' . $orderByClause;
}
$num = filter_var($preferences['entries'], FILTER_VALIDATE_INT) ?: 10;
$baseQuery .= ' LIMIT ' . ($page * $num) . ',' . $num;
$records = $realtimeDatabase->fetchAllAssociative($querySelect . $baseQuery, QueryParameters::create($mainQueryParameters));
$data = [];
$outputLength = $preferences['output_length'] ?: 50;
$commentLength = $preferences['comment_length'] ?: 50;
$hostObj = new CentreonHost($configurationDatabase);
$svcObj = new CentreonService($configurationDatabase);
$gmt = new CentreonGMT();
$gmt->getMyGMTFromSession(session_id());
$allowedActionProtocols = ['http[s]?', '//', 'ssh', 'rdp', 'ftp', 'sftp'];
$allowedProtocolsRegex = '#(^' . implode(
')|(^',
$allowedActionProtocols
) . ')#'; // String starting with one of these protocols
foreach ($records as $record) {
foreach ($record as $key => $value) {
$data[$record['host_id'] . '_' . $record['service_id']][$key] = $value;
}
$dataKey = $record['host_id'] . '_' . $record['service_id'];
// last_check
$valueLastCheck = (int) $record['last_check'];
$valueLastCheckTimestamp = time() - $valueLastCheck;
if (
$valueLastCheckTimestamp > 0
&& $valueLastCheckTimestamp < 3600
) {
$valueLastCheck = CentreonDuration::toString($valueLastCheckTimestamp) . ' ago';
}
$data[$dataKey]['last_check'] = $valueLastCheck;
// last_state_change
$valueLastState = (int) $record['last_state_change'];
if ($valueLastState > 0) {
$valueLastStateTimestamp = time() - $valueLastState;
$valueLastState = CentreonDuration::toString($valueLastStateTimestamp) . ' ago';
} else {
$valueLastState = 'N/A';
}
$data[$dataKey]['last_state_change'] = $valueLastState;
// last_hard_state_change
$valueLastHardState = (int) $record['last_hard_state_change'];
if ($valueLastHardState > 0) {
$valueLastHardStateTimestamp = time() - $valueLastHardState;
$valueLastHardState = CentreonDuration::toString($valueLastHardStateTimestamp) . ' ago';
} else {
$valueLastHardState = 'N/A';
}
$data[$dataKey]['last_hard_state_change'] = $valueLastHardState;
// check_attempt
$valueCheckAttempt = $record['check_attempt'] . '/'
. $record['max_check_attempts'] . ' (' . $aStateType[$record['state_type']] . ')';
$data[$dataKey]['check_attempt'] = $valueCheckAttempt;
// s_state
$data[$dataKey]['color'] = $stateSColors[$record['s_state']];
$data[$dataKey]['s_state'] = $stateLabels[$record['s_state']];
// h_state
$value = $data[$dataKey]['hcolor'] = $stateHColors[$record['h_state']];
$data[$dataKey]['h_state'] = $stateLabels[$record['h_state']];
// output
$data[$dataKey]['output'] = htmlspecialchars(substr($record['output'], 0, $outputLength));
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
$data[$dataKey]['h_details_uri'] = $useDeprecatedPages
? '../../main.php?p=20202&o=hd&host_name=' . $record['hostname']
: $resourceController->buildHostDetailsUri($record['host_id']);
$data[$dataKey]['s_details_uri'] = $useDeprecatedPages
? '../../main.php?p=20201&o=svcd&host_name=' . $record['hostname']
. '&service_description=' . $record['description']
: $resourceController->buildServiceDetailsUri($record['host_id'], $record['service_id']);
$data[$dataKey]['s_graph_uri'] = $useDeprecatedPages
? '../../main.php?p=204&mode=0&svc_id=' . $record['hostname'] . ';' . $record['description']
: $resourceController->buildServiceUri(
$record['host_id'],
$record['service_id'],
$resourceController::TAB_GRAPH_NAME
);
// h_action_url
$valueHActionUrl = $record['h_action_url'];
if ($valueHActionUrl) {
if (preg_match('#^\./(.+)#', $valueHActionUrl, $matches)) {
$valueHActionUrl = '../../' . $matches[1];
} elseif (! preg_match($allowedProtocolsRegex, $valueHActionUrl)) {
$valueHActionUrl = '//' . $valueHActionUrl;
}
$valueHActionUrl = CentreonUtils::escapeSecure(
$hostObj->replaceMacroInString(
$record['hostname'],
$valueHActionUrl
)
);
$data[$dataKey]['h_action_url'] = $valueHActionUrl;
}
// h_notes_url
$valueHNotesUrl = $record['h_notes_url'];
if ($valueHNotesUrl) {
if (preg_match('#^\./(.+)#', $valueHNotesUrl, $matches)) {
$valueHNotesUrl = '../../' . $matches[1];
} elseif (! preg_match($allowedProtocolsRegex, $valueHNotesUrl)) {
$valueHNotesUrl = '//' . $valueHNotesUrl;
}
$valueHNotesUrl = CentreonUtils::escapeSecure(
$hostObj->replaceMacroInString(
$record['hostname'],
$valueHNotesUrl
)
);
$data[$dataKey]['h_notes_url'] = $valueHNotesUrl;
}
// s_action_url
$valueSActionUrl = $record['s_action_url'];
if ($valueSActionUrl) {
if (preg_match('#^\./(.+)#', $valueSActionUrl, $matches)) {
$valueSActionUrl = '../../' . $matches[1];
} elseif (! preg_match($allowedProtocolsRegex, $valueSActionUrl)) {
$valueSActionUrl = '//' . $valueSActionUrl;
}
$valueSActionUrl = CentreonUtils::escapeSecure($hostObj->replaceMacroInString(
$record['hostname'],
$valueSActionUrl
));
$valueSActionUrl = CentreonUtils::escapeSecure($svcObj->replaceMacroInString(
$record['service_id'],
$valueSActionUrl
));
$data[$dataKey]['s_action_url'] = $valueSActionUrl;
}
// s_notes_url
$valueSNotesUrl = $record['s_notes_url'];
if ($valueSNotesUrl) {
if (preg_match('#^\./(.+)#', $valueSNotesUrl, $matches)) {
$valueSNotesUrl = '../../' . $matches[1];
} elseif (! preg_match($allowedProtocolsRegex, $valueSNotesUrl)) {
$valueSNotesUrl = '//' . $valueSNotesUrl;
}
$valueSNotesUrl = CentreonUtils::escapeSecure($hostObj->replaceMacroInString(
$record['hostname'],
$valueSNotesUrl
));
$valueSNotesUrl = CentreonUtils::escapeSecure($svcObj->replaceMacroInString(
$record['service_id'],
$valueSNotesUrl
));
$data[$dataKey]['s_notes_url'] = $valueSNotesUrl;
}
// criticality_id
if ($value != '') {
$critData = $criticality->getData($record['criticality_id'], 1);
// get criticality icon path
$valueCriticalityId = '';
if (isset($critData['icon_id'])) {
$valueCriticalityId = "<img src='../../img/media/" . $media->getFilename($critData['icon_id'])
. "' title='" . $critData['sc_name'] . "' width='16' height='16'>";
}
$data[$dataKey]['criticality_id'] = $valueCriticalityId;
}
// FIXME: A SQL REQUEST IS PLAYED ON EACH LINE TO GET THE COMMENTS !!!!!!
// Meaning that for 100 results on which a comment has been set we get 100 SQL requests...
if (isset($preferences['display_last_comment']) && $preferences['display_last_comment']) {
$commentSql = 'SELECT 1 AS REALTIME, data FROM comments';
$comment = '-';
if ((int) $record['s_acknowledged'] === 1) { // Service is acknowledged
$commentSql = 'SELECT 1 AS REALTIME, comment_data AS data FROM acknowledgements';
} elseif ((int) $record['s_scheduled_downtime_depth'] === 1) { // Service is in downtime
$commentSql = 'SELECT 1 AS REALTIME, comment_data AS data FROM downtimes';
}
$commentSql .= ' WHERE host_id = ' . $record['host_id'] . ' AND service_id = ' . $record['service_id'];
$commentSql .= ' ORDER BY entry_time DESC LIMIT 1';
$commentResult = $realtimeDatabase->query($commentSql);
while ($commentRow = $commentResult->fetch()) {
$comment = substr($commentRow['data'], 0, $commentLength);
unset($commentRow);
}
$data[$dataKey]['comment'] = $comment;
}
$data[$dataKey]['encoded_description'] = urlencode($data[$dataKey]['description']);
$data[$dataKey]['encoded_hostname'] = urlencode($data[$dataKey]['hostname']);
}
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('preferences', $preferences);
$template->assign('page', $page);
$template->assign('dataJS', count($data));
$template->assign('nbRows', $nbRows);
$template->assign('StateHColors', $stateHColors);
$template->assign('StateSColors', $stateSColors);
$template->assign('preferences', $preferences);
$template->assign('data', $data);
$template->assign('broker', 'broker');
$template->display('table.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/engine-status/index.php | centreon/www/widgets/engine-status/index.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;
require_once '../require.php';
require_once '../widget-error-handling.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
require_once $centreon_path . 'bootstrap.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_var($_REQUEST['widgetId'], FILTER_VALIDATE_INT);
try {
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
/**
* @var CentreonDB $configurationDatabase
*/
$configurationDatabase = $dependencyInjector['configuration_db'];
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
/**
* @var array{
* poller: string,
* avg-l: string,
* max-e: string,
* avg-e: string,
* autoRefresh: string
* } $preferences
*/
$preferences = $widgetObj->getWidgetPreferences($widgetId);
if (empty($preferences['poller'])) {
throw new InvalidArgumentException('Please select a poller');
}
$autoRefresh = filter_var(
$preferences['autoRefresh'],
FILTER_VALIDATE_INT,
);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
$variablesThemeCSS = match ($centreon->user->theme) {
'light' => 'Generic-theme',
'dark' => 'Centreon-Dark',
default => throw new Exception('Unknown user theme : ' . $centreon->user->theme),
};
$theme = $variablesThemeCSS === 'Generic-theme'
? $variablesThemeCSS . '/Variables-css'
: $variablesThemeCSS;
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while using engine-status widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/engine-status/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$latencyData = [];
$executionTimeData = [];
$hostStatusesData = [];
$serviceStatusesData = [];
['parameters' => $parameters, 'placeholderList' => $pollerList] = createMultipleBindParameters(
explode(',', $preferences['poller']),
'poller_id',
QueryParameterTypeEnum::INTEGER,
);
$queryParameters = QueryParameters::create($parameters);
$queryLatency = <<<SQL
SELECT
1 AS realtime,
MAX(h.latency) AS h_max,
AVG(h.latency) AS h_moy,
MAX(s.latency) AS s_max,
AVG(s.latency) AS s_moy
FROM hosts h
INNER JOIN services s
ON h.host_id = s.host_id
WHERE
h.instance_id IN ({$pollerList})
AND s.enabled = '1'
AND s.check_type = '0'
SQL;
$queryExecutionTime = <<<SQL
SELECT
1 AS realtime,
MAX(h.execution_time) AS h_max,
AVG(h.execution_time) AS h_moy,
MAX(s.execution_time) AS s_max,
AVG(s.execution_time) AS s_moy
FROM hosts h
INNER JOIN services s
ON h.host_id = s.host_id
WHERE
h.instance_id IN ({$pollerList})
AND s.enabled = '1'
AND s.check_type = '0';
SQL;
try {
foreach ($realtimeDatabase->iterateAssociative($queryLatency, $queryParameters) as $record) {
$record['h_max'] = round($record['h_max'], 3);
$record['h_moy'] = round($record['h_moy'], 3);
$record['s_max'] = round($record['s_max'], 3);
$record['s_moy'] = round($record['s_moy'], 3);
$latencyData[] = $record;
}
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_SQL,
message: 'Error retrieving latency data for engine-status widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme);
exit;
}
try {
foreach ($realtimeDatabase->iterateAssociative($queryExecutionTime, $queryParameters) as $record) {
$record['h_max'] = round($record['h_max'], 3);
$record['h_moy'] = round($record['h_moy'], 3);
$record['s_max'] = round($record['s_max'], 3);
$record['s_moy'] = round($record['s_moy'], 3);
$executionTimeData[] = $record;
}
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_SQL,
message: 'Error retrieving execution time data for engine-status widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme);
exit;
}
$queryHostStatuses = <<<SQL
SELECT
1 AS REALTIME,
SUM(h.state = 1) AS Dow,
SUM(h.state = 2) AS Un,
SUM(h.state = 0) AS Up,
SUM(h.state = 4) AS Pend
FROM hosts h
WHERE h.instance_id IN ({$pollerList})
AND h.enabled = 1
AND h.name NOT LIKE '%Module%'
SQL;
$queryServiceStatuses = <<<SQL
SELECT
1 AS REALTIME,
SUM(s.state = 2) AS Cri,
SUM(s.state = 1) AS Wa,
SUM(s.state = 0) AS Ok,
SUM(s.state = 4) AS Pend,
SUM(s.state = 3) AS Unk
FROM services s
INNER JOIN hosts h
ON h.host_id = s.host_id
WHERE h.instance_id IN ({$pollerList})
AND s.enabled = 1
AND h.name NOT LIKE '%Module%'
SQL;
try {
$hostStatusesData = $realtimeDatabase->fetchAllAssociative($queryHostStatuses, $queryParameters);
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_SQL,
message: 'Error retrieving host statuses data for engine-status widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme);
exit;
}
try {
$serviceStatusesData = $realtimeDatabase->fetchAllAssociative($queryServiceStatuses, $queryParameters);
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_SQL,
message: 'Error retrieving service statuses data for engine-status widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme);
exit;
}
$avg_l = $preferences['avg-l'];
$avg_e = $preferences['avg-e'];
$max_e = $preferences['max-e'];
$template->assign('avg_l', $avg_l);
$template->assign('avg_e', $avg_e);
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('preferences', $preferences);
$template->assign('max_e', $max_e);
$template->assign('dataSth', $hostStatusesData);
$template->assign('dataSts', $serviceStatusesData);
$template->assign('dataEx', $executionTimeData);
$template->assign('dataLat', $latencyData);
$template->assign(
'theme',
$theme
);
$template->display('engine-status.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/live-top10-memory-usage/index.php | centreon/www/widgets/live-top10-memory-usage/index.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\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
require_once '../require.php';
require_once '../widget-error-handling.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
require_once $centreon_path . 'bootstrap.php';
require_once __DIR__ . '/src/function.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
$widgetId = filter_var($_REQUEST['widgetId'], FILTER_VALIDATE_INT);
$grouplistStr = '';
try {
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
/**
* @var CentreonDB $configurationDatabase
*/
$configurationDatabase = $dependencyInjector['configuration_db'];
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$autoRefresh = filter_var($preferences['refresh_interval'], FILTER_VALIDATE_INT);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
$variablesThemeCSS = match ($centreon->user->theme) {
'light' => 'Generic-theme',
'dark' => 'Centreon-Dark',
default => throw new Exception('Unknown user theme : ' . $centreon->user->theme),
};
$theme = $variablesThemeCSS === 'Generic-theme'
? $variablesThemeCSS . '/Variables-css'
: $variablesThemeCSS;
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error fetching data for live-top10-memory-usage widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
$accessGroups = new AccessGroupCollection();
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups->mergeWith($acls->getAccessGroups());
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/live-top10-memory-usage/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$data = [];
try {
if ($centreon->user->admin || ! $accessGroups->isEmpty()) {
$queryParameters = [];
$query = <<<'SQL'
SELECT
1 AS REALTIME,
i.host_name,
i.service_description,
i.service_id,
i.host_id,
m.current_value / m.max AS ratio,
m.max - m.current_value AS remaining_space,
s.state AS status
FROM index_data i
JOIN metrics m
ON i.id = m.index_id
JOIN hosts h
ON i.host_id = h.host_id
LEFT JOIN services s
ON s.service_id = i.service_id
AND s.enabled = 1
SQL;
if ($preferences['host_group']) {
$query .= <<<'SQL'
INNER JOIN hosts_hostgroups hg
ON i.host_id = hg.host_id
AND hg.hostgroup_id = :hostGroupId
SQL;
$queryParameters[] = QueryParameter::int('hostGroupId', (int) $preferences['host_group']);
}
if (! $centreon->user->admin) {
['parameters' => $accessGroupParameters, 'placeholderList' => $accessGroupList] = createMultipleBindParameters(
$accessGroups->getIds(),
'access_group',
QueryParameterTypeEnum::INTEGER
);
$query .= <<<SQL
INNER JOIN centreon_acl acl
ON i.host_id = acl.host_id
AND i.service_id = acl.service_id
AND acl.group_id IN ({$accessGroupList})
SQL;
$queryParameters = [...$accessGroupParameters, ...$queryParameters];
}
$query .= <<<'SQL'
WHERE i.service_description LIKE :serviceDescription
AND m.metric_name LIKE :metricName
AND h.enabled = 1
GROUP BY
i.host_id,
i.service_id,
i.host_name,
i.service_description,
s.state,
m.current_value,
m.max
ORDER BY ratio DESC
LIMIT :numberOfLines;
SQL;
$queryParameters[] = QueryParameter::string('serviceDescription', '%' . $preferences['service_description'] . '%');
$queryParameters[] = QueryParameter::string('metricName', '%' . $preferences['metric_name'] . '%');
$queryParameters[] = QueryParameter::int('numberOfLines', $preferences['nb_lin']);
$numLine = 1;
$in = 0;
foreach ($realtimeDatabase->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$record['numLin'] = $numLine;
while ($record['remaining_space'] >= 1024) {
$record['remaining_space'] = $record['remaining_space'] / 1024;
$in = $in + 1;
}
$record['unit'] = getUnit($in);
$in = 0;
$record['remaining_space'] = round($record['remaining_space']);
$record['ratio'] = ceil($record['ratio'] * 100);
$record['details_uri'] = $useDeprecatedPages
? '../../main.php?p=20201&o=svcd&host_name='
. $record['host_name']
. '&service_description='
. $record['service_description']
: $resourceController->buildServiceDetailsUri(
$record['host_id'],
$record['service_id']
);
$data[] = $record;
$numLine++;
}
}
} catch (ConnectionException $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error fetching memory usage data: ' . $exception->getMessage(),
exception: $exception
);
throw $exception;
}
$template->assign('preferences', $preferences);
$template->assign('theme', $variablesThemeCSS);
$template->assign('widgetId', $widgetId);
$template->assign('preferences', $preferences);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('data', $data);
$template->display('table_top10memory.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/live-top10-memory-usage/src/function.php | centreon/www/widgets/live-top10-memory-usage/src/function.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 to return the unit
* @param $in int
* @return string
*/
function getUnit($in)
{
switch ($in) {
case 0:
$return = 'B';
break;
case 1:
$return = 'KB';
break;
case 2:
$return = 'MB';
break;
case 3:
$return = 'GB';
break;
case 4:
$return = 'TB';
break;
default:
$return = null;
}
return $return;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/ntopng-listing/functions.php | centreon/www/widgets/ntopng-listing/functions.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
*
*/
/**
* Call the NtopNG probe
*
* @param array{login: string, password: string, base_url: string, uri: string} $preferences
* @throws Exception
* @return string
*/
function callProbe(array $preferences): string
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $preferences['uri']);
curl_setopt($curl, CURLOPT_USERPWD, $preferences['login'] . ':' . $preferences['password']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
$result = curl_exec($curl);
curl_close($curl);
if ($result === false) {
throw new Exception(sprintf(
"Can't connect to probe !\n\n(URL API: %s)",
$preferences['base_url']
));
}
if ($result === '') {
throw new Exception(sprintf(
'No data from the probe ! (Check your credentials)\n\n(URI API : %s)',
$preferences['uri']
));
}
return $result;
}
/**
* Create the link to access the details of the measure
*
* @param array{
* mode: string,
* base_url: string,
* interface: int,
* sort: string,
* top: int,
* filter-port: int,
* filter-address: string
* } $preferences
* @return string
*/
function createLink(array $preferences): string
{
return match ($preferences['mode']) {
'top-n-local' => $preferences['base_url']
. '/lua/rest/v2/get/host/active.lua?ifid='
. $preferences['interface']
. '&mode=local&perPage=1000&sortColumn='
. $preferences['sort']
. '&limit='
. $preferences['top'],
'top-n-remote' => $preferences['base_url']
. '/lua/rest/v2/get/host/active.lua?ifid='
. $preferences['interface']
. '&mode=remote&perPage=1000&sortColumn='
. $preferences['sort']
. '&limit='
. $preferences['top'],
'top-n-flows', 'top-n-application' => $preferences['base_url']
. '/lua/rest/v2/get/flow/active.lua?ifid='
. $preferences['interface']
. '&mode=remote&perPage=1000&sortColumn='
. $preferences['sort']
. '&limit='
. $preferences['top']
. (
! empty($preferences['filter-address'])
? '&host=' . $preferences['filter-address']
: ''
)
. (
! empty($preferences['filter-port'])
? '&port=' . $preferences['filter-port']
: ''
),
default => '',
};
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/ntopng-listing/index.php | centreon/www/widgets/ntopng-listing/index.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 '../require.php';
require_once __DIR__ . '/../../class/centreon.class.php';
require_once __DIR__ . '/../../class/centreonSession.class.php';
require_once __DIR__ . '/../../class/centreonWidget.class.php';
require_once __DIR__ . '/../../../bootstrap.php';
const MAX_NUMBER_OF_LINE = 100;
const DEFAULT_NUMBER_OF_LINES = 10;
const DEFAULT_AUTO_REFRESH = 60;
const OSI_LEVEL_4 = 'l4';
const OSI_LEVEL_7 = 'l7';
try {
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_var($_REQUEST['widgetId'], FILTER_VALIDATE_INT);
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
$centreonWidget = new CentreonWidget($centreon, $dependencyInjector['configuration_db']);
$preferences = $centreonWidget->getWidgetPreferences($widgetId);
$preferences['login'] = filter_var($preferences['login'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$preferences['password'] = filter_var($preferences['password'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$preferences['token'] = filter_var($preferences['token'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$preferences['address'] = filter_var($preferences['address'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$preferences['protocol'] = filter_var($preferences['protocol'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$preferences['filter-address'] = filter_var($preferences['filter-address'] ?? '', FILTER_VALIDATE_IP);
$preferences['filter-port'] = filter_var($preferences['filter-port'] ?? '', FILTER_VALIDATE_INT);
$preferences['interface'] = filter_var($preferences['interface'] ?? 0, FILTER_VALIDATE_INT);
$preferences['port'] = filter_var($preferences['port'] ?? 3000, FILTER_VALIDATE_INT);
$preferences['mode'] = filter_var($preferences['mode'] ?? 'top-n-local', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$preferences['sort'] = filter_var($preferences['sort'] ?? 'thpt', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$preferences['top'] = filter_var($preferences['top'] ?? DEFAULT_NUMBER_OF_LINES, FILTER_VALIDATE_INT);
$autoRefresh = filter_var($preferences['refresh_interval'] ?? DEFAULT_AUTO_REFRESH, FILTER_VALIDATE_INT);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = DEFAULT_AUTO_REFRESH;
}
if ($preferences['top'] > MAX_NUMBER_OF_LINE) {
$preferences['top'] = MAX_NUMBER_OF_LINE;
} elseif ($preferences['top'] < 1) {
$preferences['top'] = DEFAULT_NUMBER_OF_LINES;
}
$variablesThemeCSS = match ($centreon->user->theme) {
'light' => 'Generic-theme',
'dark' => 'Centreon-Dark',
default => throw new Exception('Unknown user theme : ' . $centreon->user->theme),
};
} catch (Exception $e) {
echo $e->getMessage() . '<br/>';
exit;
}
$data = ['error' => 0];
if (isset($preferences['login'], $preferences['password'], $preferences['address'])) {
require_once './functions.php';
$preferences['base_url'] = $preferences['protocol'] . '://' . $preferences['address'] . ':' . $preferences['port'];
try {
$preferences['uri'] = createLink($preferences);
$result = callProbe($preferences);
$array = json_decode($result, true);
if (in_array($preferences['mode'], ['top-n-local', 'top-n-remote'], true)) {
$data['hosts'] = [];
$i = 1;
foreach ($array['rsp']['data'] as $traffic) {
$data['hosts'][] = [
'name' => preg_replace('/\[.*\]/', '', $traffic['name']),
'ip' => $traffic['ip'],
'bandwidth' => round($traffic['thpt']['bps'] / 1000000, 2),
'packets_per_second' => round($traffic['thpt']['pps'], 2),
];
if ($i >= $preferences['top']) {
break;
}
$i++;
}
} elseif ($preferences['mode'] === 'top-n-flows') {
$data['flows'] = [];
$i = 1;
foreach ($array['rsp']['data'] as $traffic) {
$protocol = $traffic['protocol'][OSI_LEVEL_4] . ' ' . $traffic['protocol'][OSI_LEVEL_7];
$client = $traffic['client']['name'] . ':' . $traffic['client']['port'];
$server = $traffic['server']['name'] . ':' . $traffic['server']['port'];
$bandwidth = round($traffic['thpt']['bps'] / 1000000, 2);
$pps = round($traffic['thpt']['pps'], 2);
$data['flows'][] = [
'protocol' => $protocol,
'client' => $client,
'server' => $server,
'bandwidth' => $bandwidth,
'packets_per_second' => $pps,
];
if ($i >= $preferences['top']) {
break;
}
$i++;
}
} elseif ($preferences['mode'] === 'top-n-application') {
$applications = [];
$applicationList = [];
$totalBandwidth = 0;
foreach ($array['rsp']['data'] as $traffic) {
$totalBandwidth += $traffic['thpt']['bps'];
$application = $traffic['protocol'][OSI_LEVEL_4] . '-' . $traffic['protocol'][OSI_LEVEL_7];
if (in_array($application, $applicationList)) {
$applications[$application]['bandwidth'] += $traffic['thpt']['bps'];
} else {
$applicationList[] = $application;
$applications[$application] = [];
$applications[$application]['protocol'] = $traffic['protocol'][OSI_LEVEL_4];
$l7 = $traffic['protocol'][OSI_LEVEL_7] === 'Unknown'
? $traffic['server']['port']
: $traffic['protocol'][OSI_LEVEL_7];
$applications[$application]['protocol'] = $traffic['protocol'][OSI_LEVEL_4];
$applications[$application]['application'] = $l7;
$applications[$application]['bandwidth'] = $traffic['thpt']['bps'];
}
}
$sortedApplications = [];
foreach ($applications as $application) {
$sortedApplications[] = [
'application' => $application['application'],
'protocol' => $application['protocol'],
'bandwidth' => $application['bandwidth'],
];
}
usort($sortedApplications, function ($a, $b) {
return $a['bandwidth'] < $b['bandwidth'] ? 1 : -1;
});
$data['applications'] = [];
$data['total_bandwidth'] = round($totalBandwidth / 1000000, 2);
$i = 1;
foreach ($sortedApplications as $application) {
$bandwidthPct = round(100 * $application['bandwidth'] / $totalBandwidth, 2);
$data['applications'][] = [
'application' => $application['application'],
'protocol' => $application['protocol'],
'bandwidth' => round($application['bandwidth'] / 1000000, 2),
'bandwidth_pct' => $bandwidthPct,
];
if ($i >= $preferences['top']) {
break;
}
$i++;
}
}
} catch (Exception $ex) {
$data['error'] = 1;
$data['message'] = str_replace('\n', '<br>', $ex->getMessage());
}
}
// Smarty template initialization
$template = SmartyBC::createSmartyTemplate(__DIR__ . '/src/', './');
$template->assign('data', $data);
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('preferences', $preferences);
$template->assign('theme', $variablesThemeCSS);
$template->display('ntopng.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/servicegroup-monitoring/index.php | centreon/www/widgets/servicegroup-monitoring/index.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 '../require.php';
require_once '../widget-error-handling.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_var(
$_REQUEST['widgetId'],
FILTER_VALIDATE_INT,
);
try {
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
global $pearDB;
$configurationDatabase = $dependencyInjector['configuration_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$autoRefresh = filter_var(
$preferences['refresh_interval'],
FILTER_VALIDATE_INT,
);
$variablesThemeCSS = match ($centreon->user->theme) {
'light' => 'Generic-theme',
'dark' => 'Centreon-Dark',
default => throw new Exception('Unknown user theme : ' . $centreon->user->theme),
};
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
$theme = $variablesThemeCSS === 'Generic-theme'
? $variablesThemeCSS . '/Variables-css'
: $variablesThemeCSS;
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error fetching data for servicegroup-monitoring widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/servicegroup-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign('widgetId', $widgetId);
$template->assign('preferences', $preferences);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('theme', $variablesThemeCSS);
$bMoreViews = 0;
if ($preferences['more_views']) {
$bMoreViews = $preferences['more_views'];
}
$template->assign('more_views', $bMoreViews);
$template->display('index.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/servicegroup-monitoring/src/export.php | centreon/www/widgets/servicegroup-monitoring/src/export.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\ValueObject\QueryParameter;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="servicegroups-monitoring.csv"');
require_once '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/widgets/servicegroup-monitoring/src/class/ServicegroupMonitoring.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$configurationDatabase = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $configurationDatabase) == 0) {
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/servicegroup-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$centreon = $_SESSION['centreon'];
$widgetId = $_REQUEST['widgetId'];
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$serviceGroupService = new ServicegroupMonitoring($realtimeDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$hostStateLabels = [
0 => 'Up',
1 => 'Down',
2 => 'Unreachable',
4 => 'Pending',
];
$serviceStateLabels = [
0 => 'Ok',
1 => 'Warning',
2 => 'Critical',
3 => 'Unknown',
4 => 'Pending',
];
$baseQuery = 'FROM servicegroups ';
$queryParameters = [];
$accessGroups = new AccessGroupCollection();
if (! $centreon->user->admin) {
$acl = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acl->getAccessGroups();
['parameters' => $queryParameters, 'placeholderList' => $accessGroupList] = createMultipleBindParameters(
$accessGroups->getIds(),
'access_group',
QueryParameterTypeEnum::INTEGER
);
$configurationDatabaseName = $configurationDatabase->getConnectionConfig()->getDatabaseNameConfiguration();
$baseQuery .= <<<SQL
INNER JOIN {$configurationDatabaseName}.acl_resources_sg_relations arsr
ON servicegroups.servicegroup_id = arsr.sg_id
INNER JOIN {$configurationDatabaseName}.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN {$configurationDatabaseName}.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN {$configurationDatabaseName}.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN ({$accessGroupList})
SQL;
}
if (isset($preferences['sg_name_search']) && trim($preferences['sg_name_search']) != '') {
$tab = explode(' ', $preferences['sg_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && trim($search) != '') {
$baseQuery = CentreonUtils::conditionBuilder(
$baseQuery,
'name ' . CentreonUtils::operandToMysqlFormat($op) . ' :search '
);
$queryParameters[] = QueryParameter::string('search', $search);
}
}
$orderBy = 'name ASC';
$allowedOrderColumns = ['name'];
$allowedDirections = ['ASC', 'DESC'];
if (isset($preferences['order_by']) && trim($preferences['order_by']) !== '') {
$aOrder = explode(' ', trim($preferences['order_by']));
$column = $aOrder[0] ?? '';
$direction = isset($aOrder[1]) ? strtoupper($aOrder[1]) : 'ASC';
if (in_array($column, $allowedOrderColumns, true) && in_array($direction, $allowedDirections, true)) {
$orderBy = $column . ' ' . $direction;
}
}
try {
// Query to count total rows
$countQuery = 'SELECT COUNT(DISTINCT servicegroups.servicegroup_id) ' . $baseQuery;
$nbRows = (int) $realtimeDatabase->fetchOne($countQuery, QueryParameters::create($queryParameters));
// Main SELECT query
$query = 'SELECT DISTINCT 1 AS REALTIME, name, servicegroup_id ' . $baseQuery;
$query .= " ORDER BY {$orderBy}";
$data = [];
$detailMode = false;
if (isset($preferences['enable_detailed_mode']) && $preferences['enable_detailed_mode']) {
$detailMode = true;
}
foreach ($realtimeDatabase->iterateAssociative($query, QueryParameters::create($queryParameters)) as $row) {
$data[$row['name']]['name'] = $row['name'];
$data[$row['name']]['host_state'] = $serviceGroupService->getHostStates(
$row['name'],
(int) $centreon->user->admin === 1,
$accessGroups,
$detailMode
);
$data[$row['name']]['service_state'] = $serviceGroupService->getServiceStates(
$row['name'],
(int) $centreon->user->admin === 1,
$accessGroups,
$detailMode
);
}
} catch (CentreonDbException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while exporting service group monitoring',
[
'message' => $e->getMessage(),
'parameters' => [
'entries_per_page' => $entriesPerPage,
'page' => $page,
'orderby' => $orderby,
],
],
$e
);
}
$template->assign('preferences', $preferences);
$template->assign('hostStateLabels', $hostStateLabels);
$template->assign('serviceStateLabels', $serviceStateLabels);
$template->assign('data', $data);
$template->display('export.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/servicegroup-monitoring/src/index.php | centreon/www/widgets/servicegroup-monitoring/src/index.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\ValueObject\QueryParameter;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
require_once '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonLog.class.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
require_once $centreon_path . 'www/widgets/servicegroup-monitoring/src/class/ServicegroupMonitoring.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId']) || ! isset($_REQUEST['page'])) {
exit();
}
/**
* @var CentreonDB $configurationDatabase
*/
$configurationDatabase = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $configurationDatabase) == 0) {
exit();
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/servicegroup-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$centreon = $_SESSION['centreon'];
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
$widgetId = filter_var(
$_REQUEST['widgetId'],
FILTER_VALIDATE_INT,
);
$page = filter_var(
$_REQUEST['page'],
FILTER_VALIDATE_INT,
);
if ($widgetId === false) {
throw new InvalidArgumentException('Widget ID must be an integer');
}
if ($page === false) {
throw new InvalidArgumentException('page must be an integer');
}
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$sgMonObj = new ServicegroupMonitoring($realtimeDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$aColorHost = [
0 => 'host_up',
1 => 'host_down',
2 => 'host_unreachable',
4 => 'host_pending',
];
$aColorService = [
0 => 'service_ok',
1 => 'service_warning',
2 => 'service_critical',
3 => 'service_unknown',
4 => 'pending',
];
$hostStateLabels = [
0 => 'Up',
1 => 'Down',
2 => 'Unreachable',
4 => 'Pending',
];
$serviceStateLabels = [
0 => 'Ok',
1 => 'Warning',
2 => 'Critical',
3 => 'Unknown',
4 => 'Pending',
];
// Prepare the base query
$baseQuery = 'FROM servicegroups ';
$queryParameters = [];
$accessGroups = new AccessGroupCollection();
if (! $centreon->user->admin) {
$acl = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acl->getAccessGroups();
['parameters' => $queryParameters, 'placeholderList' => $accessGroupList] = createMultipleBindParameters(
$accessGroups->getIds(),
'access_group',
QueryParameterTypeEnum::INTEGER
);
$configurationDatabaseName = $configurationDatabase->getConnectionConfig()->getDatabaseNameConfiguration();
$baseQuery .= <<<SQL
INNER JOIN {$configurationDatabaseName}.acl_resources_sg_relations arsr
ON servicegroups.servicegroup_id = arsr.sg_id
INNER JOIN {$configurationDatabaseName}.acl_resources res
ON arsr.acl_res_id = res.acl_res_id
INNER JOIN {$configurationDatabaseName}.acl_res_group_relations argr
ON res.acl_res_id = argr.acl_res_id
INNER JOIN {$configurationDatabaseName}.acl_groups ag
ON argr.acl_group_id = ag.acl_group_id
WHERE ag.acl_group_id IN ({$accessGroupList})
SQL;
}
if (isset($preferences['sg_name_search']) && trim($preferences['sg_name_search']) != '') {
$tab = explode(' ', $preferences['sg_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && trim($search) != '') {
$baseQuery = CentreonUtils::conditionBuilder(
$baseQuery,
'name ' . CentreonUtils::operandToMysqlFormat($op) . ' :search '
);
$queryParameters[] = QueryParameter::string('search', $search);
}
}
$orderby = 'name ASC';
$allowedOrderColumns = ['name'];
const ORDER_DIRECTION_ASC = 'ASC';
const ORDER_DIRECTION_DESC = 'DESC';
const DEFAULT_ENTRIES_PER_PAGE = 10;
$allowedDirections = [ORDER_DIRECTION_ASC, ORDER_DIRECTION_DESC];
$defaultDirection = ORDER_DIRECTION_ASC;
$orderByToAnalyse = isset($preferences['order_by'])
? trim($preferences['order_by'])
: null;
if ($orderByToAnalyse !== null) {
$orderByToAnalyse .= " {$defaultDirection}";
[$column, $direction] = explode(' ', $orderByToAnalyse);
if (in_array($column, $allowedOrderColumns, true) && in_array($direction, $allowedDirections, true)) {
$orderby = $column . ' ' . $direction;
}
}
try {
// Query to count total rows
$countQuery = 'SELECT COUNT(*) ' . $baseQuery;
$nbRows = (int) $realtimeDatabase->fetchOne($countQuery, QueryParameters::create($queryParameters));
// Sanitize and validate input
$entriesPerPage = filter_var($preferences['entries'], FILTER_VALIDATE_INT);
if ($entriesPerPage === false || $entriesPerPage < 1) {
$entriesPerPage = DEFAULT_ENTRIES_PER_PAGE; // Default value
}
$offset = max(0, $page) * $entriesPerPage;
// Main SELECT query with LIMIT
$query = 'SELECT name, servicegroup_id ' . $baseQuery;
$query .= " ORDER BY {$orderby}";
$query .= ' LIMIT :offset, :entriesPerPage';
$queryParameters[] = QueryParameter::int('offset', $offset);
$queryParameters[] = QueryParameter::int('entriesPerPage', $entriesPerPage);
$kernel = App\Kernel::createForWeb();
$resourceController = $kernel->getContainer()->get(
Centreon\Application\Controller\MonitoringResourceController::class
);
$buildServicegroupUri = function (
$servicegroups = [],
$types = [],
$statuses = [],
$search = '',
) use ($resourceController) {
return $resourceController->buildListingUri(
[
'filter' => json_encode(
[
'criterias' => [
[
'name' => 'service_groups',
'value' => $servicegroups,
],
[
'name' => 'resource_types',
'value' => $types,
],
[
'name' => 'statuses',
'value' => $statuses,
],
[
'name' => 'search',
'value' => $search,
],
],
]
),
]
);
};
$buildParameter = function ($id, $name) {
return [
'id' => $id,
'name' => $name,
];
};
$hostType = $buildParameter('host', 'Host');
$serviceType = $buildParameter('service', 'Service');
$okStatus = $buildParameter('OK', 'Ok');
$warningStatus = $buildParameter('WARNING', 'Warning');
$criticalStatus = $buildParameter('CRITICAL', 'Critical');
$unknownStatus = $buildParameter('UNKNOWN', 'Unknown');
$pendingStatus = $buildParameter('PENDING', 'Pending');
$data = [];
$detailMode = false;
if (isset($preferences['enable_detailed_mode']) && $preferences['enable_detailed_mode']) {
$detailMode = true;
}
foreach ($realtimeDatabase->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
$servicegroup = [
'id' => (int) $record['servicegroup_id'],
'name' => $record['name'],
];
$hostStates = $sgMonObj->getHostStates(
$record['name'],
$centreon->user->admin === '1',
$accessGroups,
$detailMode
);
$serviceStates = $sgMonObj->getServiceStates(
$record['name'],
$centreon->user->admin === '1',
$accessGroups,
$detailMode
);
if ($detailMode === true) {
foreach ($hostStates as $hostName => &$properties) {
$properties['details_uri'] = $useDeprecatedPages
? '../../main.php?p=20202&o=hd&host_name=' . $hostName
: $resourceController->buildHostDetailsUri($properties['host_id']);
$properties['services_uri'] = $useDeprecatedPages
? '../../main.php?p=20201&host_search=' . $hostName . '&sg=' . $servicegroup['id']
: $buildServicegroupUri(
[$servicegroup],
[$serviceType],
[],
'h.name:' . $hostName
);
}
foreach ($serviceStates as $hostId => &$serviceState) {
foreach ($serviceState as $serviceId => &$properties) {
$properties['details_uri'] = $useDeprecatedPages
? '../../main.php?p=20201&o=svcd&host_name=' . $properties['name']
. '&service_description=' . $properties['description']
: $resourceController->buildServiceDetailsUri(
$hostId,
$serviceId
);
}
}
}
$serviceGroupDeprecatedUri = '../../main.php?p=20201&search=0'
. '&host_search=0&output_search=0&hg=0&sg=' . $servicegroup['id'];
$serviceGroupUri = $useDeprecatedPages
? $serviceGroupDeprecatedUri
: $buildServicegroupUri([$servicegroup]);
$serviceGroupServicesOkUri = $useDeprecatedPages
? $serviceGroupDeprecatedUri . '&o=svc&statusFilter=ok'
: $buildServicegroupUri([$servicegroup], [$serviceType], [$okStatus]);
$serviceGroupServicesWarningUri = $useDeprecatedPages
? $serviceGroupDeprecatedUri . '&o=svc&statusFilter=warning'
: $buildServicegroupUri([$servicegroup], [$serviceType], [$warningStatus]);
$serviceGroupServicesCriticalUri = $useDeprecatedPages
? $serviceGroupDeprecatedUri . '&o=svc&statusFilter=critical'
: $buildServicegroupUri([$servicegroup], [$serviceType], [$criticalStatus]);
$serviceGroupServicesPendingUri = $useDeprecatedPages
? $serviceGroupDeprecatedUri . '&o=svc&statusFilter=pending'
: $buildServicegroupUri([$servicegroup], [$serviceType], [$pendingStatus]);
$serviceGroupServicesUnknownUri = $useDeprecatedPages
? $serviceGroupDeprecatedUri . '&o=svc&statusFilter=unknown'
: $buildServicegroupUri([$servicegroup], [$serviceType], [$unknownStatus]);
$data[$record['name']] = [
'name' => $record['name'],
'svc_id' => $record['servicegroup_id'],
'sgurl' => $serviceGroupUri,
'host_state' => $hostStates,
'service_state' => $serviceStates,
'sg_service_ok_uri' => $serviceGroupServicesOkUri,
'sg_service_warning_uri' => $serviceGroupServicesWarningUri,
'sg_service_critical_uri' => $serviceGroupServicesCriticalUri,
'sg_service_unknown_uri' => $serviceGroupServicesUnknownUri,
'sg_service_pending_uri' => $serviceGroupServicesPendingUri,
];
}
} catch (CentreonDbException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching service group monitoring',
[
'message' => $e->getMessage(),
'parameters' => [
'entries_per_page' => $entriesPerPage,
'page' => $page,
'orderby' => $orderby,
],
],
$e
);
}
$autoRefresh = filter_var($preferences['refresh_interval'], FILTER_VALIDATE_INT);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('preferences', $preferences);
$template->assign('nbRows', $nbRows);
$template->assign('page', $page);
$template->assign('orderby', $orderby);
$template->assign('data', $data);
$template->assign('dataJS', count($data));
$template->assign('aColorHost', $aColorHost);
$template->assign('aColorService', $aColorService);
$template->assign('preferences', $preferences);
$template->assign('hostStateLabels', $hostStateLabels);
$template->assign('serviceStateLabels', $serviceStateLabels);
$template->assign('centreon_path', $centreon_path);
$bMoreViews = 0;
if ($preferences['more_views']) {
$bMoreViews = $preferences['more_views'];
}
$template->assign('more_views', $bMoreViews);
$template->display('table.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/servicegroup-monitoring/src/class/ServicegroupMonitoring.class.php | centreon/www/widgets/servicegroup-monitoring/src/class/ServicegroupMonitoring.class.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;
use Core\Security\AccessGroup\Domain\Collection\AccessGroupCollection;
class ServicegroupMonitoring
{
protected $dbb;
/**
* Constructor
*
* @param CentreonDB $dbb
* @return void
*/
public function __construct($dbb)
{
$this->dbb = $dbb;
}
/**
* Get Host States
*
* @param string $serviceGroupName
* @param bool $isUserAdmin
* @param AccessGroupCollection $accessGroups
* @param bool $detailFlag
* @return array
*/
public function getHostStates(
string $serviceGroupName,
bool $isUserAdmin,
AccessGroupCollection $accessGroups,
bool $detailFlag = false,
): array {
if (
empty($serviceGroupName)
|| (! $isUserAdmin && $accessGroups->isEmpty())
) {
return [];
}
$queryParameters = [];
$queryParameters[] = QueryParameter::string('serviceGroupName', $serviceGroupName);
$query = <<<'SQL'
SELECT DISTINCT
h.host_id,
h.state,
h.name,
h.alias,
ssg.servicegroup_id
FROM hosts h
INNER JOIN services_servicegroups ssg
ON h.host_id = ssg.host_id
INNER JOIN servicegroups sg
ON ssg.servicegroup_id = sg.servicegroup_id
SQL;
if (! $isUserAdmin) {
$accessGroupsList = implode(', ', $accessGroups->getIds());
$query .= <<<SQL
INNER JOIN centreon_acl
ON centreon_acl.host_id = h.host_id
AND centreon_acl.group_id IN ({$accessGroupsList})
SQL;
}
$query .= <<<'SQL'
WHERE h.name NOT LIKE '_Module_%'
AND h.enabled = 1
AND sg.name = :serviceGroupName
ORDER BY h.name
SQL;
$tab = [];
$detailTab = [];
foreach ($this->dbb->iterateAssociative($query, QueryParameters::create($queryParameters)) as $record) {
if (! isset($tab[$record['state']])) {
$tab[$record['state']] = 0;
}
if (! isset($detailTab[$record['name']])) {
$detailTab[$record['name']] = [];
}
foreach ($record as $key => $val) {
$detailTab[$record['name']][$key] = $val;
}
$tab[$record['state']]++;
}
if ($detailFlag == true) {
return $detailTab;
}
return $tab;
}
/**
* Get Service States
*
* @param string $serviceGroupName
* @param bool $isUserAdmin
* @param AccessGroupCollection $accessGroups
* @param bool $detailFlag
* @return array
*/
public function getServiceStates(
string $serviceGroupName,
bool $isUserAdmin,
AccessGroupCollection $accessGroups,
bool $detailFlag = false,
): array {
if (
empty($serviceGroupName)
|| (! $isUserAdmin && $accessGroups->isEmpty())
) {
return [];
}
$query = <<<'SQL'
SELECT DISTINCT
h.host_id,
s.state,
h.name,
s.service_id,
s.description,
ssg.servicegroup_id
FROM hosts h
INNER JOIN services s
ON h.host_id = s.host_id
INNER JOIN services_servicegroups ssg
ON s.host_id = ssg.host_id
AND s.service_id = ssg.service_id
INNER JOIN servicegroups sg
ON ssg.servicegroup_id = sg.servicegroup_id
SQL;
if (! $isUserAdmin) {
$accessGroupsList = implode(', ', $accessGroups->getIds());
$query .= <<<SQL
INNER JOIN centreon_acl acl
ON h.host_id = acl.host_id
AND s.service_id = acl.service_id
AND acl.group_id IN ({$accessGroupsList})
SQL;
}
$query .= <<<'SQL'
WHERE h.name NOT LIKE '_Module_%'
AND s.enabled = 1
AND sg.name = :serviceGroupName
ORDER BY h.name
SQL;
$tab = [];
$detailTab = [];
$queryParameters = QueryParameters::create([QueryParameter::string('serviceGroupName', $serviceGroupName)]);
foreach ($this->dbb->iterateAssociative($query, $queryParameters) as $record) {
if (! isset($tab[$record['state']])) {
$tab[$record['state']] = 0;
}
if (! isset($detailTab[$record['host_id']])) {
$detailTab[$record['host_id']] = [];
}
if (isset($detailTab[$record['name']]) && ! isset($detailTab[$record['name']][$record['service_id']])) {
$detailTab[$record['host_id']][$record['service_id']] = [];
}
foreach ($record as $key => $val) {
$detailTab[$record['host_id']][$record['service_id']][$key] = $val;
}
$tab[$record['state']]++;
}
if ($detailFlag == true) {
return $detailTab;
}
return $tab;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/host-monitoring/index.php | centreon/www/widgets/host-monitoring/index.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 '../require.php';
require_once '../widget-error-handling.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId'])) {
exit;
}
$centreon = $_SESSION['centreon'];
$widgetId = filter_input(INPUT_GET, 'widgetId', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
try {
$db = $dependencyInjector['configuration_db'];
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$autoRefresh = filter_var($preferences['refresh_interval'], FILTER_VALIDATE_INT);
if ($autoRefresh === false || $autoRefresh < 5) {
$autoRefresh = 30;
}
$variablesThemeCSS = match ($centreon->user->theme) {
'light' => 'Generic-theme',
'dark' => 'Centreon-Dark',
default => throw new Exception('Unknown user theme : ' . $centreon->user->theme),
};
$theme = $variablesThemeCSS === 'Generic-theme'
? $variablesThemeCSS . '/Variables-css'
: $variablesThemeCSS;
} catch (Exception $exception) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_BUSINESS_LOG,
message: 'Error while using host-monitoring widget: ' . $exception->getMessage(),
customContext: [
'widget_id' => $widgetId,
],
exception: $exception
);
showError($exception->getMessage(), $theme ?? 'Generic-theme/Variables-css');
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/host-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign('widgetId', $widgetId);
$template->assign('preferences', $preferences);
$template->assign('autoRefresh', $autoRefresh);
$bMoreViews = 0;
if ($preferences['more_views']) {
$bMoreViews = $preferences['more_views'];
}
$template->assign('more_views', $bMoreViews);
$template->assign('theme', $variablesThemeCSS);
$template->display('index.ihtml');
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/host-monitoring/src/export.php | centreon/www/widgets/host-monitoring/src/export.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\ValueObject\QueryParameter;
require_once '../../require.php';
require_once './DB-Func.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonMedia.class.php';
require_once $centreon_path . 'www/class/centreonCriticality.class.php';
require_once $centreon_path . 'www/include/common/sqlCommonFunction.php';
session_start();
if (! isset($_SESSION['centreon'], $_GET['widgetId'], $_GET['list'])) {
// As the header is already defined, if one of these parameters is missing, an empty CSV is exported
exit;
}
/**
* @var CentreonDB $configurationDatabase
*/
$configurationDatabase = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $configurationDatabase) == 0) {
exit;
}
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
// Init Objects
$criticality = new CentreonCriticality($configurationDatabase);
$aStateType = [
'1' => 'H',
'0' => 'S',
];
$centreon = $_SESSION['centreon'];
$widgetId = filter_input(
INPUT_GET,
'widgetId',
FILTER_VALIDATE_INT,
['options' => ['default' => 0]],
);
/**
* Sanitize and concatenate selected resources for the query
*/
// Check returned list and make an array of it
if (str_contains($_GET['list'], ',')) {
$exportList = explode(',', $_GET['list']);
} else {
$exportList[] = $_GET['list'];
}
// if export list contains a 0, that means all checkboxes a checked.
if (in_array('0', $exportList, true)) {
$exportList = $_SESSION[sprintf('w_hm_%d', $widgetId)];
}
// Filter out invalid host IDs
$filteredHostList = array_filter($exportList, static function ($hostId) {
return (int) $hostId > 0; // Keep only valid positive integers
});
$mainQueryParameters = [];
try {
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
} catch (Exception $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while getting widget preferences for the host monitoring custom view',
['widget_id' => $widgetId],
$e
);
throw $e;
}
// Get status labels
$stateLabels = getLabels();
// Request
$columns = <<<'SQL'
SELECT
1 AS REALTIME,
h.host_id,
h.name,
h.alias,
h.flapping,
state,
state_type,
address,
last_hard_state,
output,
scheduled_downtime_depth,
acknowledged,
notify,
active_checks,
passive_checks,
last_check,
last_state_change,
last_hard_state_change,
check_attempt,
max_check_attempts,
action_url,
notes_url,
cv.value AS criticality,
h.icon_image,
h.icon_image_alt,
cv2.value AS criticality_id,
cv.name IS NULL as isnull
SQL;
$baseQuery = <<<'SQL'
FROM hosts h
LEFT JOIN `customvariables` cv
ON (cv.host_id = h.host_id AND cv.service_id IS NULL AND cv.name = 'CRITICALITY_LEVEL')
LEFT JOIN `customvariables` cv2
ON (cv2.host_id = h.host_id AND cv2.service_id IS NULL AND cv2.name = 'CRITICALITY_ID')
SQL;
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acls->getAccessGroups()->getIds();
['parameters' => $accessGroupParameters, 'placeholderList' => $accessGroupList] = createMultipleBindParameters(
$accessGroups,
'access_group',
QueryParameterTypeEnum::INTEGER
);
$baseQuery .= <<<SQL
INNER JOIN centreon_acl acl
ON h.host_id = acl.host_id
AND acl.service_id IS NULL
AND acl.group_id IN ({$accessGroupList})
SQL;
$mainQueryParameters = [...$accessGroupParameters, ...$mainQueryParameters];
}
$baseQuery .= " WHERE enabled = 1 AND h.name NOT LIKE '_Module_%'";
['parameters' => $hostQueryParameters, 'placeholderList' => $hostQuery] = createMultipleBindParameters(
$filteredHostList,
'host_',
QueryParameterTypeEnum::INTEGER,
);
$mainQueryParameters = [...$hostQueryParameters, ...$mainQueryParameters];
if (! empty($hostQuery)) {
$baseQuery .= ' AND h.host_id IN (' . $hostQuery . ') ';
}
if (isset($preferences['host_name_search']) && $preferences['host_name_search'] != '') {
$tab = explode(' ', $preferences['host_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('host_name_search', $search);
$hostNameCondition = 'h.name ' . CentreonUtils::operandToMysqlFormat($op) . ' :host_name_search ';
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $hostNameCondition);
}
}
$stateTab = [];
if (isset($preferences['host_up']) && $preferences['host_up']) {
$stateTab[] = 0;
}
if (isset($preferences['host_down']) && $preferences['host_down']) {
$stateTab[] = 1;
}
if (isset($preferences['host_unreachable']) && $preferences['host_unreachable']) {
$stateTab[] = 2;
}
if ($stateTab !== []) {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' state IN (' . implode(',', $stateTab) . ')');
}
if (isset($preferences['acknowledgement_filter']) && $preferences['acknowledgement_filter']) {
if ($preferences['acknowledgement_filter'] == 'ack') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' acknowledged = 1');
} elseif ($preferences['acknowledgement_filter'] == 'nack') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' acknowledged = 0');
}
}
if (isset($preferences['notification_filter']) && $preferences['notification_filter']) {
if ($preferences['notification_filter'] == 'enabled') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' notify = 1');
} elseif ($preferences['notification_filter'] == 'disabled') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' notify = 0');
}
}
if (isset($preferences['downtime_filter']) && $preferences['downtime_filter']) {
if ($preferences['downtime_filter'] == 'downtime') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' scheduled_downtime_depth > 0 ');
} elseif ($preferences['downtime_filter'] == 'ndowntime') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' scheduled_downtime_depth = 0 ');
}
}
if (isset($preferences['poller_filter']) && $preferences['poller_filter']) {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' instance_id = ' . $preferences['poller_filter'] . ' ');
}
if (isset($preferences['state_type_filter']) && $preferences['state_type_filter']) {
if ($preferences['state_type_filter'] == 'hardonly') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' state_type = 1 ');
} elseif ($preferences['state_type_filter'] == 'softonly') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' state_type = 0 ');
}
}
if (isset($preferences['hostgroup']) && $preferences['hostgroup']) {
$results = explode(',', $preferences['hostgroup']);
['parameters' => $hostGroupIdsParameters, 'placeholderList' => $hostGroupList] = createMultipleBindParameters(
$results,
'hg_id',
QueryParameterTypeEnum::INTEGER,
);
$hostgroupHgIdCondition = <<<SQL
h.host_id IN (
SELECT host_id
FROM hosts_hostgroups
WHERE hostgroup_id IN ({$hostGroupList}))
SQL;
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $hostgroupHgIdCondition);
$mainQueryParameters = [...$mainQueryParameters, ...$hostGroupIdsParameters];
}
if (! empty($preferences['display_severities']) && ! empty($preferences['criticality_filter'])) {
$severities = explode(',', $preferences['criticality_filter']);
['parameters' => $severityParameters, 'placeholderList' => $severityList] = createMultipleBindParameters(
$severities,
'severity_id',
QueryParameterTypeEnum::INTEGER,
);
$SeverityIdCondition
= "h.host_id IN (
SELECT DISTINCT host_host_id
FROM `{$conf_centreon['db']}`.hostcategories_relation
WHERE hostcategories_hc_id IN ({$severityList}))";
$mainQueryParameters = [...$mainQueryParameters, ...$severityParameters];
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $SeverityIdCondition);
}
$orderBy = 'h.name ASC';
$allowedOrderColumns = [
'h.host_id',
'h.name',
'h.alias',
'h.flapping',
'state',
'state_type',
'address',
'last_hard_state',
'output',
'scheduled_downtime_depth',
'acknowledged',
'notify',
'active_checks',
'passive_checks',
'last_check',
'last_state_change',
'last_hard_state_change',
'check_attempt',
'max_check_attempts',
'action_url',
'notes_url',
'cv.value AS criticality',
'h.icon_image',
'h.icon_image_alt',
'criticality_id',
];
const ORDER_DIRECTION_ASC = 'ASC';
const ORDER_DIRECTION_DESC = 'DESC';
$allowedDirections = [ORDER_DIRECTION_ASC, ORDER_DIRECTION_DESC];
$defaultDirection = ORDER_DIRECTION_ASC;
$orderByToAnalyse = isset($preferences['order_by'])
? trim($preferences['order_by'])
: null;
if ($orderByToAnalyse !== null) {
$orderByToAnalyse .= " {$defaultDirection}";
[$column, $direction] = explode(' ', $orderByToAnalyse);
if (in_array($column, $allowedOrderColumns, true) && in_array($direction, $allowedDirections, true)) {
$orderBy = $column . ' ' . $direction;
}
}
$data = [];
try {
// Main SELECT query
$query = $columns . $baseQuery;
$query .= " ORDER BY {$orderBy}";
$outputLength = $preferences['output_length'] ?? 50;
$commentLength = $preferences['comment_length'] ?? 50;
$hostObj = new CentreonHost($configurationDatabase);
$gmt = new CentreonGMT();
$gmt->getMyGMTFromSession(session_id());
foreach ($realtimeDatabase->iterateAssociative($query, QueryParameters::create($mainQueryParameters)) as $row) {
foreach ($row as $key => $value) {
if ($key == 'last_check') {
$value = $gmt->getDate('Y-m-d H:i:s', $value);
} elseif ($key == 'last_state_change' || $key == 'last_hard_state_change') {
$value = time() - $value;
$value = CentreonDuration::toString($value);
} elseif ($key == 'check_attempt') {
$value = $value . '/' . $row['max_check_attempts'] . ' (' . $aStateType[$row['state_type']] . ')';
} elseif ($key == 'state') {
$value = $stateLabels[$value];
} elseif ($key == 'output') {
$value = substr($value, 0, $outputLength);
} elseif (($key == 'action_url' || $key == 'notes_url') && $value) {
if (! preg_match("/(^http[s]?)|(^\/\/)/", $value)) {
$value = '//' . $value;
}
$value = CentreonUtils::escapeSecure($hostObj->replaceMacroInString($row['name'], $value));
} elseif ($key == 'criticality' && $value != '') {
$critData = $criticality->getData($row['criticality_id']);
$value = $critData['hc_name'];
}
$data[$row['host_id']][$key] = $value;
}
if (isset($preferences['display_last_comment']) && $preferences['display_last_comment']) {
$res2 = $realtimeDatabase->prepare(
<<<'SQL'
SELECT
1 AS REALTIME,
data
FROM comments
WHERE host_id = :hostId
AND service_id IS NULL
ORDER BY entry_time DESC
LIMIT 1
SQL
);
$res2->bindValue(':hostId', $row['host_id'], PDO::PARAM_INT);
$res2->execute();
$data[$row['host_id']]['comment'] = ($row2 = $res2->fetch()) ? substr($row2['data'], 0, $commentLength) : '-';
}
}
} catch (CentreonDbException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while fetching host monitoring',
[
'message' => $e->getMessage(),
'parameters' => [
'orderby' => $orderBy,
],
],
$e
);
}
$lines = [];
foreach ($data as $lineData) {
$lines[0] = [];
$line = [];
// severity column
if ($preferences['display_severities']) {
$lines[0][] = 'Severity';
$line[] = $lineData['criticality'];
}
// name column
if ($preferences['display_host_name'] && $preferences['display_host_alias']) {
$lines[0][] = 'Host Name - Host Alias';
$line[] = $lineData['name'] . ' - ' . $lineData['alias'];
} elseif ($preferences['display_host_alias']) {
$lines[0][] = 'Host Alias';
$line[] = $lineData['alias'];
} else {
$lines[0][] = 'Host Name';
$line[] = $lineData['name'];
}
// ip address column
if ($preferences['display_ip']) {
$lines[0][] = 'Address';
$line[] = $lineData['address'];
}
// status column
if ($preferences['display_status']) {
$lines[0][] = 'Status';
$line[] = $lineData['state'];
}
// duration column
if ($preferences['display_duration']) {
$lines[0][] = 'Duration';
$line[] = $lineData['last_state_change'];
}
// hard state duration column
if ($preferences['display_hard_state_duration']) {
$lines[0][] = 'Hard State Duration';
$line[] = $lineData['last_hard_state_change'];
}
// last check column
if ($preferences['display_last_check']) {
$lines[0][] = 'Last Check';
$line[] = $lineData['last_check'];
}
// check attempts column
if ($preferences['display_tries']) {
$lines[0][] = 'Attempt';
$line[] = $lineData['check_attempt'];
}
// output column
if ($preferences['display_output']) {
$lines[0][] = 'Output';
$line[] = $lineData['output'];
}
// comment column
if ($preferences['display_last_comment']) {
$lines[0][] = 'Last comment';
$line[] = $lineData['comment'];
}
$lines[] = $line;
}
// open raw memory as file so no temp files needed, you might run out of memory though
$memoryFile = fopen('php://memory', 'w');
// loop over the input array
foreach ($lines as $line) {
// generate csv lines from the inner arrays
fputcsv($memoryFile, $line, ';');
}
// reset the file pointer to the start of the file
fseek($memoryFile, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="hosts-monitoring.csv";');
// make php send the generated csv lines to the browser
fpassthru($memoryFile);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/host-monitoring/src/sendCmd.php | centreon/www/widgets/host-monitoring/src/sendCmd.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 '../../require.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonService.class.php';
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
session_start();
try {
if (
! isset($_SESSION['centreon'])
|| ! isset($_POST['cmdType'])
|| ! isset($_POST['hosts'])
|| ! isset($_POST['author'])
) {
throw new Exception('Missing data');
}
$db = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $db) == 0) {
throw new Exception('Invalid session');
}
$centreon = $_SESSION['centreon'];
$oreon = $centreon;
$type = filter_input(INPUT_POST, 'cmdType', FILTER_SANITIZE_STRING, ['options' => ['default' => '']]);
// @TODO choose what to do with harmful names and comments
$author = filter_input(INPUT_POST, 'author', FILTER_SANITIZE_STRING, ['options' => ['default' => '']]);
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING, ['options' => ['default' => '']]) ?? '';
$externalCmd = new CentreonExternalCommand($centreon);
$hostObj = new CentreonHost($db);
$svcObj = new CentreonService($db);
$command = '';
if ($type == 'ack') {
$persistent = 0;
$sticky = 0;
$notify = 0;
if (isset($_POST['persistent'])) {
$persistent = 1;
}
if (isset($_POST['sticky'])) {
$sticky = 2;
}
if (isset($_POST['notify'])) {
$notify = 1;
}
$command = "ACKNOWLEDGE_HOST_PROBLEM;%s;{$sticky};{$notify};{$persistent};{$author};{$comment}";
$commandSvc = "ACKNOWLEDGE_SVC_PROBLEM;%s;%s;{$sticky};{$notify};{$persistent};{$author};{$comment}";
if (isset($_POST['forcecheck'])) {
$forceCmd = 'SCHEDULE_FORCED_HOST_CHECK;%s;' . time();
$forceCmdSvc = 'SCHEDULE_FORCED_SVC_CHECK;%s;%s;' . time();
}
} elseif ($type == 'downtime') {
$fixed = 0;
if (isset($_POST['fixed'])) {
$fixed = 1;
}
$duration = 0;
if (isset($_POST['dayduration'])) {
$duration += ($_POST['dayduration'] * 86400);
}
if (isset($_POST['hourduration'])) {
$duration += ($_POST['hourduration'] * 3600);
}
if (isset($_POST['minuteduration'])) {
$duration += ($_POST['minuteduration'] * 60);
}
if (! isset($_POST['start_time']) || ! isset($_POST['end_time'])) {
throw new Exception('Missing downtime start/end');
}
[$tmpHstart, $tmpMstart] = array_map('trim', explode(':', $_POST['start_time']));
[$tmpHend, $tmpMend] = array_map('trim', explode(':', $_POST['end_time']));
$dateStart = $_POST['alternativeDateStart'];
$start = $dateStart . ' ' . $tmpHstart . ':' . $tmpMstart;
$start = CentreonUtils::getDateTimeTimestamp($start);
$dateEnd = $_POST['alternativeDateEnd'];
$end = $dateEnd . ' ' . $tmpHend . ':' . $tmpMend;
$end = CentreonUtils::getDateTimeTimestamp($end);
$command = "SCHEDULE_HOST_DOWNTIME;%s;{$start};{$end};{$fixed};0;{$duration};{$author};{$comment}";
$commandSvc = "SCHEDULE_SVC_DOWNTIME;%s;%s;{$start};{$end};{$fixed};0;{$duration};{$author};{$comment}";
} else {
throw new Exception('Unknown command');
}
if ($command != '') {
$externalCommandMethod = 'set_process_command';
if (method_exists($externalCmd, 'setProcessCommand')) {
$externalCommandMethod = 'setProcessCommand';
}
$hosts = explode(',', $_POST['hosts']);
foreach ($hosts as $hostId) {
$hostId = filter_var($hostId, FILTER_VALIDATE_INT) ?: 0;
if ($hostId !== 0) {
$hostname = $hostObj->getHostName($hostId);
$pollerId = $hostObj->getHostPollerId($hostId);
$externalCmd->{$externalCommandMethod}(sprintf($command, $hostname), $pollerId);
if (isset($forceCmd)) {
$externalCmd->{$externalCommandMethod}(sprintf($forceCmd, $hostname), $pollerId);
}
if (isset($_POST['processServices'])) {
$services = $svcObj->getServiceId(null, $hostname);
foreach ($services as $svcDesc => $svcId) {
$externalCmd->{$externalCommandMethod}(sprintf($commandSvc, $hostname, $svcDesc), $pollerId);
if (isset($forceCmdSvc)) {
$externalCmd->{$externalCommandMethod}(sprintf($forceCmdSvc, $hostname, $svcDesc), $pollerId);
}
}
}
}
}
$externalCmd->write();
}
} catch (Exception $e) {
echo $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/widgets/host-monitoring/src/action.php | centreon/www/widgets/host-monitoring/src/action.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 '../../require.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonDB.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonExternalCommand.class.php';
session_start();
try {
if (
! isset($_SESSION['centreon'])
|| ! isset($_REQUEST['cmd'])
|| ! isset($_REQUEST['selection'])
) {
throw new Exception('Missing data');
}
$db = new CentreonDB();
if (CentreonSession::checkSession(session_id(), $db) == 0) {
throw new Exception('Invalid session');
}
$centreon = $_SESSION['centreon'];
$oreon = $centreon;
$cmd = filter_input(INPUT_GET, 'cmd', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$selection = '';
$hosts = explode(',', $_GET['selection']);
foreach ($hosts as $host) {
$selection .= (filter_var($host, FILTER_VALIDATE_INT) ?: 0) . ',';
}
$selection = rtrim($selection, ',');
$externalCmd = new CentreonExternalCommand($centreon);
$hostObj = new CentreonHost($db);
$successMsg = _('External Command successfully submitted... Exiting window...');
$result = 0;
$defaultDuration = 7200;
$defaultScale = 's';
if (! empty($centreon->optGen['monitoring_dwt_duration'])) {
$defaultDuration = $centreon->optGen['monitoring_dwt_duration'];
if (! empty($centreon->optGen['monitoring_dwt_duration_scale'])) {
$defaultScale = $centreon->optGen['monitoring_dwt_duration_scale'];
}
}
if ($cmd == 72 || $cmd == 75) {
// Smarty template initialization
$path = $centreon_path . 'www/widgets/host-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$template->assign('stickyLabel', _('Sticky'));
$template->assign('persistentLabel', _('Persistent'));
$template->assign('authorLabel', _('Author'));
$template->assign('notifyLabel', _('Notify'));
$template->assign('commentLabel', _('Comment'));
$template->assign('forceCheckLabel', _('Force active checks'));
$template->assign('fixedLabel', _('Fixed'));
$template->assign('durationLabel', _('Duration'));
$template->assign('startLabel', _('Start'));
$template->assign('endLabel', _('End'));
$template->assign('hosts', $selection);
$template->assign('author', $centreon->user->name);
if ($cmd == 72) {
$template->assign('ackHostSvcLabel', _('Acknowledge services of hosts'));
$template->assign('defaultMessage', sprintf(_('Acknowledged by %s'), $centreon->user->alias));
$template->assign('titleLabel', _('Host Acknowledgement'));
$template->assign('submitLabel', _('Acknowledge'));
// default ack options
$persistent_checked = '';
if (! empty($centreon->optGen['monitoring_ack_persistent'])) {
$persistent_checked = 'checked';
}
$template->assign('persistent_checked', $persistent_checked);
$sticky_checked = '';
if (! empty($centreon->optGen['monitoring_ack_sticky'])) {
$sticky_checked = 'checked';
}
$template->assign('sticky_checked', $sticky_checked);
$notify_checked = '';
if (! empty($centreon->optGen['monitoring_ack_notify'])) {
$notify_checked = 'checked';
}
$template->assign('notify_checked', $notify_checked);
$process_service_checked = '';
if (! empty($centreon->optGen['monitoring_ack_svc'])) {
$process_service_checked = 'checked';
}
$template->assign('process_service_checked', $process_service_checked);
$force_active_checked = '';
if (! empty($centreon->optGen['monitoring_ack_active_checks'])) {
$force_active_checked = 'checked';
}
$template->assign('force_active_checked', $force_active_checked);
$template->display('acknowledge.ihtml');
} elseif ($cmd == 75) {
$template->assign('downtimeHostSvcLabel', _('Set downtime on services of hosts'));
$template->assign('defaultMessage', sprintf(_('Downtime set by %s'), $centreon->user->alias));
$template->assign('titleLabel', _('Host Downtime'));
$template->assign('submitLabel', _('Set Downtime'));
$template->assign('defaultDuration', $defaultDuration);
$template->assign('sDurationLabel', _('seconds'));
$template->assign('mDurationLabel', _('minutes'));
$template->assign('hDurationLabel', _('hours'));
$template->assign('dDurationLabel', _('days'));
$template->assign($defaultScale . 'DefaultScale', 'selected');
// default downtime options
$fixed_checked = '';
if (! empty($centreon->optGen['monitoring_dwt_fixed'])) {
$fixed_checked = 'checked';
}
$template->assign('fixed_checked', $fixed_checked);
$process_service_checked = '';
if (! empty($centreon->optGen['monitoring_dwt_svc'])) {
$process_service_checked = 'checked';
}
$template->assign('process_service_checked', $process_service_checked);
$template->display('downtime.ihtml');
}
} else {
$command = '';
switch ($cmd) {
// remove ack
case 73:
$command = 'REMOVE_HOST_ACKNOWLEDGEMENT;%s';
break;
// enable notif
case 82:
$command = 'ENABLE_HOST_NOTIFICATIONS;%s';
break;
// disable notif
case 83:
$command = 'DISABLE_HOST_NOTIFICATIONS;%s';
break;
// enable check
case 92:
$command = 'ENABLE_HOST_CHECK;%s';
break;
// disable check
case 93:
$command = 'DISABLE_HOST_CHECK;%s';
break;
default:
throw new Exception('Unknown command');
break;
}
if ($command != '') {
$externalCommandMethod = 'set_process_command';
if (method_exists($externalCmd, 'setProcessCommand')) {
$externalCommandMethod = 'setProcessCommand';
}
foreach ($hosts as $hostId) {
$hostId = filter_var($hostId, FILTER_VALIDATE_INT) ?: 0;
if ($hostId !== 0) {
$externalCmd->{$externalCommandMethod}(
sprintf($command, $hostObj->getHostName($hostId)),
$hostObj->getHostPollerId($hostId)
);
}
}
$externalCmd->write();
}
$result = 1;
}
} catch (Exception $e) {
echo $e->getMessage() . '<br/>';
}
?>
<div id='result'></div>
<script type='text/javascript'>
var result = <?php echo $result; ?>;
var successMsg = "<?php echo $successMsg; ?>";
jQuery(function () {
if (result) {
jQuery("#result").html(successMsg);
setTimeout('closeBox()', 2000);
}
jQuery("#submit").click(function () {
sendCmd();
});
jQuery("#submit").button();
toggleDurationField();
jQuery("[name=fixed]").click(function () {
toggleDurationField();
});
//initializing datepicker and timepicker
jQuery(".timepicker").each(function () {
if (!$(this).val()) {
$(this).val(moment().tz(localStorage.getItem('realTimezone')
? localStorage.getItem('realTimezone')
: moment.tz.guess()).format("HH:mm")
);
}
});
jQuery("#start_time, #end_time").timepicker();
initDatepicker();
turnOnEvents();
updateDateAndTime();
});
function closeBox() {
jQuery('#WidgetDowntime').centreonPopin('close');
}
function sendCmd() {
fieldResult = true;
if (jQuery("#comment") && !jQuery("#comment").val()) {
fieldResult = false;
}
if (fieldResult == false) {
jQuery("#result").html("<font color=red><b>Please fill all mandatory fields.</b></font>");
return false;
}
jQuery.ajax({
type: "POST",
url: "./widgets/host-monitoring/src/sendCmd.php",
data: jQuery("#Form").serialize(),
success: function () {
jQuery("#result").html(successMsg);
setTimeout('closeBox()', 2000);
}
});
}
function toggleDurationField() {
if (jQuery("[name=fixed]").is(':checked')) {
jQuery("[name=duration]").attr('disabled', true);
jQuery("[name=duration_scale]").attr('disabled', true);
} else {
jQuery("[name=duration]").removeAttr('disabled');
jQuery("[name=duration_scale]").removeAttr('disabled');
}
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/host-monitoring/src/toolbar.php | centreon/www/widgets/host-monitoring/src/toolbar.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 '../../require.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
session_start();
if (! isset($_SESSION['centreon']) || ! isset($_POST['widgetId'])) {
exit;
}
// Smarty template initialization
$path = $centreon_path . 'www/widgets/host-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$centreon = $_SESSION['centreon'];
$widgetId = filter_input(INPUT_POST, 'widgetId', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$db = new CentreonDB();
$widgetObj = new CentreonWidget($centreon, $db);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
$admin = $centreon->user->admin;
$canDoAction = false;
if ($admin) {
$canDoAction = true;
}
$actions = "<option value='0'>-- " . _('More actions') . ' -- </option>';
if ($canDoAction || $centreon->user->access->checkAction('host_acknowledgement')) {
$actions .= "<option value='72'>" . _('Acknowledge') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_disacknowledgement')) {
$actions .= "<option value='73'>" . _('Remove Acknowledgement') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_schedule_downtime')) {
$actions .= "<option value='75'>" . _('Set Downtime') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_notifications')) {
$actions .= "<option value='82'>" . _('Enable Host Notification') . '</option>';
$actions .= "<option value='83'>" . _('Disable Host Notification') . '</option>';
}
if ($canDoAction || $centreon->user->access->checkAction('host_checks')) {
$actions .= "<option value='92'>" . _('Enable Host Check') . '</option>';
$actions .= "<option value='93'>" . _('Disable Host Check') . '</option>';
}
$template->assign('widgetId', $widgetId);
$template->assign('actions', $actions);
$template->display('toolbar.ihtml');
?>
<script type="text/javascript" src="../../include/common/javascript/centreon/popin.js"></script>
<script type='text/javascript'>
var tab = new Array();
var actions = "<?php echo $actions; ?>";
var widget_id = "<?php echo $widgetId; ?>";
jQuery(function () {
jQuery(".toolbar").change(function () {
if (jQuery(this).val() != 0) {
var checkValues = jQuery("input:checked")
.map(function () {
var tmp = jQuery(this).attr('id').split("_");
return tmp[1];
})
.get().join(",");
if (checkValues != '') {
var url = "./widgets/host-monitoring/src/action.php?widgetId=" + widgetId +
"&selection=" + checkValues + "&cmd=" + jQuery(this).val();
parent.jQuery('#WidgetDowntime').parent().remove();
var popin = parent.jQuery('<div id="WidgetDowntime">');
popin.centreonPopin({
open: true,
url: url,
onClose: () => {
checkValues.split(',').forEach((value) => {
localStorage.removeItem('w_hm_selection_' + value);
jQuery('#selection_' + value).prop('checked', false);
});
}
});
} else {
alert("<?php echo _('Please select one or more items'); ?>");
}
jQuery(this).val(0);
}
});
});
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/host-monitoring/src/index.php | centreon/www/widgets/host-monitoring/src/index.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\ValueObject\QueryParameter;
use App\Kernel;
use Centreon\Application\Controller\MonitoringResourceController;
use Centreon\Domain\Log\Logger;
require_once '../../require.php';
require_once './DB-Func.php';
require_once $centreon_path . 'bootstrap.php';
require_once $centreon_path . 'www/class/centreon.class.php';
require_once $centreon_path . 'www/class/centreonSession.class.php';
require_once $centreon_path . 'www/class/centreonWidget.class.php';
require_once $centreon_path . 'www/class/centreonDuration.class.php';
require_once $centreon_path . 'www/class/centreonUtils.class.php';
require_once $centreon_path . 'www/class/centreonAclLazy.class.php';
require_once $centreon_path . 'www/class/centreonHost.class.php';
require_once $centreon_path . 'www/class/centreonMedia.class.php';
require_once $centreon_path . 'www/class/centreonCriticality.class.php';
CentreonSession::start(1);
if (! isset($_SESSION['centreon']) || ! isset($_REQUEST['widgetId']) || ! isset($_REQUEST['page'])) {
exit;
}
$configurationDatabase = $dependencyInjector['configuration_db'];
if (CentreonSession::checkSession(session_id(), $configurationDatabase) == 0) {
exit;
}
/**
* @var CentreonDB $realtimeDatabase
*/
$realtimeDatabase = $dependencyInjector['realtime_db'];
// Init Objects
$criticality = new CentreonCriticality($configurationDatabase);
$media = new CentreonMedia($configurationDatabase);
// Smarty template initialization
$path = $centreon_path . 'www/widgets/host-monitoring/src/';
$template = SmartyBC::createSmartyTemplate($path, './');
$centreon = $_SESSION['centreon'];
$kernel = Kernel::createForWeb();
/** @var Logger $logger */
$logger = $kernel->getContainer()->get(Logger::class);
/**
* true: URIs will correspond to deprecated pages
* false: URIs will correspond to new page (Resource Status)
*/
$useDeprecatedPages = $centreon->user->doesShowDeprecatedPages();
$widgetId = filter_input(INPUT_GET, 'widgetId', FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1]]);
$mainQueryParameters = [];
try {
$widgetObj = new CentreonWidget($centreon, $configurationDatabase);
$preferences = $widgetObj->getWidgetPreferences($widgetId);
} catch (Exception $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while getting widget preferences for the host monitoring custom view',
['widget_id' => $widgetId],
$e
);
throw $e;
}
// Default colors
$stateColors = getColors($configurationDatabase);
// Get status labels
$stateLabels = getLabels();
$aStateType = [
'1' => 'H',
'0' => 'S',
];
$querySelect = <<<'SQL'
SELECT SQL_CALC_FOUND_ROWS
1 AS REALTIME,
h.host_id,
h.name AS host_name,
h.alias,
h.flapping,
state,
state_type,
address,
last_hard_state,
output,
scheduled_downtime_depth,
acknowledged,
notify,
active_checks,
passive_checks,
last_check,
last_state_change,
last_hard_state_change,
check_attempt,
max_check_attempts,
action_url,
notes_url,
cv.value AS criticality,
h.icon_image,
h.icon_image_alt,
cv2.value AS criticality_id,
cv.name IS NULL as isnull
SQL;
$baseQuery = <<<'SQL'
FROM hosts h
LEFT JOIN `customvariables` cv
ON (cv.host_id = h.host_id AND cv.service_id = 0 AND cv.name = 'CRITICALITY_LEVEL')
LEFT JOIN `customvariables` cv2
ON (cv2.host_id = h.host_id AND cv2.service_id = 0 AND cv2.name = 'CRITICALITY_ID')
SQL;
if (! $centreon->user->admin) {
$acls = new CentreonAclLazy($centreon->user->user_id);
$accessGroups = $acls->getAccessGroups()->getIds();
['parameters' => $accessGroupParameters, 'placeholderList' => $accessGroupList] = createMultipleBindParameters(
$accessGroups,
'access_group',
QueryParameterTypeEnum::INTEGER
);
$baseQuery .= <<<SQL
INNER JOIN centreon_acl acl
ON h.host_id = acl.host_id
AND acl.service_id IS NULL
AND acl.group_id IN ({$accessGroupList})
SQL;
$mainQueryParameters = [...$accessGroupParameters, ...$mainQueryParameters];
}
$baseQuery .= " WHERE enabled = 1 AND h.name NOT LIKE '_Module_%'";
$stateTab = [];
if (isset($preferences['host_name_search']) && $preferences['host_name_search'] != '') {
$tab = explode(' ', $preferences['host_name_search']);
$op = $tab[0];
if (isset($tab[1])) {
$search = $tab[1];
}
if ($op && isset($search) && $search != '') {
$mainQueryParameters[] = QueryParameter::string('host_name_search', $search);
$hostNameCondition = 'h.name ' . CentreonUtils::operandToMysqlFormat($op) . ' :host_name_search ';
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $hostNameCondition);
}
}
if (isset($preferences['notification_filter']) && $preferences['notification_filter']) {
if ($preferences['notification_filter'] == 'enabled') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' notify = 1');
} elseif ($preferences['notification_filter'] == 'disabled') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' notify = 0');
}
}
if (isset($preferences['host_up']) && $preferences['host_up']) {
$stateTab[] = 0;
}
if (isset($preferences['host_down']) && $preferences['host_down']) {
$stateTab[] = 1;
}
if (isset($preferences['host_unreachable']) && $preferences['host_unreachable']) {
$stateTab[] = 2;
}
if ($stateTab !== []) {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' state IN (' . implode(',', $stateTab) . ')');
}
if (isset($preferences['acknowledgement_filter']) && $preferences['acknowledgement_filter']) {
if ($preferences['acknowledgement_filter'] == 'ack') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' acknowledged = 1');
} elseif ($preferences['acknowledgement_filter'] == 'nack') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' acknowledged = 0');
}
}
if (isset($preferences['downtime_filter']) && $preferences['downtime_filter']) {
if ($preferences['downtime_filter'] == 'downtime') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' scheduled_downtime_depth > 0 ');
} elseif ($preferences['downtime_filter'] == 'ndowntime') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' scheduled_downtime_depth = 0 ');
}
}
if (isset($preferences['poller_filter']) && $preferences['poller_filter']) {
$mainQueryParameters[] = QueryParameter::int('instance_id', (int) $preferences['poller_filter']);
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' instance_id = :instance_id ');
}
if (isset($preferences['state_type_filter']) && $preferences['state_type_filter']) {
if ($preferences['state_type_filter'] == 'hardonly') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' state_type = 1 ');
} elseif ($preferences['state_type_filter'] == 'softonly') {
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, ' state_type = 0 ');
}
}
if (isset($preferences['hostgroup']) && $preferences['hostgroup']) {
$results = explode(',', $preferences['hostgroup']);
if ($results !== []) {
['parameters' => $hostGroupIdsParameters, 'placeholderList' => $hostGroupList] = createMultipleBindParameters(
$results,
'hg_id',
QueryParameterTypeEnum::INTEGER,
);
$hostgroupHgIdCondition = <<<SQL
h.host_id IN (
SELECT host_id
FROM hosts_hostgroups
WHERE hostgroup_id IN ({$hostGroupList}))
SQL;
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $hostgroupHgIdCondition);
$mainQueryParameters = [...$mainQueryParameters, ...$hostGroupIdsParameters];
}
}
if (! empty($preferences['display_severities']) && ! empty($preferences['criticality_filter'])) {
$severities = explode(',', $preferences['criticality_filter']);
['parameters' => $severityParameters, 'placeholderList' => $severityList] = createMultipleBindParameters(
$severities,
'severity_id',
QueryParameterTypeEnum::INTEGER,
);
$severityIdCondition = <<<SQL
cv2.value IN ({$severityList})
SQL;
$mainQueryParameters = [...$mainQueryParameters, ...$severityParameters];
$baseQuery = CentreonUtils::conditionBuilder($baseQuery, $severityIdCondition);
}
// prepare order_by
$orderBy = 'h.name ASC';
// Define allowed columns and directions
$allowedOrderColumns = [
'h.name',
'h.alias',
'criticality',
'address',
'state',
'output',
'check_attempt',
'last_check',
'last_state_change',
'last_hard_state_change',
'scheduled_downtime_depth',
'acknowledged',
'notify',
'active_checks',
'passive_checks',
];
const ORDER_DIRECTION_ASC = 'ASC';
const ORDER_DIRECTION_DESC = 'DESC';
$allowedDirections = [ORDER_DIRECTION_ASC, ORDER_DIRECTION_DESC];
$defaultDirection = ORDER_DIRECTION_ASC;
$orderByToAnalyse = isset($preferences['order_by'])
? trim($preferences['order_by'])
: null;
if ($orderByToAnalyse !== null) {
$orderByToAnalyse .= " {$defaultDirection}";
[$column, $direction] = explode(' ', $orderByToAnalyse);
if (in_array($column, $allowedOrderColumns, true) && in_array($direction, $allowedDirections, true)) {
$orderBy = $column . ' ' . $direction;
}
}
// concatenate order by + limit + offset to the query
$baseQuery .= ' ORDER BY ' . $orderBy;
try {
$recordIds = $realtimeDatabase->fetchAllAssociative('SELECT h.host_id' . $baseQuery, QueryParameters::create($mainQueryParameters));
$hostIds = array_map(
fn (array $record) => $record['host_id'],
$recordIds,
);
$nbRows = count($hostIds);
CentreonSession::writeSessionClose(sprintf('w_hm_%d', $widgetId), $hostIds);
} catch (PDOException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while counting hosts for the host monitoring custom view',
['pdo_info' => $e->errorInfo],
$e
);
throw $e;
}
$query = $querySelect . $baseQuery . ' LIMIT :limit OFFSET :offset';
$num = filter_var($preferences['entries'], FILTER_VALIDATE_INT) ?: 10;
$mainQueryParameters[] = QueryParameter::int('limit', $num);
$mainQueryParameters[] = QueryParameter::int('offset', ($page * $num));
try {
$records = $realtimeDatabase->fetchAllAssociative($query, QueryParameters::create($mainQueryParameters));
} catch (PDOException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while getting hosts for the host monitoring custom view',
['pdo_info' => $e->errorInfo, 'query_parameters' => $mainQueryParameters],
$e
);
throw $e;
}
$data = [];
$outputLength = $preferences['output_length'] ?: 50;
$commentLength = $preferences['comment_length'] ?: 50;
try {
$hostObj = new CentreonHost($configurationDatabase);
} catch (PDOException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error when CentreonHost called for the host monitoring custom view',
['pdo_info' => $e->errorInfo],
$e
);
throw $e;
}
$gmt = new CentreonGMT();
$gmt->getMyGMTFromSession(session_id());
$allowedActionProtocols = ['http[s]?', '//', 'ssh', 'rdp', 'ftp', 'sftp'];
$allowedProtocolsRegex = '#(^' . implode(')|(^', $allowedActionProtocols) . ')#';
foreach ($records as $row) {
foreach ($row as $key => $value) {
$data[$row['host_id']][$key] = $value;
}
// last_check
$valueLastCheck = (int) $row['last_check'];
$valueLastCheckTimestamp = time() - $valueLastCheck;
if (
$valueLastCheckTimestamp > 0
&& $valueLastCheckTimestamp < 3600
) {
$valueLastCheck = CentreonDuration::toString($valueLastCheckTimestamp) . ' ago';
}
$data[$row['host_id']]['last_check'] = $valueLastCheck;
// last_state_change
$valueLastState = (int) $row['last_state_change'];
if ($valueLastState > 0) {
$valueLastStateTimestamp = time() - $valueLastState;
$valueLastState = CentreonDuration::toString($valueLastStateTimestamp) . ' ago';
} else {
$valueLastState = 'N/A';
}
$data[$row['host_id']]['last_state_change'] = $valueLastState;
// last_hard_state_change
$valueLastHardState = (int) $row['last_hard_state_change'];
if ($valueLastHardState > 0) {
$valueLastHardStateTimestamp = time() - $valueLastHardState;
$valueLastHardState = CentreonDuration::toString($valueLastHardStateTimestamp) . ' ago';
} else {
$valueLastHardState = 'N/A';
}
$data[$row['host_id']]['last_hard_state_change'] = $valueLastHardState;
// check_attempt
$valueCheckAttempt = "{$row['check_attempt']}/{$row['max_check_attempts']} ({$aStateType[$row['state_type']]})";
$data[$row['host_id']]['check_attempt'] = $valueCheckAttempt;
// state
$valueState = $row['state'];
$data[$row['host_id']]['status'] = $valueState;
$data[$row['host_id']]['color'] = $stateColors[$valueState];
$data[$row['host_id']]['state'] = $stateLabels[$valueState];
// output
$data[$row['host_id']]['output'] = substr($row['output'], 0, $outputLength);
$resourceController = $kernel->getContainer()->get(MonitoringResourceController::class);
$data[$row['host_id']]['details_uri'] = $useDeprecatedPages
? '../../main.php?p=20202&o=hd&host_name=' . $row['host_name']
: $resourceController->buildHostDetailsUri($row['host_id']);
// action_url
$valueActionUrl = $row['action_url'];
if (! empty($valueActionUrl)) {
if (preg_match('#^\./(.+)#', $valueActionUrl, $matches)) {
$valueActionUrl = '../../' . $matches[1];
} elseif (! preg_match($allowedProtocolsRegex, $valueActionUrl)) {
$valueActionUrl = '//' . $valueActionUrl;
}
$valueActionUrl = CentreonUtils::escapeSecure(
$hostObj->replaceMacroInString($row['host_name'], $valueActionUrl)
);
$data[$row['host_id']]['action_url'] = $valueActionUrl;
}
// notes_url
$valueNotesUrl = $row['notes_url'];
if (! empty($valueNotesUrl)) {
if (preg_match('#^\./(.+)#', $valueNotesUrl, $matches)) {
$valueNotesUrl = '../../' . $matches[1];
} elseif (! preg_match($allowedProtocolsRegex, $valueNotesUrl)) {
$valueNotesUrl = '//' . $valueNotesUrl;
}
$valueNotesUrl = CentreonUtils::escapeSecure($hostObj->replaceMacroInString(
$row['host_name'],
$valueNotesUrl
));
$data[$row['host_id']]['notes_url'] = $valueNotesUrl;
}
// criticality
$valueCriticality = $row['criticality'];
if ($valueCriticality != '') {
$critData = $criticality->getData($row['criticality_id']);
$valueCriticality = "<img src='../../img/media/" . $media->getFilename($critData['icon_id'])
. "' title='" . $critData['hc_name'] . "' width='16' height='16'>";
$data[$row['host_id']]['criticality'] = $valueCriticality;
}
if (isset($preferences['display_last_comment']) && $preferences['display_last_comment']) {
try {
$baseQuery = <<<'SQL'
SELECT data FROM comments where host_id = :hostId
AND service_id = 0 ORDER BY entry_time DESC LIMIT 1
SQL;
$res2 = $realtimeDatabase->prepare($baseQuery);
$res2->bindValue(':hostId', $row['host_id'], PDO::PARAM_INT);
$res2->execute();
$data[$row['host_id']]['comment'] = ($row2 = $res2->fetch()) ? substr($row2['data'], 0, $commentLength) : '-';
} catch (PDOException $e) {
CentreonLog::create()->error(
CentreonLog::TYPE_SQL,
'Error while getting data from comments for the host monitoring custom view',
['pdo_info' => $e->errorInfo, 'host_id' => $row['host_id'] ?? null],
$e
);
throw $e;
}
}
$data[$row['host_id']]['encoded_host_name'] = urlencode($data[$row['host_id']]['host_name']);
$class = null;
if ($row['scheduled_downtime_depth'] > 0) {
$class = 'line_downtime';
} elseif ($row['state'] == 1) {
$class = $row['acknowledged'] == 1 ? 'line_ack' : 'list_down';
} elseif ($row['acknowledged'] == 1) {
$class = 'line_ack';
}
$data[$row['host_id']]['class_tr'] = $class;
}
$aColorHost = [
0 => 'host_up',
1 => 'host_down',
2 => 'host_unreachable',
4 => 'host_pending',
];
$autoRefresh = (isset($preferences['refresh_interval']) && (int) $preferences['refresh_interval'] > 0)
? (int) $preferences['refresh_interval']
: 30;
$template->assign('widgetId', $widgetId);
$template->assign('autoRefresh', $autoRefresh);
$template->assign('preferences', $preferences);
$template->assign('page', $page);
$template->assign('dataJS', count($data));
$template->assign('nbRows', $nbRows);
$template->assign('aColorHost', $aColorHost);
$template->assign('preferences', $preferences);
$template->assign('data', $data);
$template->assign('broker', 'broker');
$template->assign('title_graph', _('See Graphs of this host'));
$template->assign('title_flapping', _('Host is flapping'));
$bMoreViews = 0;
if ($preferences['more_views']) {
$bMoreViews = $preferences['more_views'];
}
$template->assign('more_views', $bMoreViews);
try {
$template->display('table.ihtml');
} catch (Exception $e) {
$logger->error(
'Error while displaying the host monitoring custom view',
[
'file' => $e->getFile(),
'line' => $e->getLine(),
'exception_type' => $e::class,
'exception_message' => $e->getMessage(),
]
);
throw $e;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/widgets/host-monitoring/src/DB-Func.php | centreon/www/widgets/host-monitoring/src/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 getColors($db): array
{
return [0 => '#88b917', 1 => '#e00b3d', 2 => '#82CFD8', 4 => '#2ad1d4'];
}
function getLabels(): array
{
return [0 => 'Up', 1 => 'Down', 2 => 'Unreachable', 4 => 'Pending'];
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/HTML_QuickForm_checkbox_Custom.php | centreon/www/lib/HTML/QuickForm/HTML_QuickForm_checkbox_Custom.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
*
*/
class HTML_QuickForm_checkbox_Custom extends HTML_QuickForm_checkbox
{
/**
* @return string
*/
public function toHtml()
{
if ($this->_flagFrozen) {
$label = $this->_text;
} elseif (empty($this->_text)) {
$label = '<label class="empty-label" for="' . $this->getAttribute('id') . '"/>' . $this->_text . '</label>';
} else {
$label = '<label for="' . $this->getAttribute('id') . '">' . $this->_text . '</label>';
}
return '<div class="md-checkbox md-checkbox-inline">' . HTML_QuickForm_input::toHtml() . $label . '</div>';
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/HTML_QuickForm_radio_Custom.php | centreon/www/lib/HTML/QuickForm/HTML_QuickForm_radio_Custom.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
*
*/
class HTML_QuickForm_radio_Custom extends HTML_QuickForm_radio
{
/**
* @return string
*/
public function toHtml()
{
return '<div class="md-radio md-radio-inline">' . parent::toHtml() . '</div>';
}
/**
* Tries to find the element value from the values array
* This is a modified version of the original _findValue()
* Which has changes for loading the default values
*
* @param array $values
*
* @return mixed
*/
protected function _findValue(&$values)
{
if (empty($values)) {
return null;
}
$elementName = $this->getName();
if (isset($values[$elementName])) {
return $values[$elementName];
}
if (strpos($elementName, '[')) {
$myVar = "['" . str_replace(
['\\', '\'', ']', '['],
['\\\\', '\\\'', '', "']['"],
$elementName
) . "']";
// patch for centreon
if (preg_match('/\[(.+)\]$/', $elementName, $matches)) {
if (isset($values[$matches[1]]) && ! isset($values[$matches[1]][$matches[1]])) {
return $values[$matches[1]];
}
}
// end of patch
return eval("return (isset(\$values{$myVar})) ? \$values{$myVar} : null;");
}
return null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/HTML_QuickFormCustom.php | centreon/www/lib/HTML/QuickForm/HTML_QuickFormCustom.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
*
*/
class HTML_QuickFormCustom extends HTML_QuickForm
{
/** @var bool */
public $_tokenValidated = false;
/**
* Class constructor
* @param string $formName form's name
* @param string $method (optional)Form's method defaults to 'POST'
* @param string $action (optional)Form's action
* @param string $target (optional)Form's target defaults to '_self'
* @param mixed $attributes (optional)Extra attributes for <form> tag
* @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
*/
public function __construct($formName = '', $method = 'post', $action = '', $target = '', $attributes = null, $trackSubmit = false)
{
parent::__construct($formName, $method, $action, $target, $attributes, $trackSubmit);
$this->addFormRule([$this, 'checkSecurityToken']);
$this->loadCustomElementsInGlobal();
}
/**
* Accepts a renderer
*
* @param object An HTML_QuickForm_Renderer object
* @param mixed $renderer
*/
public function accept(&$renderer): void
{
$this->createSecurityToken();
parent::accept($renderer);
}
/**
* Creates a new form element of the given type.
*
* This method accepts variable number of parameters, their
* meaning and count depending on $elementType
*
* @param string $elementType type of element to add (text, textarea, file...)
* @throws HTML_QuickForm_Error
* @return HTML_QuickForm_Element
*/
public function &createElement($elementType)
{
if ($elementType == 'radio') { // If element is radio we'll load our custom class type
$elementType = 'radio_custom';
} elseif ($elementType === 'checkbox') {
$elementType = 'checkbox_custom';
}
$parentMethod = [get_parent_class($this), __FUNCTION__];
$arguments = array_slice(func_get_args(), 1); // Get all arguments except the first one
array_unshift($arguments, $elementType); // Add the modified element type name
return call_user_func_array($parentMethod, $arguments);
}
/**
* Create the CSRF Token to be set in every form using QuickForm
*/
public function createSecurityToken(): void
{
if (! $this->elementExists('centreon_token')) {
$token = bin2hex(openssl_random_pseudo_bytes(16));
if (! isset($_SESSION['x-centreon-token']) || ! is_array($_SESSION['x-centreon-token'])) {
$_SESSION['x-centreon-token'] = [];
$_SESSION['x-centreon-token-generated-at'] = [];
}
$_SESSION['x-centreon-token'][] = $token;
$_SESSION['x-centreon-token-generated-at'][(string) $token] = time();
$myTokenElement = $this->addElement('hidden', 'centreon_token');
$myTokenElement->setValue($token);
}
}
/**
* Check if the CSRF Token is still valid
*
* @param array $submittedValues
* @return bool
*/
public function checkSecurityToken($submittedValues)
{
$success = false;
if ($this->_tokenValidated) {
$success = true;
} elseif (isset($submittedValues['centreon_token'])
&& in_array($submittedValues['centreon_token'], $_SESSION['x-centreon-token'])) {
$elapsedTime
= time() - $_SESSION['x-centreon-token-generated-at'][(string) $submittedValues['centreon_token']];
if ($elapsedTime < (15 * 60)) {
$key = array_search((string) $submittedValues['centreon_token'], $_SESSION['x-centreon-token']);
unset($_SESSION['x-centreon-token'][$key], $_SESSION['x-centreon-token-generated-at'][(string) $submittedValues['centreon_token']]);
$success = true;
$this->_tokenValidated = true;
}
}
if ($success) {
$error = true;
} else {
$error = ['centreon_token' => 'The Token is invalid'];
echo "<div class='msg' align='center'>"
. _('The form has not been submitted since 15 minutes. Please retry to resubmit')
. "<a href='' OnLoad = windows.location(); alt='reload'> " . _('here') . '</a></div>';
}
$this->purgeToken();
return $error;
}
/**
* Empty all elapsed Token stored
*/
public function purgeToken(): void
{
foreach ($_SESSION['x-centreon-token-generated-at'] as $key => $value) {
$elapsedTime = time() - $value;
if ($elapsedTime > (15 * 60)) {
$tokenKey = array_search((string) $key, $_SESSION['x-centreon-token']);
unset($_SESSION['x-centreon-token'][$tokenKey], $_SESSION['x-centreon-token-generated-at'][(string) $key]);
}
}
}
/**
* Adds a validation rule for the given field
*
* If the element is in fact a group, it will be considered as a whole.
* To validate grouped elements as separated entities,
* use addGroupRule instead of addRule.
*
* @param string|string[] $element Form element name
* @param string $message Message to display for invalid data
* @param string $type Rule type, use getRegisteredRules() to get types
* @param string $format (optional)Required for extra rule data
* @param string $validation (optional)Where to perform validation: "server", "client"
* @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
* @param bool $force Force the rule to be applied, even if the target form element does not exist
* @throws HTML_QuickForm_Error
*/
public function addRule($element, $message, $type, $format = null, $validation = 'server', $reset = false, $force = false): void
{
if (! $force) {
if (! is_array($element) && ! $this->elementExists($element)) {
trigger_error("Element '{$element}' does not exist");
return;
}
if (is_array($element)) {
foreach ($element as $el) {
if (! $this->elementExists($el)) {
trigger_error("Element '{$el}' does not exist");
return;
}
}
}
}
if (false === ($newName = $this->isRuleRegistered($type, true))) {
throw new HTML_QuickForm_Error("Rule '{$type}' is not registered", QUICKFORM_INVALID_RULE);
}
if (is_string($newName)) {
$type = $newName;
}
if (is_array($element)) {
$dependent = $element;
$element = array_shift($dependent);
} else {
$dependent = null;
}
if ($type == 'required' || $type == 'uploadedfile') {
$this->_required[] = $element;
}
if (! isset($this->_rules[$element])) {
$this->_rules[$element] = [];
}
if ($validation == 'client') {
$this->updateAttributes(['onsubmit' => 'try { var myValidator = validate_' . $this->_attributes['id'] . '; } catch(e) { return true; } return myValidator(this);']);
}
$this->_rules[$element][] = ['type' => $type, 'format' => $format, 'message' => $message, 'validation' => $validation, 'reset' => $reset, 'dependent' => $dependent];
}
/**
* Applies a data filter for the given field(s)
*
* @param mixed $element Form element name or array of such names
* @param mixed $filter Callback, either function name or array(&$object, 'method')
* @throws HTML_QuickForm_Error
*/
public function applyFilter($element, $filter): void
{
if (! is_callable($filter)) {
trigger_error("Callback function '{$filter}' does not exist");
}
if ($element == '__ALL__') {
$this->_submitValues = $this->_recursiveFilter($filter, $this->_submitValues);
} else {
if (! is_array($element)) {
$element = [$element];
}
foreach ($element as $elName) {
$value = $this->getSubmitValue($elName);
if ($value !== null) {
if (! str_contains($elName, '[')) {
$this->_submitValues[$elName] = $this->_recursiveFilter($filter, $value);
} else {
$idx = "['" . str_replace(
['\\', '\'', ']', '['],
['\\\\', '\\\'', '', "']['"],
$elName
) . "']";
eval("\$this->_submitValues{$idx} = \$this->_recursiveFilter(\$filter, \$value);");
}
}
}
}
}
/**
* Add additional custom element types to $GLOBALS
*/
private function loadCustomElementsInGlobal(): void
{
// Add custom radio element type which will load our own radio HTML class
if (! isset($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']['radio_custom'])) {
$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']['radio_custom'] = 'HTML_QuickForm_radio_Custom';
}
// Add custom checkbox element type which will load our own checkbox HTML class
if (! isset($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']['checkbox_custom'])) {
$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']['checkbox'] = 'HTML_QuickForm_checkbox_Custom';
$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']['checkbox_custom'] = 'HTML_QuickForm_checkbox_Custom';
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/advmultiselect.php | centreon/www/lib/HTML/QuickForm/advmultiselect.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
*
*/
/**
* Basic error codes
*
* @var int
* @since 1.5.0
*/
define('HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT', 1);
/**
* Element for HTML_QuickForm that emulate a multi-select.
*
* The HTML_QuickForm_advmultiselect package adds an element to the
* HTML_QuickForm package that is two select boxes next to each other
* emulating a multi-select.
*
* @category HTML
* @package HTML_QuickForm_advmultiselect
* @author Laurent Laville <pear@laurent-laville.org>
* @copyright 2005-2009 Laurent Laville
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @version Release: 1.5.1
* @see http://pear.php.net/package/HTML_QuickForm_advmultiselect
* @since Class available since Release 0.4.0
*/
class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select
{
/**
* Prefix function name in javascript move selections
*
* @var string
* @since 0.4.0
*/
public $_jsPrefix;
/**
* Postfix function name in javascript move selections
*
* @var string
* @since 0.4.0
*/
public $_jsPostfix;
/**
* Associative array of the multi select container attributes
*
* @var array
* @since 0.4.0
*/
public $_tableAttributes;
/**
* Associative array of the add button attributes
*
* @var array
* @since 0.4.0
*/
public $_addButtonAttributes;
/**
* Associative array of the remove button attributes
*
* @var array
* @since 0.4.0
*/
public $_removeButtonAttributes;
/**
* Associative array of the select all button attributes
*
* @var array
* @since 1.1.0
*/
public $_allButtonAttributes;
/**
* Associative array of the select none button attributes
*
* @var array
* @since 1.1.0
*/
public $_noneButtonAttributes;
/**
* Associative array of the toggle selection button attributes
*
* @var array
* @since 1.1.0
*/
public $_toggleButtonAttributes;
/**
* Associative array of the move up button attributes
*
* @var array
* @since 0.5.0
*/
public $_upButtonAttributes;
/**
* Associative array of the move up button attributes
*
* @var array
* @since 0.5.0
*/
public $_downButtonAttributes;
/**
* Associative array of the move top button attributes
*
* @var array
* @since 1.5.0
*/
public $_topButtonAttributes;
/**
* Associative array of the move bottom button attributes
*
* @var array
* @since 1.5.0
*/
public $_bottomButtonAttributes;
/**
* Defines if both list (unselected, selected) will have their elements be
* arranged from lowest to highest (or reverse)
* depending on comparaison function.
*
* SORT_ASC is used to sort in ascending order
* SORT_DESC is used to sort in descending order
*
* @var string ('none' == false, 'asc' == SORT_ASC, 'desc' == SORT_DESC)
* @since 0.5.0
*/
public $_sort;
/**
* Associative array of the unselected item box attributes
*
* @var array
* @since 0.4.0
*/
public $_attributesUnselected;
/**
* Associative array of the selected item box attributes
*
* @var array
* @since 0.4.0
*/
public $_attributesSelected;
/**
* Associative array of the internal hidden box attributes
*
* @var array
* @since 0.4.0
*/
public $_attributesHidden;
/**
* Default Element template string
*
* @var string
* @since 0.4.0
*/
public $_elementTemplate;
/**
* Default Element stylesheet string
*
* @var string
* @since 0.4.0
*/
public $_elementCSS = '
#qfams_{id} {
font: 13.3px sans-serif;
background-color: #fff;
overflow: auto;
height: 14.3em;
width: 12em;
border-left: 1px solid #404040;
border-top: 1px solid #404040;
border-bottom: 1px solid #d4d0c8;
border-right: 1px solid #d4d0c8;
}
#qfams_{id} label {
padding-right: 3px;
display: block;
}
';
/**
* Class constructor
*
* Class constructors :
* Zend Engine 1 uses HTML_QuickForm_advmultiselect, while
* Zend Engine 2 uses __construct
*
* @param string $elementName Dual Select name attribute
* @param mixed $elementLabel Label(s) for the select boxes
* @param mixed $options Data to be used to populate options
* @param mixed $attributes Either a typical HTML attribute string or
* an associative array
* @param int $sort Either SORT_ASC for auto ascending arrange,
* SORT_DESC for auto descending arrange, or
* NULL for no sort (append at end: default)
*
* @return void
* @since version 0.4.0 (2005-06-25)
*/
public function __construct(
$elementName = null,
$elementLabel = null,
$options = null,
$attributes = null,
$sort = null,
) {
$opts = $options;
$options = null; // prevent to use the default select element load options
parent::__construct($elementName, $elementLabel, $options, $attributes);
// allow to load options at once and take care of fancy attributes
$this->load($opts);
// add multiple selection attribute by default if missing
$this->updateAttributes(['multiple' => 'multiple']);
if (is_null($this->getAttribute('size'))) {
// default size is ten item on each select box (left and right)
$this->updateAttributes(['size' => 10]);
}
if (is_null($this->getAttribute('style'))) {
// default width of each select box
$this->updateAttributes(['style' => 'width:100px;']);
}
$this->_tableAttributes = $this->getAttribute('class');
if (is_null($this->_tableAttributes)) {
// default table layout
$attr = ['border' => '0', 'cellpadding' => '10', 'cellspacing' => '0'];
} else {
$attr = ['class' => $this->_tableAttributes];
$this->_removeAttr('class', $this->_attributes);
}
$this->_tableAttributes = $this->_getAttrString($attr);
// set default add button attributes
$this->setButtonAttributes('add');
// set default remove button attributes
$this->setButtonAttributes('remove');
// set default selectall button attributes
$this->setButtonAttributes('all');
// set default selectnone button attributes
$this->setButtonAttributes('none');
// set default toggle selection button attributes
$this->setButtonAttributes('toggle');
// set default move up button attributes
$this->setButtonAttributes('moveup');
// set default move up button attributes
$this->setButtonAttributes('movedown');
// set default move top button attributes
$this->setButtonAttributes('movetop');
// set default move bottom button attributes
$this->setButtonAttributes('movebottom');
// defines javascript functions names
$this->_jsPrefix = 'QFAMS.';
$this->_jsPostfix = 'moveSelection';
// set select boxes sort order (none by default)
if (! isset($sort)) {
$sort = false;
}
if ($sort === SORT_ASC) {
$this->_sort = 'asc';
} elseif ($sort === SORT_DESC) {
$this->_sort = 'desc';
} else {
$this->_sort = 'none';
}
// set the default advmultiselect element template (with javascript embedded)
$this->setElementTemplate();
}
/**
* Sets the button attributes
*
* In <b>custom example 1</b>, the <i>add</i> and <i>remove</i> buttons
* have look set by the css class <i>inputCommand</i>.
*
* In <b>custom example 2</b>, the basic text <i>add</i> and <i>remove</i>
* buttons are now replaced by images.
*
* In <b>custom example 5</b>, we have ability to sort the selection list
* (on right side) by :
* <pre>
* - <b>user-end</b>: with <i>Up</i> and <i>Down</i> buttons
* - <b>programming</b>: with the QF element constructor $sort option
* </pre>
*
* @param string $button Button identifier, either 'add', 'remove',
* 'all', 'none', 'toggle',
* 'movetop', 'movebottom'
* 'moveup' or 'movedown'
* @param mixed $attributes (optional) Either a typical HTML attribute string
* or an associative array
*
* @throws PEAR_Error $button argument
* is not a string, or not in range
* (add, remove, all, none, toggle,
* movetop, movebottom, moveup, movedown)
* @return void
* @since version 0.4.0 (2005-06-25)
*
* @example examples/qfams_custom_5.php
* Custom example 5: source code
* @see http://www.laurent-laville.org/img/qfams/screenshot/custom5.png
* Custom example 5: screenshot
*
* @example examples/qfams_custom_2.php
* Custom example 2: source code
* @see http://www.laurent-laville.org/img/qfams/screenshot/custom2.png
* Custom example 2: screenshot
*
* @example examples/qfams_custom_1.php
* Custom example 1: source code
* @see http://www.laurent-laville.org/img/qfams/screenshot/custom1.png
* Custom example 1: screenshot
*/
public function setButtonAttributes($button, $attributes = null)
{
if (! is_string($button)) {
return PEAR::throwError(
'Argument 1 of HTML_QuickForm_advmultiselect::'
. 'setButtonAttributes is not a string',
HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT,
['level' => 'exception']
);
}
switch ($button) {
case 'add':
if (is_null($attributes)) {
$this->_addButtonAttributes
= ['name' => 'add', 'value' => ' >> ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_addButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'remove':
if (is_null($attributes)) {
$this->_removeButtonAttributes
= ['name' => 'remove', 'value' => ' << ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_removeButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'all':
if (is_null($attributes)) {
$this->_allButtonAttributes
= ['name' => 'all', 'value' => ' Select All ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_allButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'none':
if (is_null($attributes)) {
$this->_noneButtonAttributes
= ['name' => 'none', 'value' => ' Select None ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_noneButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'toggle':
if (is_null($attributes)) {
$this->_toggleButtonAttributes
= ['name' => 'toggle', 'value' => ' Toggle Selection ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_toggleButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'moveup':
if (is_null($attributes)) {
$this->_upButtonAttributes
= ['name' => 'up', 'value' => ' Up ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_upButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'movedown':
if (is_null($attributes)) {
$this->_downButtonAttributes
= ['name' => 'down', 'value' => ' Down ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_downButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'movetop':
if (is_null($attributes)) {
$this->_topButtonAttributes
= ['name' => 'top', 'value' => ' Top ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_topButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
case 'movebottom':
if (is_null($attributes)) {
$this->_bottomButtonAttributes
= ['name' => 'bottom', 'value' => ' Bottom ', 'type' => 'button'];
} else {
$this->_updateAttrArray(
$this->_bottomButtonAttributes,
$this->_parseAttributes($attributes)
);
}
break;
default:
return PEAR::throwError(
'Argument 1 of HTML_QuickForm_advmultiselect::'
. 'setButtonAttributes has unexpected value',
HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT,
['level' => 'error']
);
}
}
/**
* Sets element template
*
* @param string $html (optional) The HTML surrounding select boxes and buttons
* @param string $js (optional) if we need to include qfams javascript handler
*
* @return string
* @since version 0.4.0 (2005-06-25)
*/
public function setElementTemplate($html = null, $js = true)
{
$oldTemplate = $this->_elementTemplate;
if (isset($html) && is_string($html)) {
$this->_elementTemplate = $html;
} else {
$this->_elementTemplate = '
{javascript}
<table{class}>
<!-- BEGIN label_2 --><tr><th>{label_2}</th><!-- END label_2 -->
<!-- BEGIN label_3 --><th> </th><th>{label_3}</th></tr><!-- END label_3 -->
<tr>
<td valign="top">{unselected}</td>
<td align="center">{add}{remove}</td>
<td valign="top">{selected}</td>
</tr>
</table>
';
}
if ($js == false) {
$this->_elementTemplate = str_replace(
'{javascript}',
'',
$this->_elementTemplate
);
}
return $oldTemplate;
}
/**
* Gets default element stylesheet for a single multi-select shape render
*
* In <b>custom example 4</b>, the template defined allows
* a single multi-select checkboxes shape. Useful when javascript is disabled
* (or when browser is not js compliant). In our example, no need to add
* javascript code, but css is mandatory.
*
* @param bool $raw (optional) html output with style tags or just raw data
*
* @return string
* @since version 0.4.0 (2005-06-25)
*
* @example qfams_custom_4.php
* Custom example 4: source code
* @see http://www.laurent-laville.org/img/qfams/screenshot/custom4.png
* Custom example 4: screenshot
*/
public function getElementCss($raw = true)
{
$id = $this->getAttribute('name');
$css = str_replace('{id}', $id, $this->_elementCSS);
if ($raw !== true) {
$css = '<style type="text/css">' . PHP_EOL
. '<!--' . $css . ' -->' . PHP_EOL
. '</style>';
}
return $css;
}
/**
* Returns the HTML generated for the advanced mutliple select component
*
* @return string
* @since version 0.4.0 (2005-06-25)
*/
public function toHtml()
{
if ($this->_flagFrozen) {
return $this->getFrozenHtml();
}
$tabs = $this->_getTabs();
$tab = $this->_getTab();
$selectId = $this->getName();
$selectName = $this->getName() . '[]';
$selectNameFrom = $this->getName() . '-f[]';
$selectNameTo = $this->getName() . '-t[]';
$selected_count = 0;
// placeholder {unselected} existence determines if we will render
if (! str_contains($this->_elementTemplate, '{unselected}')) {
// ... a single multi-select with checkboxes
$this->_jsPostfix = 'editSelection';
$id = $this->getAttribute('name');
$strHtmlSelected = $tab . '<div id="qfams_' . $id . '">' . PHP_EOL;
$unselected_count = count($this->_options);
$checkbox_id_suffix = 0;
foreach ($this->_options as $option) {
$_labelAttributes
= ['style', 'class', 'onmouseover', 'onmouseout'];
$labelAttributes = [];
foreach ($_labelAttributes as $attr) {
if (isset($option['attr'][$attr])) {
$labelAttributes[$attr] = $option['attr'][$attr];
unset($option['attr'][$attr]);
}
}
if (is_array($this->_values)
&& in_array((string) $option['attr']['value'], $this->_values)) {
// The items is *selected*
$checked = ' checked="checked"';
$selected_count++;
} else {
// The item is *unselected* so we want to put it
$checked = '';
}
$checkbox_id_suffix++;
$strHtmlSelected .= $tab
. '<label'
. $this->_getAttrString($labelAttributes) . '>'
. '<input type="checkbox"'
. ' id="' . $selectId . $checkbox_id_suffix . '"'
. ' name="' . $selectName . '"'
. $checked
. $this->_getAttrString($option['attr'])
. ' />' . $option['text'] . '</label>'
. PHP_EOL;
}
$strHtmlSelected .= $tab . '</div>' . PHP_EOL;
$strHtmlHidden = '';
$strHtmlUnselected = '';
$strHtmlAdd = '';
$strHtmlRemove = '';
// build the select all button with all its attributes
$jsName = $this->_jsPrefix . $this->_jsPostfix;
$attributes = ['onclick' => $jsName
. "('" . $selectId . "', 1);"];
$this->_allButtonAttributes
= array_merge($this->_allButtonAttributes, $attributes);
$attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
$strHtmlAll = "<input{$attrStrAll} />" . PHP_EOL;
// build the select none button with all its attributes
$attributes = ['onclick' => $jsName
. "('" . $selectId . "', 0);"];
$this->_noneButtonAttributes
= array_merge($this->_noneButtonAttributes, $attributes);
$attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
$strHtmlNone = "<input{$attrStrNone} />" . PHP_EOL;
// build the toggle selection button with all its attributes
$attributes = ['onclick' => $jsName
. "('" . $selectId . "', 2);"];
$this->_toggleButtonAttributes
= array_merge(
$this->_toggleButtonAttributes,
$attributes
);
$attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes);
$strHtmlToggle = "<input{$attrStrToggle} />" . PHP_EOL;
$strHtmlMoveUp = '';
$strHtmlMoveDown = '';
$strHtmlMoveTop = '';
$strHtmlMoveBottom = '';
// default selection counters
$strHtmlSelectedCount = $selected_count . '/' . $unselected_count;
} else {
// ... or a dual multi-select
$this->_jsPostfix = 'moveSelection';
$jsName = $this->_jsPrefix . $this->_jsPostfix;
// set name of Select From Box
$this->_attributesUnselected
= ['id' => $selectId . '-f', 'name' => $selectNameFrom, 'ondblclick' => $jsName
. "('{$selectId}', "
. "this.form.elements['" . $selectNameFrom . "'], "
. "this.form.elements['" . $selectNameTo . "'], "
. "this.form.elements['" . $selectName . "'], "
. "'add', '{$this->_sort}')"];
$this->_attributesUnselected
= array_merge($this->_attributes, $this->_attributesUnselected);
$attrUnselected = $this->_getAttrString($this->_attributesUnselected);
// set name of Select To Box
$this->_attributesSelected
= ['id' => $selectId . '-t', 'name' => $selectNameTo, 'ondblclick' => $jsName
. "('{$selectId}', "
. "this.form.elements['" . $selectNameFrom . "'], "
. "this.form.elements['" . $selectNameTo . "'], "
. "this.form.elements['" . $selectName . "'], "
. "'remove', '{$this->_sort}')"];
$this->_attributesSelected
= array_merge($this->_attributes, $this->_attributesSelected);
$attrSelected = $this->_getAttrString($this->_attributesSelected);
// set name of Select hidden Box
$this->_attributesHidden
= ['name' => $selectName, 'style' => 'overflow: hidden; visibility: hidden; '
. 'width: 1px; height: 0;'];
$this->_attributesHidden
= array_merge($this->_attributes, $this->_attributesHidden);
$attrHidden = $this->_getAttrString($this->_attributesHidden);
// prepare option tables to be displayed as in POST order
$append = is_array($this->_values) ? count($this->_values) : 0;
$arrHtmlSelected = $append > 0 ? array_fill(0, $append, ' ') : [];
$options = count($this->_options);
$arrHtmlUnselected = [];
if ($options > 0) {
$arrHtmlHidden = array_fill(0, $options, ' ');
foreach ($this->_options as $option) {
if (is_array($this->_values)
&& in_array(
(string) $option['attr']['value'],
$this->_values
)) {
// Get the post order
$key = array_search(
$option['attr']['value'],
$this->_values
);
/** The items is *selected* so we want to put it
* in the 'selected' multi-select */
$arrHtmlSelected[$key] = $option;
/** Add it to the 'hidden' multi-select
* and set it as 'selected' */
if (isset($option['attr']['disabled'])) {
unset($option['attr']['disabled']);
}
$option['attr']['selected'] = 'selected';
$arrHtmlHidden[$key] = $option;
} else {
/** The item is *unselected* so we want to put it
* in the 'unselected' multi-select */
$arrHtmlUnselected[] = $option;
// Add it to the hidden multi-select as 'unselected'
$arrHtmlHidden[$append] = $option;
$append++;
}
}
} else {
$arrHtmlHidden = [];
}
// The 'unselected' multi-select which appears on the left
$unselected_count = count($arrHtmlUnselected);
if ($unselected_count == 0) {
$this->_attributesUnselected['disabled'] = 'disabled';
$this->_attributesUnselected
= array_merge($this->_attributes, $this->_attributesUnselected);
$attrUnselected = $this->_getAttrString($this->_attributesUnselected);
}
$strHtmlUnselected = "<select{$attrUnselected}>" . PHP_EOL;
if ($unselected_count > 0) {
foreach ($arrHtmlUnselected as $data) {
$strHtmlUnselected
.= $tabs . $tab
. '<option' . $this->_getAttrString($data['attr']) . '>'
. $data['text'] . '</option>' . PHP_EOL;
}
} else {
$strHtmlUnselected .= '<option value=""> </option>';
}
$strHtmlUnselected .= '</select>';
// The 'selected' multi-select which appears on the right
$selected_count = count($arrHtmlSelected);
if ($selected_count == 0) {
$this->_attributesSelected['disabled'] = 'disabled';
$this->_attributesSelected
= array_merge($this->_attributes, $this->_attributesSelected);
$attrSelected = $this->_getAttrString($this->_attributesSelected);
}
$strHtmlSelected = "<select{$attrSelected}>" . PHP_EOL;
if ($selected_count > 0) {
foreach ($arrHtmlSelected as $data) {
if (! isset($data['attr']) || ! isset($data['text'])) {
continue;
}
$strHtmlSelected .= $tabs . $tab
. '<option' . $this->_getAttrString($data['attr']) . '>'
. $data['text'] . '</option>' . PHP_EOL;
}
} else {
$strHtmlSelected .= '<option value=""> </option>';
}
$strHtmlSelected .= '</select>';
// The 'hidden' multi-select
$strHtmlHidden = "<select{$attrHidden}>" . PHP_EOL;
if ($arrHtmlHidden !== []) {
foreach ($arrHtmlHidden as $data) {
if (! isset($data['attr']) || ! isset($data['text'])) {
continue;
}
$strHtmlHidden .= $tabs . $tab
. '<option' . $this->_getAttrString($data['attr']) . '>'
. $data['text'] . '</option>' . PHP_EOL;
}
}
$strHtmlHidden .= '</select>';
// build the remove button with all its attributes
$attributes
= ['onclick' => $jsName
. "('{$selectId}', "
. "this.form.elements['" . $selectNameFrom . "'], "
. "this.form.elements['" . $selectNameTo . "'], "
. "this.form.elements['" . $selectName . "'], "
. "'remove', '{$this->_sort}'); return false;"];
$this->_removeButtonAttributes
= array_merge($this->_removeButtonAttributes, $attributes);
$attrStrRemove = $this->_getAttrString($this->_removeButtonAttributes);
$strHtmlRemove = "<input{$attrStrRemove} />" . PHP_EOL;
// build the add button with all its attributes
$attributes
= ['onclick' => $jsName
. "('{$selectId}', "
. "this.form.elements['" . $selectNameFrom . "'], "
. "this.form.elements['" . $selectNameTo . "'], "
. "this.form.elements['" . $selectName . "'], "
. "'add', '{$this->_sort}'); return false;"];
$this->_addButtonAttributes
= array_merge($this->_addButtonAttributes, $attributes);
$attrStrAdd = $this->_getAttrString($this->_addButtonAttributes);
$strHtmlAdd = "<input{$attrStrAdd} />" . PHP_EOL;
// build the select all button with all its attributes
$attributes
= ['onclick' => $jsName
. "('{$selectId}', "
. "this.form.elements['" . $selectNameFrom . "'], "
. "this.form.elements['" . $selectNameTo . "'], "
. "this.form.elements['" . $selectName . "'], "
. "'all', '{$this->_sort}'); return false;"];
$this->_allButtonAttributes
= array_merge($this->_allButtonAttributes, $attributes);
$attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
$strHtmlAll = "<input{$attrStrAll} />" . PHP_EOL;
// build the select none button with all its attributes
$attributes
= ['onclick' => $jsName
. "('{$selectId}', "
. "this.form.elements['" . $selectNameFrom . "'], "
. "this.form.elements['" . $selectNameTo . "'], "
. "this.form.elements['" . $selectName . "'], "
. "'none', '{$this->_sort}'); return false;"];
$this->_noneButtonAttributes
= array_merge($this->_noneButtonAttributes, $attributes);
$attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
$strHtmlNone = "<input{$attrStrNone} />" . PHP_EOL;
// build the toggle button with all its attributes
$attributes
= ['onclick' => $jsName
. "('{$selectId}', "
. "this.form.elements['" . $selectNameFrom . "'], "
. "this.form.elements['" . $selectNameTo . "'], "
. "this.form.elements['" . $selectName . "'], "
. "'toggle', '{$this->_sort}'); return false;"];
$this->_toggleButtonAttributes
= array_merge($this->_toggleButtonAttributes, $attributes);
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/selectoptgroup.php | centreon/www/lib/HTML/QuickForm/selectoptgroup.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
*
*/
/**
* Description of select2
*
* @author Lionel Assepo <lassepo@centreon.com>
*/
class HTML_QuickForm_selectoptgroup extends HTML_QuickForm_select
{
/** @var string */
public $_elementHtmlName;
/** @var string */
public $_elementTemplate;
/** @var string */
public $_elementCSS;
/** @var string */
public $_availableDatasetRoute;
/** @var string */
public $_defaultDatasetRoute;
/** @var string */
public $_defaultDataset = null;
/** @var bool */
public $_ajaxSource = false;
/** @var bool */
public $_multiple;
/** @var string */
public $_multipleHtml = '';
/** @var string */
public $_defaultSelectedOptions = '';
/** @var string */
public $_jsCallback = '';
/** @var bool */
public $_allowClear = true;
/** @var string */
public $_linkedObject;
/** @var type */
public $_defaultDatasetOptions = [];
/** @var int The number of element in the pagination */
public $_pagination;
/** @var array */
public $realOptionsArray;
public $_memOptions = [];
/**
* @param string $elementName
* @param string $elementLabel
* @param array $options
* @param array $attributes
* @param string $sort
*/
public function __construct(
$elementName = null,
$elementLabel = null,
$options = null,
$attributes = null,
$sort = null,
) {
global $centreon;
$this->realOptionsArray = $options;
parent::__construct($elementName, $elementLabel, $options, $attributes);
$this->_elementHtmlName = $this->getName();
$this->parseCustomAttributes($attributes);
$this->_pagination = $centreon->optGen['selectPaginationSize'];
}
/**
* @param array $attributes
*/
public function parseCustomAttributes(&$attributes): void
{
// Check for
if (isset($attributes['datasourceOrigin']) && ($attributes['datasourceOrigin'] == 'ajax')) {
$this->_ajaxSource = true;
// Check for
if (isset($attributes['availableDatasetRoute'])) {
$this->_availableDatasetRoute = $attributes['availableDatasetRoute'];
}
// Check for
if (isset($attributes['defaultDatasetRoute'])) {
$this->_defaultDatasetRoute = $attributes['defaultDatasetRoute'];
}
}
if (isset($attributes['multiple']) && $attributes['multiple'] === true) {
$this->_elementHtmlName .= '[]';
$this->_multiple = true;
$this->_multipleHtml = 'multiple="multiple"';
} else {
$this->_multiple = false;
}
if (isset($attributes['allowClear']) && $attributes['allowClear'] === false) {
$this->_allowClear = false;
} elseif (isset($attributes['allowClear']) && $attributes['allowClear'] === true) {
$this->_allowClear = true;
}
if (isset($attributes['defaultDataset']) && ! is_null($attributes['defaultDataset'])) {
$this->_defaultDataset = $attributes['defaultDataset'];
}
if (isset($attributes['defaultDatasetOptions'])) {
$this->_defaultDatasetOptions = $attributes['defaultDatasetOptions'];
}
if (isset($attributes['linkedObject'])) {
$this->_linkedObject = $attributes['linkedObject'];
}
}
/**
* @param bool $raw
* @param bool $min
* @return string
*/
public function getElementJs($raw = true, $min = false)
{
$jsFile = './include/common/javascript/jquery/plugins/select2/js/';
$jsFile2 = './include/common/javascript/centreon/centreon-select2-optgroup.js';
if ($min) {
$jsFile .= 'select2.min.js';
} else {
$jsFile .= 'select2.js';
}
return '<script type="text/javascript" '
. 'src="' . $jsFile . '">'
. '</script>'
. '<script type="text/javascript" '
. 'src="' . $jsFile2 . '">'
. '</script>';
}
/**
* @return type
*/
public function getElementHtmlName()
{
return $this->_elementHtmlName;
}
/**
* @param bool $raw
* @param bool $min
* @return string
*/
public function getElementCss($raw = true, $min = false)
{
$cssFile = './include/common/javascript/jquery/plugins/select2/css/';
if ($min) {
$cssFile .= 'select2.min.js';
} else {
$cssFile .= 'select2.js';
}
return '<link href="' . $cssFile . '" rel="stylesheet" type="text/css"/>';
}
/**
* @return string
*/
public function toHtml()
{
$strHtml = '';
$readonly = '';
$strHtml .= '<select id="' . $this->getName()
. '" name="' . $this->getElementHtmlName()
. '" ' . $this->_multipleHtml . ' '
. ' style="width: 300px;" ' . $readonly . '><option></option>'
. '%%DEFAULT_SELECTED_VALUES%%'
. '</select>';
$strHtml .= $this->getJsInit();
return str_replace('%%DEFAULT_SELECTED_VALUES%%', $this->_defaultSelectedOptions, $strHtml);
}
/**
* @return string
*/
public function getJsInit()
{
$allowClear = 'true';
$additionnalJs = '';
if ($this->_allowClear === false || $this->_flagFrozen) {
$allowClear = 'false';
}
$disabled = 'false';
if ($this->_flagFrozen) {
$disabled = 'true';
}
$ajaxOption = '';
$defaultData = '';
if ($this->_ajaxSource) {
$ajaxOption = 'ajax: {
url: "' . $this->_availableDatasetRoute . '"
},';
if ($this->_defaultDatasetRoute && is_null($this->_defaultDataset)) {
$additionnalJs = $this->setDefaultAjaxDatas();
} else {
$this->setDefaultFixedDatas();
}
} else {
$defaultData = $this->setFixedDatas() . ',';
$this->setDefaultFixedDatas();
}
$additionnalJs .= ' ' . $this->_jsCallback;
return '<script>
jQuery(function () {
var $currentSelect2Object' . $this->getName()
. ' = jQuery("#' . $this->getName() . '").centreonSelect2({
allowClear: ' . $allowClear . ',
pageLimit: ' . $this->_pagination . ',
optGroup: true,
select2: {
' . $ajaxOption . '
' . $defaultData . '
placeholder: "' . $this->getLabel() . '",
disabled: ' . $disabled . '
}
});
' . $additionnalJs . '
});
</script>';
}
/**
* @return string
*/
public function setFixedDatas()
{
$datas = 'data: ';
$datas .= json_encode($this->realOptionsArray, 1);
return $datas;
}
/**
* obsolete
*/
public function setDefaultFixedDatas()
{
return true;
}
/**
* @param string $event
* @param string $callback
*/
public function addJsCallback($event, $callback): void
{
$this->_jsCallback .= ' jQuery("#' . $this->getName() . '").on("' . $event . '", function(){ '
. $callback
. ' }); ';
}
/**
* @return string
*/
public function setDefaultAjaxDatas()
{
return '$request' . $this->getName() . ' = jQuery.ajax({
url: "' . $this->_defaultDatasetRoute . '",
});
$request' . $this->getName() . '.success(function (data) {
for (var d = 0; d < data.length; d++) {
var item = data[d];
// Create the DOM option that is pre-selected by default
var option = "<option selected=\"selected\" value=\"" + item.id + "\" ";
if (item.hide === true) {
option += "hidden";
}
option += ">" + item.text + "</option>";
// Append it to the select
$currentSelect2Object' . $this->getName() . '.append(option);
}
// Update the selected options that are displayed
$currentSelect2Object' . $this->getName() . '.trigger("change",[{origin:\'select2defaultinit\'}]);
});
$request' . $this->getName() . '.error(function(data) {
});
';
}
/**
* @return string
*/
public function getFrozenHtml()
{
return '';
}
/**
* @param type $event
* @param type $arg
* @param type $caller
* @return bool
*/
public function onQuickFormEvent($event, $arg, &$caller)
{
if ($event == 'updateValue') {
$value = $this->_findValue($caller->_constantValues);
if ($value === null) {
$value = is_null($this->_defaultDataset) ? $this->_findValue($caller->_submitValues) : $this->_defaultDataset;
// Fix for bug #4465 & #5269
// XXX: should we push this to element::onQuickFormEvent()?
if ($value === null && (! $caller->isSubmitted() || ! $this->getMultiple())) {
$value = $this->_findValue($caller->_defaultValues);
}
}
if ($value !== null) {
if (! is_array($value)) {
$value = [$value];
}
$this->_defaultDataset = $value;
$this->setDefaultFixedDatas();
}
return true;
}
return parent::onQuickFormEvent($event, $arg, $caller);
}
}
if (class_exists('HTML_QuickForm')) {
(new HTML_QuickForm())->registerElementType(
'selectoptgroup',
'HTML/QuickForm/selectoptgroup.php',
'HTML_QuickForm_selectoptgroup'
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/select2.php | centreon/www/lib/HTML/QuickForm/select2.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
*
*/
/**
* Base class for form elements
*/
// require_once 'HTML/QuickForm/select.php';
/**
* Description of select2
*
* @author Lionel Assepo <lassepo@centreon.com>
*/
class HTML_QuickForm_select2 extends HTML_QuickForm_select
{
/** @var string */
public $_elementHtmlName;
/** @var string */
public $_elementTemplate;
/** @var string */
public $_elementCSS;
/** @var string */
public $_availableDatasetRoute;
/** @var string */
public $_defaultDatasetRoute;
/** @var string */
public $_defaultDataset = null;
/** @var bool */
public $_ajaxSource = false;
/** @var bool */
public $_multiple;
/** @var string */
public $_multipleHtml = '';
/** @var string */
public $_defaultSelectedOptions = '';
/** @var string */
public $_jsCallback = '';
/** @var bool */
public $_allowClear = true;
/** @var string */
public $_linkedObject;
/** @var bool */
public $_showDisabled = false;
/** @var type */
public $_defaultDatasetOptions = [];
/** @var int The number of element in the pagination */
public $_pagination;
public $_memOptions = [];
/**
* @param string $elementName
* @param string $elementLabel
* @param array $options
* @param array $attributes
* @param string $sort
*/
public function __construct(
$elementName = null,
$elementLabel = null,
$options = null,
$attributes = null,
$sort = null,
) {
global $centreon;
parent::__construct($elementName, $elementLabel, $options, $attributes);
$this->_elementHtmlName = $this->getName();
$this->parseCustomAttributes($attributes);
$this->_pagination = $centreon->optGen['selectPaginationSize'];
}
/**
* @param array $attributes
*/
public function parseCustomAttributes(&$attributes): void
{
// Check for
if (isset($attributes['datasourceOrigin']) && ($attributes['datasourceOrigin'] == 'ajax')) {
$this->_ajaxSource = true;
// Check for
if (isset($attributes['availableDatasetRoute'])) {
$this->_availableDatasetRoute = $attributes['availableDatasetRoute'];
}
// Check for
if (isset($attributes['defaultDatasetRoute'])) {
$this->_defaultDatasetRoute = $attributes['defaultDatasetRoute'];
}
}
if (isset($attributes['multiple']) && $attributes['multiple'] === true) {
$this->_elementHtmlName .= '[]';
$this->_multiple = true;
$this->_multipleHtml = 'multiple="multiple"';
} else {
$this->_multiple = false;
}
if (isset($attributes['allowClear']) && $attributes['allowClear'] === false) {
$this->_allowClear = false;
} elseif (isset($attributes['allowClear']) && $attributes['allowClear'] === true) {
$this->_allowClear = true;
}
if (isset($attributes['defaultDataset']) && ! is_null($attributes['defaultDataset'])) {
$this->_defaultDataset = $attributes['defaultDataset'];
}
if (isset($attributes['defaultDatasetOptions'])) {
$this->_defaultDatasetOptions = $attributes['defaultDatasetOptions'];
}
if (isset($attributes['linkedObject'])) {
$this->_linkedObject = $attributes['linkedObject'];
}
if (isset($attributes['showDisabled'])) {
$this->_showDisabled = $attributes['showDisabled'];
}
}
/**
* @param bool $raw
* @param bool $min
* @return string
*/
public function getElementJs($raw = true, $min = false)
{
$jsFile = './include/common/javascript/jquery/plugins/select2/js/';
$jsFile2 = './include/common/javascript/centreon/centreon-select2.js';
if ($min) {
$jsFile .= 'select2.min.js';
} else {
$jsFile .= 'select2.js';
}
return '<script type="text/javascript" '
. 'src="' . $jsFile . '">'
. '</script>'
. '<script type="text/javascript" '
. 'src="' . $jsFile2 . '">'
. '</script>';
}
/**
* @return type
*/
public function getElementHtmlName()
{
return $this->_elementHtmlName;
}
/**
* @param bool $raw
* @param bool $min
* @return string
*/
public function getElementCss($raw = true, $min = false)
{
$cssFile = './include/common/javascript/jquery/plugins/select2/css/';
if ($min) {
$cssFile .= 'select2.min.js';
} else {
$cssFile .= 'select2.js';
}
return '<link href="' . $cssFile . '" rel="stylesheet" type="text/css"/>';
}
/**
* @return string
*/
public function toHtml()
{
$strHtml = '';
$readonly = '';
$strHtml .= '<select id="' . $this->getName()
. '" name="' . $this->getElementHtmlName()
. '" data-testid="' . $this->getName()
. '" ' . $this->_multipleHtml . ' '
. ' style="width: 300px;" ' . $readonly . '><option></option>'
. '%%DEFAULT_SELECTED_VALUES%%'
. '</select>';
$strHtml .= $this->getJsInit();
return str_replace('%%DEFAULT_SELECTED_VALUES%%', $this->_defaultSelectedOptions, $strHtml);
}
/**
* @return string
*/
public function getJsInit()
{
$allowClear = 'true';
$additionnalJs = '';
if ($this->_allowClear === false || $this->_flagFrozen) {
$allowClear = 'false';
}
$disabled = 'false';
if ($this->_flagFrozen) {
$disabled = 'true';
}
$ajaxOption = '';
$defaultData = '';
$template = '';
if ($this->_ajaxSource) {
$ajaxOption = 'ajax: {
url: "' . $this->_availableDatasetRoute . '"
},';
if ($this->_defaultDatasetRoute && is_null($this->_defaultDataset)) {
$additionnalJs = $this->setDefaultAjaxDatas();
} else {
$this->setDefaultFixedDatas();
}
} else {
$defaultData = $this->setFixedDatas() . ',';
$this->setDefaultFixedDatas();
}
if ($this->_showDisabled === true) {
$template = "
templateResult: function(state){
let template = state.text;
if (state.hasOwnProperty('status') && state.status === false) {
template = jQuery('<span class=\"show-disabled\" disabled=\"" . _('disabled') . "\"></span>');
template.text(state.text);
}
return template;
},";
}
$additionnalJs .= ' ' . $this->_jsCallback;
return '<script>
jQuery(function () {
var $currentSelect2Object' . $this->getName()
. ' = jQuery("#' . $this->getName() . '").centreonSelect2({
allowClear: ' . $allowClear . ',
pageLimit: ' . $this->_pagination . ',' . $template . '
select2: {
' . $ajaxOption . '
' . $defaultData . '
placeholder: "' . $this->getLabel() . '",
disabled: ' . $disabled . '
}
});
' . $additionnalJs . '
});
</script>';
}
/**
* @return string
*/
public function setFixedDatas()
{
$datas = 'data: [';
// Set default values
$strValues = is_array($this->_values) ? array_map('strval', $this->_values) : [];
foreach ($this->_options as $option) {
if (empty($option['attr']['value'])) {
$option['attr']['value'] = -1;
}
if (! is_numeric($option['attr']['value'])) {
$option['attr']['value'] = '"' . $option['attr']['value'] . '"';
}
$datas .= '{id: ' . $option['attr']['value'] . ', text: "' . $option['text'] . '"},';
if ($strValues !== [] && in_array($option['attr']['value'], $strValues, true)) {
$option['attr']['selected'] = 'selected';
$this->_defaultSelectedOptions .= '<option' . $this->_getAttrString($option['attr']) . '>'
. $option['text'] . '</option>';
}
}
$datas .= ']';
return $datas;
}
public function setDefaultFixedDatas(): void
{
global $pearDB;
if (! is_null($this->_linkedObject)) {
require_once _CENTREON_PATH_ . '/www/class/' . $this->_linkedObject . '.class.php';
$objectFinalName = ucfirst($this->_linkedObject);
$myObject = new $objectFinalName($pearDB);
try {
$finalDataset = $myObject->getObjectForSelect2($this->_defaultDataset, $this->_defaultDatasetOptions);
} catch (Exception $e) {
echo $e->getMessage();
return;
}
foreach ($finalDataset as $dataSet) {
$currentOption = '<option selected="selected" value="'
. $dataSet['id'] . '" ';
if (isset($dataSet['hide']) && $dataSet['hide'] === true) {
$currentOption .= 'hidden';
}
$currentOption .= '>'
. $dataSet['text'] . '</option>';
if (! in_array($dataSet['id'], $this->_memOptions)) {
$this->_memOptions[] = $dataSet['id'];
$this->_defaultSelectedOptions .= $currentOption;
}
}
} elseif (! is_null($this->_defaultDataset)) {
foreach ($this->_defaultDataset as $elementName => $elementValue) {
$currentOption = '<option selected="selected" value="'
. $elementValue . '">'
. $elementName . '</option>';
if (! in_array($elementValue, $this->_memOptions)) {
$this->_memOptions[] = $elementValue;
$this->_defaultSelectedOptions .= $currentOption;
}
}
}
}
/**
* @param string $event
* @param string $callback
*/
public function addJsCallback($event, $callback): void
{
$this->_jsCallback .= ' jQuery("#' . $this->getName() . '").on("' . $event . '", function(){ '
. $callback
. ' }); ';
}
/**
* @return string
*/
public function setDefaultAjaxDatas()
{
if (preg_match('/id=$/', $this->_defaultDatasetRoute)) {
// do not fetch data if id is not set
// it happens when creating a new object
return '';
}
return '$request' . $this->getName() . ' = jQuery.ajax({
url: "' . $this->_defaultDatasetRoute . '",
success: (data) => {
let options = "";
data.map((item) => {
// Create the DOM option that is pre-selected by default
options += "<option selected=\"selected\" value=\"" + item.id + "\" ";
if (item.hide === true) {
options += "hidden";
}
options += ">" + item.text + "</option>";
})
// Append it to the select
$currentSelect2Object' . $this->getName() . '.append(options);
// Update the selected options that are displayed
$currentSelect2Object' . $this->getName() . '.trigger("change",[{origin:\'select2defaultinit\'}]);
}
});
';
}
/**
* @return string
*/
public function getFrozenHtml()
{
return '';
}
/**
* @param type $event
* @param type $arg
* @param type $caller
* @return bool
*/
public function onQuickFormEvent($event, $arg, &$caller)
{
if ($event == 'updateValue') {
$value = $this->_findValue($caller->_constantValues);
if ($value === null) {
$value = is_null($this->_defaultDataset) ? $this->_findValue($caller->_submitValues) : $this->_defaultDataset;
// Fix for bug #4465 & #5269
// XXX: should we push this to element::onQuickFormEvent()?
if ($value === null && (! $caller->isSubmitted() || ! $this->getMultiple())) {
$value = $this->_findValue($caller->_defaultValues);
}
}
if ($value !== null) {
if (! is_array($value)) {
$value = [$value];
}
$this->_defaultDataset = $value;
$this->setDefaultFixedDatas();
}
return true;
}
return parent::onQuickFormEvent($event, $arg, $caller);
}
}
if (class_exists('HTML_QuickForm')) {
(new HTML_QuickForm())->registerElementType(
'select2',
'HTML/QuickForm/select2.php',
'HTML_QuickForm_select2'
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/customcheckbox.php | centreon/www/lib/HTML/QuickForm/customcheckbox.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
*
*/
/**
* HTML class for a checkbox type field
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_01.txt If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category HTML
* @package HTML_QuickForm
* @author Adam Daniel <adaniel1@eesus.jnj.com>
* @author Bertrand Mansion <bmansion@mamasam.com>
* @author Alexey Borzov <avb@php.net>
* @copyright 2001-2011 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version CVS: $Id$
* @see http://pear.php.net/package/HTML_QuickForm
*/
/**
* HTML class for a checkbox type field
*
* @category HTML
* @package HTML_QuickForm
* @author Adam Daniel <adaniel1@eesus.jnj.com>
* @author Bertrand Mansion <bmansion@mamasam.com>
* @author Alexey Borzov <avb@php.net>
* @version Release: 3.2.14
* @since 1.0
*/
class HTML_QuickForm_customcheckbox extends HTML_QuickForm_checkbox
{
public $checkboxTemplate;
/**
* @return string
*/
public function toHtml()
{
$oldHtml = parent::toHtml();
$matches = ['{element}', '{id}'];
$replacements = [$oldHtml, $this->getAttribute('id')];
return str_replace($matches, $replacements, $this->checkboxTemplate);
}
public function setCheckboxTemplate($checkboxTemplate): void
{
$this->checkboxTemplate = $checkboxTemplate;
}
}
if (class_exists('HTML_QuickForm')) {
(new HTML_QuickForm())->registerElementType(
'customcheckbox',
'HTML/QuickForm/customcheckbox.php',
'HTML_QuickForm_customcheckbox'
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/lib/HTML/QuickForm/tags.php | centreon/www/lib/HTML/QuickForm/tags.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
*
*/
/**
* Description of tags
*
* @author Toufik MECHOUET
*/
class HTML_QuickForm_tags extends HTML_QuickForm_select2
{
/**
* @param string $elementName
* @param string $elementLabel
* @param array $options
* @param array $attributes
* @param string $sort
*/
public function __construct(
$elementName = null,
$elementLabel = null,
$options = null,
$attributes = null,
$sort = null,
) {
global $centreon;
$this->_ajaxSource = false;
$this->_defaultSelectedOptions = '';
$this->_multipleHtml = '';
$this->_allowClear = true;
$this->_elementHtmlName = $this->getName();
$this->_defaultDataset = [];
$this->_defaultDatasetOptions = [];
$this->_jsCallback = '';
$this->_allowClear = false;
$this->_pagination = $centreon->optGen['selectPaginationSize'];
$this->parseCustomAttributes($attributes);
parent::__construct($elementName, $elementLabel, $options, $attributes);
}
/**
* @return string
*/
public function getJsInit()
{
$allowClear = 'true';
if ($this->_allowClear === false || $this->_flagFrozen) {
$allowClear = 'false';
}
$disabled = 'false';
if ($this->_flagFrozen) {
$disabled = 'true';
}
$ajaxOption = '';
$defaultData = '';
if ($this->_ajaxSource) {
$ajaxOption = 'ajax: {
url: "' . $this->_availableDatasetRoute . '"
},';
if ($this->_defaultDatasetRoute && (count($this->_defaultDataset) == 0)) {
$additionnalJs = $this->setDefaultAjaxDatas();
} else {
$this->setDefaultFixedDatas();
}
} else {
$defaultData = $this->setFixedDatas() . ',';
}
$additionnalJs = ' jQuery(".select2-selection").each(function(){'
. ' if(typeof this.isResiable == "undefined" || this.isResiable){'
. ' jQuery(this).resizable({ maxWidth: 500, '
. ' minWidth : jQuery(this).width() != 0 ? jQuery(this).width() : 200, '
. ' minHeight : jQuery(this).height() != 0 ? jQuery(this).height() : 45 });'
. ' this.isResiable = true; '
. ' }'
. ' }); ';
return '<script>
jQuery(function () {
var $currentSelect2Object' . $this->getName() . ' = jQuery("#' . $this->getName() . '").centreonSelect2({
allowClear: ' . $allowClear . ',
pageLimit: ' . $this->_pagination . ',
select2: {
tags: true,
' . $ajaxOption . '
' . $defaultData . '
placeholder: "' . $this->getLabel() . '",
disabled: ' . $disabled . '
}
});
' . $additionnalJs . '
});
</script>';
}
}
if (class_exists('HTML_QuickForm')) {
(new HTML_QuickForm())->registerElementType(
'tags',
'HTML/QuickForm/tags.php',
'HTML_QuickForm_tags'
);
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonExternalCommand.class.php | centreon/www/class/centreonExternalCommand.class.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
*
*/
// file centreon.config.php may not exist in test environment
$configFile = realpath(__DIR__ . '/../../config/centreon.config.php');
if ($configFile !== false) {
require_once $configFile;
}
require_once __DIR__ . '/centreonDB.class.php';
require_once realpath(__DIR__ . '/centreonDBInstance.class.php');
require_once __DIR__ . '/../include/common/common-Func.php';
/**
* Class
*
* @class CentreonExternalCommand
* @description This class allows the user to send external commands to Nagios
*/
class CentreonExternalCommand
{
/** @var array */
public $localhostTab = [];
/** @var int */
public $debug = 0;
/** @var CentreonDB */
protected $DB;
/** @var CentreonDB */
protected $DBC;
/** @var array */
protected $cmdTab = [];
/** @var array */
protected $pollerTab;
/** @var array */
protected $actions = [];
/** @var CentreonGMT */
protected $GMT;
/** @var string|null */
protected $userAlias;
/** @var int|mixed|string|null */
protected $userId;
/**
* CentreonExternalCommand constructor
*/
public function __construct()
{
global $centreon;
$rq = "SELECT id FROM `nagios_server` WHERE localhost = '1'";
$DBRES = CentreonDBInstance::getDbCentreonInstance()->query($rq);
while ($row = $DBRES->fetchRow()) {
$this->localhostTab[$row['id']] = '1';
}
$DBRES->closeCursor();
$this->setExternalCommandList();
// Init GMT classes
$this->GMT = new CentreonGMT();
$this->GMT->getMyGMTFromSession(session_id());
if (! is_null($centreon)) {
$this->userId = $centreon->user->get_id();
$this->userAlias = $centreon->user->get_alias();
}
}
/**
* @param $newUserId
*
* @return void
*/
public function setUserId($newUserId): void
{
$this->userId = $newUserId;
}
/**
* @param $newUserAlias
*
* @return void
*/
public function setUserAlias($newUserAlias): void
{
$this->userAlias = $newUserAlias;
}
/**
* Write command in Nagios or Centcore Pipe.
*
* @return int
*/
public function write()
{
global $centreon;
$varlib = ! defined('_CENTREON_VARLIB_') ? '/var/lib/centreon' : _CENTREON_VARLIB_;
$str_remote = '';
$return_remote = 0;
foreach ($this->cmdTab as $key => $cmd) {
$cmd = str_replace('"', '', $cmd);
$cmd = str_replace("\n", '<br>', $cmd);
$cmd = '[' . time() . '] ' . $cmd . "\n";
$str_remote .= 'EXTERNALCMD:' . $this->pollerTab[$key] . ':' . $cmd;
}
if ($str_remote != '') {
if ($this->debug) {
echo "COMMAND BEFORE SEND: {$str_remote}";
}
$result = file_put_contents($varlib . '/centcore/' . microtime(true) . '-externalcommand.cmd', $str_remote, FILE_APPEND);
$return_remote = ($result !== false) ? 0 : 1;
}
$this->cmdTab = [];
$this->pollerTab = [];
return $return_remote;
}
/**
* @param $command
* @param $poller
*
* @return void
*/
public function setProcessCommand($command, $poller): void
{
if ($this->debug) {
echo "POLLER: {$poller}<br>";
echo "COMMAND: {$command}<br>";
}
$this->cmdTab[] = $command;
$this->pollerTab[] = $poller;
}
/**
* Get poller id where the host is hosted
*
* @param null $host
*
* @throws PDOException
* @return int
* @internal param $pearDB
* @internal param $host_name
*/
public function getPollerID($host = null)
{
if (! isset($host)) {
return 0;
}
$db = CentreonDBInstance::getDbCentreonStorageInstance();
// Check if $host is an id or a name
if (preg_match("/^\d+$/", $host)) {
$statement = $db->prepare(
<<<'SQL'
SELECT instance_id
FROM hosts
WHERE hosts.host_id = :host_id
AND hosts.enabled = '1'
SQL
);
$statement->bindValue(':host_id', (int) $host, PDO::PARAM_INT);
$statement->execute();
} else {
$statement = $db->prepare(
<<<'SQL'
SELECT instance_id
FROM hosts
WHERE hosts.name = :host_name
AND hosts.enabled = '1' LIMIT 1
SQL
);
$statement->bindValue(':host_name', $host);
$statement->execute();
}
$row = $statement->fetchRow();
return $row['instance_id'] ?? 0;
}
/**
* get list of external commands
*
* @return array
*/
public function getExternalCommandList()
{
return $this->actions;
}
// Schedule check
/**
* @param $hostName
*
* @throws PDOException
*/
public function scheduleForcedCheckHost($hostName): void
{
$pollerId = $this->getPollerID($hostName);
$this->setProcessCommand(
'SCHEDULE_FORCED_HOST_CHECK;' . $hostName . ';' . time(),
$pollerId
);
$this->write();
}
/**
* @param $hostName
* @param $serviceDescription
*
* @throws PDOException
*/
public function scheduleForcedCheckService($hostName, $serviceDescription): void
{
$pollerId = $this->getPollerID($hostName);
$this->setProcessCommand(
'SCHEDULE_FORCED_SVC_CHECK;' . $hostName . ';' . $serviceDescription . ';' . time(),
$pollerId
);
$this->write();
}
// Acknowledgement
/**
* @param $hostName
* @param $sticky
* @param $notify
* @param $persistent
* @param $author
* @param $comment
*
* @throws PDOException
*/
public function acknowledgeHost(
$hostName,
$sticky,
$notify,
$persistent,
$author,
$comment,
): void {
$pollerId = $this->getPollerID($hostName);
$this->setProcessCommand(
'ACKNOWLEDGE_HOST_PROBLEM;' . $hostName . ';'
. $sticky . ';' . $notify . ';' . $persistent . ';' . $author . ';' . $comment,
$pollerId
);
$this->write();
}
/**
* @param $hostName
* @param $serviceDescription
* @param $sticky
* @param $notify
* @param $persistent
* @param $author
* @param $comment
*
* @throws PDOException
*/
public function acknowledgeService(
$hostName,
$serviceDescription,
$sticky,
$notify,
$persistent,
$author,
$comment,
): void {
$pollerId = $this->getPollerID($hostName);
$this->setProcessCommand(
'ACKNOWLEDGE_SVC_PROBLEM;' . $hostName . ';' . $serviceDescription . ';'
. $sticky . ';' . $notify . ';' . $persistent . ';' . $author . ';' . $comment,
$pollerId
);
$this->write();
}
/**
* Delete acknowledgement.
*
* @param string $type (HOST/SVC)
* @param array $hosts
*
* @throws PDOException
*/
public function deleteAcknowledgement($type, $hosts = []): void
{
foreach (array_keys($hosts) as $name) {
$res = preg_split("/\;/", $name);
$oName = $res[0];
$pollerId = $this->getPollerID($oName);
if ($type === 'SVC') {
$oName .= ';' . $res[1];
}
$this->setProcessCommand('REMOVE_' . $type . '_ACKNOWLEDGEMENT;' . $oName, $pollerId);
}
$this->write();
}
/**
* Delete downtimes.
*
* @param string $type
* @param array $hosts
*
* @throws PDOException
*/
public function deleteDowntime($type, $hosts = []): void
{
foreach ($hosts as $key => $value) {
$res = preg_split("/\;/", $key);
$pollerId = $this->getPollerID($res[0]);
$downtimeInternalId = (int) $res[1];
$this->setProcessCommand('DEL_' . $type . '_DOWNTIME;' . $downtimeInternalId, $pollerId);
}
$this->write();
}
/**
* Add a host downtime
*
* @param string $host
* @param string $comment
* @param string $start
* @param string $end
* @param int $persistant
* @param null $duration
* @param bool $withServices
* @param string $hostOrCentreonTime
*
* @throws PDOException
*/
public function addHostDowntime(
$host,
$comment,
$start,
$end,
$persistant,
$duration = null,
$withServices = false,
$hostOrCentreonTime = '0',
): void {
global $centreon;
if (is_null($centreon)) {
global $oreon;
$centreon = $oreon;
}
if (! isset($persistant) || ! in_array($persistant, ['0', '1'])) {
$persistant = '0';
}
if ($hostOrCentreonTime == '0') {
$timezoneId = $this->GMT->getMyGTMFromUser($this->userId);
} else {
$timezoneId = $this->GMT->getUTCLocationHost($host);
}
$timezone = $this->GMT->getActiveTimezone($timezoneId);
$start_time = $this->getDowntimeTimestampFromDate($start, $timezone, true);
$end_time = $this->getDowntimeTimestampFromDate($end, $timezone, false);
if ($end_time == $start_time) {
return;
}
// Get poller for this host
$poller_id = $this->getPollerID($host);
// Send command
if (! isset($duration)) {
$duration = $end_time - $start_time;
}
$finalHostName = '';
if (! is_numeric($host)) {
$finalHostName .= $host;
} else {
$finalHostName .= getMyHostName($host);
}
$this->setProcessCommand(
'SCHEDULE_HOST_DOWNTIME;' . $finalHostName . ';' . $start_time . ';' . $end_time
. ';' . $persistant . ';0;' . $duration . ';' . $this->userAlias . ';' . $comment,
$poller_id
);
if ($withServices === true) {
$this->setProcessCommand(
'SCHEDULE_HOST_SVC_DOWNTIME;' . $finalHostName . ';' . $start_time . ';' . $end_time
. ';' . $persistant . ';0;' . $duration . ';' . $this->userAlias . ';' . $comment,
$poller_id
);
}
$this->write();
}
/**
* Add Service Downtime
*
* @param string $host
* @param string $service
* @param string $comment
* @param string $start
* @param string $end
* @param int $persistant
* @param null $duration
* @param string $hostOrCentreonTime
*
* @throws PDOException
*/
public function addSvcDowntime(
$host,
$service,
$comment,
$start,
$end,
$persistant,
$duration = null,
$hostOrCentreonTime = '0',
): void {
global $centreon;
if (is_null($centreon)) {
global $oreon;
$centreon = $oreon;
}
if (! isset($persistant) || ! in_array($persistant, ['0', '1'])) {
$persistant = '0';
}
if ($hostOrCentreonTime == '0') {
$timezoneId = $this->GMT->getMyGTMFromUser($this->userId);
} else {
$timezoneId = $this->GMT->getUTCLocationHost($host);
}
$timezone = $this->GMT->getActiveTimezone($timezoneId);
$start_time = $this->getDowntimeTimestampFromDate($start, $timezone, true);
$end_time = $this->getDowntimeTimestampFromDate($end, $timezone, false);
if ($end_time == $start_time) {
return;
}
// Get poller for this host
$poller_id = $this->getPollerID($host);
// Send command
if (! isset($duration)) {
$duration = $end_time - $start_time;
}
$finalHostName = '';
if (! is_numeric($host)) {
$finalHostName .= $host;
} else {
$finalHostName .= getMyHostName($host);
}
$finalServiceName = '';
if (! is_numeric($service)) {
$finalServiceName .= $service;
} else {
$finalServiceName .= getMyServiceName($service);
}
$this->setProcessCommand(
'SCHEDULE_SVC_DOWNTIME;' . $finalHostName . ';' . $finalServiceName . ';' . $start_time
. ';' . $end_time . ';' . $persistant . ';0;' . $duration . ';' . $this->userAlias
. ';' . $comment,
$poller_id
);
$this->write();
}
/**
* set list of external commands
*
* @return void
*/
private function setExternalCommandList(): void
{
// Services Actions
$this->actions['service_checks'][0] = 'ENABLE_SVC_CHECK';
$this->actions['service_checks'][1] = 'DISABLE_SVC_CHECK';
$this->actions['service_notifications'][0] = 'ENABLE_SVC_NOTIFICATIONS';
$this->actions['service_notifications'][1] = 'DISABLE_SVC_NOTIFICATIONS';
$this->actions['service_acknowledgement'][0] = 'ACKNOWLEDGE_SVC_PROBLEM';
$this->actions['service_disacknowledgement'][0] = 'REMOVE_SVC_ACKNOWLEDGEMENT';
$this->actions['service_schedule_check'][0] = 'SCHEDULE_SVC_CHECK';
$this->actions['service_schedule_check'][1] = 'SCHEDULE_FORCED_SVC_CHECK';
$this->actions['service_schedule_forced_check'][0] = 'SCHEDULE_FORCED_SVC_CHECK';
$this->actions['service_schedule_downtime'][0] = 'SCHEDULE_SVC_DOWNTIME';
$this->actions['service_comment'][0] = 'ADD_SVC_COMMENT';
$this->actions['service_event_handler'][0] = 'ENABLE_SVC_EVENT_HANDLER';
$this->actions['service_event_handler'][1] = 'DISABLE_SVC_EVENT_HANDLER';
$this->actions['service_flap_detection'][0] = 'ENABLE_SVC_FLAP_DETECTION';
$this->actions['service_flap_detection'][1] = 'DISABLE_SVC_FLAP_DETECTION';
$this->actions['service_passive_checks'][0] = 'ENABLE_PASSIVE_SVC_CHECKS';
$this->actions['service_passive_checks'][1] = 'DISABLE_PASSIVE_SVC_CHECKS';
$this->actions['service_submit_result'][0] = 'PROCESS_SERVICE_CHECK_RESULT';
$this->actions['service_obsess'][0] = 'START_OBSESSING_OVER_SVC';
$this->actions['service_obsess'][1] = 'STOP_OBSESSING_OVER_SVC';
// Hosts Actions
$this->actions['host_checks'][0] = 'ENABLE_HOST_CHECK';
$this->actions['host_checks'][1] = 'DISABLE_HOST_CHECK';
$this->actions['host_passive_checks'][0] = 'ENABLE_PASSIVE_HOST_CHECKS';
$this->actions['host_passive_checks'][1] = 'DISABLE_PASSIVE_HOST_CHECKS';
$this->actions['host_notifications'][0] = 'ENABLE_HOST_NOTIFICATIONS';
$this->actions['host_notifications'][1] = 'DISABLE_HOST_NOTIFICATIONS';
$this->actions['host_acknowledgement'][0] = 'ACKNOWLEDGE_HOST_PROBLEM';
$this->actions['host_disacknowledgement'][0] = 'REMOVE_HOST_ACKNOWLEDGEMENT';
$this->actions['host_schedule_check'][0] = 'SCHEDULE_HOST_SVC_CHECKS';
$this->actions['host_schedule_check'][1] = 'SCHEDULE_FORCED_HOST_SVC_CHECKS';
$this->actions['host_schedule_forced_check'][0] = 'SCHEDULE_FORCED_HOST_SVC_CHECKS';
$this->actions['host_schedule_downtime'][0] = 'SCHEDULE_HOST_DOWNTIME';
$this->actions['host_comment'][0] = 'ADD_HOST_COMMENT';
$this->actions['host_event_handler'][0] = 'ENABLE_HOST_EVENT_HANDLER';
$this->actions['host_event_handler'][1] = 'DISABLE_HOST_EVENT_HANDLER';
$this->actions['host_flap_detection'][0] = 'ENABLE_HOST_FLAP_DETECTION';
$this->actions['host_flap_detection'][1] = 'DISABLE_HOST_FLAP_DETECTION';
$this->actions['host_checks_for_services'][0] = 'ENABLE_HOST_SVC_CHECKS';
$this->actions['host_checks_for_services'][1] = 'DISABLE_HOST_SVC_CHECKS';
$this->actions['host_notifications_for_services'][0] = 'ENABLE_HOST_SVC_NOTIFICATIONS';
$this->actions['host_notifications_for_services'][1] = 'DISABLE_HOST_SVC_NOTIFICATIONS';
$this->actions['host_obsess'][0] = 'START_OBSESSING_OVER_HOST';
$this->actions['host_obsess'][1] = 'STOP_OBSESSING_OVER_HOST';
// Global Nagios External Commands
$this->actions['global_shutdown'][0] = 'SHUTDOWN_PROGRAM';
$this->actions['global_shutdown'][1] = 'SHUTDOWN_PROGRAM';
$this->actions['global_restart'][0] = 'RESTART_PROGRAM';
$this->actions['global_restart'][1] = 'RESTART_PROGRAM';
$this->actions['global_notifications'][0] = 'ENABLE_NOTIFICATIONS';
$this->actions['global_notifications'][1] = 'DISABLE_NOTIFICATIONS';
$this->actions['global_service_checks'][0] = 'START_EXECUTING_SVC_CHECKS';
$this->actions['global_service_checks'][1] = 'STOP_EXECUTING_SVC_CHECKS';
$this->actions['global_service_passive_checks'][0] = 'START_ACCEPTING_PASSIVE_SVC_CHECKS';
$this->actions['global_service_passive_checks'][1] = 'STOP_ACCEPTING_PASSIVE_SVC_CHECKS';
$this->actions['global_host_checks'][0] = 'START_EXECUTING_HOST_CHECKS';
$this->actions['global_host_checks'][1] = 'STOP_EXECUTING_HOST_CHECKS';
$this->actions['global_host_passive_checks'][0] = 'START_ACCEPTING_PASSIVE_HOST_CHECKS';
$this->actions['global_host_passive_checks'][1] = 'STOP_ACCEPTING_PASSIVE_HOST_CHECKS';
$this->actions['global_event_handler'][0] = 'ENABLE_EVENT_HANDLERS';
$this->actions['global_event_handler'][1] = 'DISABLE_EVENT_HANDLERS';
$this->actions['global_flap_detection'][0] = 'ENABLE_FLAP_DETECTION';
$this->actions['global_flap_detection'][1] = 'DISABLE_FLAP_DETECTION';
$this->actions['global_service_obsess'][0] = 'START_OBSESSING_OVER_SVC_CHECKS';
$this->actions['global_service_obsess'][1] = 'STOP_OBSESSING_OVER_SVC_CHECKS';
$this->actions['global_host_obsess'][0] = 'START_OBSESSING_OVER_HOST_CHECKS';
$this->actions['global_host_obsess'][1] = 'STOP_OBSESSING_OVER_HOST_CHECKS';
$this->actions['global_perf_data'][0] = 'ENABLE_PERFORMANCE_DATA';
$this->actions['global_perf_data'][1] = 'DISABLE_PERFORMANCE_DATA';
}
// Downtime
/**
* @param $date
* @param $timezone
* @param $start
*
* @throws Exception
* @return int
*/
private function getDowntimeTimestampFromDate($date = 'now', $timezone = '', $start = true)
{
$inputDate = new DateTime($date . ' GMT');
$dateTime = new DateTime($date, new DateTimeZone($timezone));
// Winter to summer dst
$dateTime2 = clone $dateTime;
$dateTime2->setTimestamp($dateTime2->getTimestamp());
if ($dateTime2->format('H') != $inputDate->format('H')) {
$hour = $inputDate->format('H');
$dateTime->setTime($hour, '00');
return $dateTime->getTimestamp();
}
// Summer to winter dst
$dateTime3 = clone $dateTime;
$dateTime3->sub(new DateInterval('PT1H'));
if ($dateTime3->format('H:m') === $dateTime->format('H:m')) {
if ($start) {
return $dateTime->getTimestamp() - 3600;
}
return $dateTime->getTimestamp();
}
$dateTime4 = clone $dateTime;
$dateTime4->add(new DateInterval('PT1H'));
if ($dateTime4->format('H:m') === $dateTime->format('H:m')) {
if ($start) {
return $dateTime->getTimestamp();
}
return $dateTime->getTimestamp() + 3600;
}
return $dateTime->getTimestamp();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonContact.class.php | centreon/www/class/centreonContact.class.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\Security\ProviderConfiguration\Domain\Local\Model\SecurityPolicy;
/**
* Class
*
* @class CentreonContact
*/
class CentreonContact
{
/** @var CentreonDB */
protected $db;
/**
* CentreonContact constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Get contact templates
*
* @param array $fields | columns to return
* @param array $filters
* @param array $order |i.e: array('contact_name', 'ASC')
* @param array $limit |i.e: array($limit, $offset)
*
* @throws PDOException
* @return array
*/
public function getContactTemplates($fields = [], $filters = [], $order = [], $limit = [])
{
$fieldStr = '*';
if (count($fields)) {
$fieldStr = implode(', ', $fields);
}
$filterStr = " WHERE contact_register = '0' ";
foreach ($filters as $k => $v) {
$filterStr .= " AND {$k} LIKE '{$this->db->escape($v)}' ";
}
$orderStr = '';
if (count($order) === 2) {
$orderStr = " ORDER BY {$order[0]} {$order[1]} ";
}
$limitStr = '';
if (count($limit) === 2) {
$limitStr = " LIMIT {$limit[0]},{$limit[1]}";
}
$res = $this->db->query("SELECT SQL_CALC_FOUND_ROWS {$fieldStr}
FROM contact
{$filterStr}
{$orderStr}
{$limitStr}");
$arr = [];
while ($row = $res->fetchRow()) {
$arr[] = $row;
}
return $arr;
}
/**
* Get contactgroup from contact id
*
* @param CentreonDB $db
* @param int $contactId
*
* @throws PDOException
* @return array
*/
public static function getContactGroupsFromContact($db, $contactId)
{
$sql = 'SELECT cg_id, cg_name
FROM contactgroup_contact_relation r, contactgroup cg
WHERE cg.cg_id = r.contactgroup_cg_id
AND r.contact_contact_id = ' . $db->escape($contactId);
$stmt = $db->query($sql);
$cgs = [];
while ($row = $stmt->fetchRow()) {
$cgs[$row['cg_id']] = $row['cg_name'];
}
return $cgs;
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'contact';
$parameters['currentObject']['id'] = 'contact_id';
$parameters['currentObject']['name'] = 'contact_name';
$parameters['currentObject']['comparator'] = 'contact_id';
switch ($field) {
case 'timeperiod_tp_id':
case 'timeperiod_tp_id2':
$parameters['type'] = 'simple';
$parameters['externalObject']['table'] = 'timeperiod';
$parameters['externalObject']['id'] = 'tp_id';
$parameters['externalObject']['name'] = 'tp_name';
$parameters['externalObject']['comparator'] = 'tp_id';
break;
case 'contact_hostNotifCmds':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'command';
$parameters['externalObject']['id'] = 'command_id';
$parameters['externalObject']['name'] = 'command_name';
$parameters['externalObject']['comparator'] = 'command_id';
$parameters['relationObject']['table'] = 'contact_hostcommands_relation';
$parameters['relationObject']['field'] = 'command_command_id';
$parameters['relationObject']['comparator'] = 'contact_contact_id';
break;
case 'contact_svNotifCmds':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'command';
$parameters['externalObject']['id'] = 'command_id';
$parameters['externalObject']['name'] = 'command_name';
$parameters['externalObject']['comparator'] = 'command_id';
$parameters['relationObject']['table'] = 'contact_servicecommands_relation';
$parameters['relationObject']['field'] = 'command_command_id';
$parameters['relationObject']['comparator'] = 'contact_contact_id';
break;
case 'contact_cgNotif':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'contactgroup';
$parameters['externalObject']['id'] = 'cg_id';
$parameters['externalObject']['name'] = 'cg_name';
$parameters['externalObject']['comparator'] = 'cg_id';
$parameters['relationObject']['table'] = 'contactgroup_contact_relation';
$parameters['relationObject']['field'] = 'contactgroup_cg_id';
$parameters['relationObject']['comparator'] = 'contact_contact_id';
break;
case 'contact_location':
$parameters['type'] = 'simple';
$parameters['externalObject']['table'] = 'timezone';
$parameters['externalObject']['id'] = 'timezone_id';
$parameters['externalObject']['name'] = 'timezone_name';
$parameters['externalObject']['comparator'] = 'timezone_id';
break;
case 'contact_acl_groups':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'acl_groups';
$parameters['externalObject']['id'] = 'acl_group_id';
$parameters['externalObject']['name'] = 'acl_group_name';
$parameters['externalObject']['comparator'] = 'acl_group_id';
$parameters['relationObject']['table'] = 'acl_group_contacts_relations';
$parameters['relationObject']['field'] = 'acl_group_id';
$parameters['relationObject']['comparator'] = 'contact_contact_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
global $centreon;
$items = [];
// get list of authorized contacts
if (! $centreon->user->access->admin) {
$cAcl = $centreon->user->access->getContactAclConf(
['fields' => ['contact_id'], 'get_row' => 'contact_id', 'keys' => ['contact_id'], 'conditions' => ['contact_id' => ['IN', $values]]],
false
);
}
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':contact' . $v . ',';
$queryValues['contact' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected contacts
$query = 'SELECT contact_id, contact_name FROM contact '
. 'WHERE contact_id IN (' . $listValues . ') ORDER BY contact_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
// hide unauthorized contacts
$hide = false;
if (! $centreon->user->access->admin && ! in_array($row['contact_id'], $cAcl)) {
$hide = true;
}
$items[] = ['id' => $row['contact_id'], 'text' => $row['contact_name'], 'hide' => $hide];
}
return $items;
}
/**
* Find contact id from alias
*
* @param string $alias
*
* @throws PDOException
* @return int|null
*/
public function findContactIdByAlias(string $alias): ?int
{
$contactId = null;
$statement = $this->db->prepare(
'SELECT contact_id
FROM contact
WHERE contact_alias = :contactAlias'
);
$statement->bindValue(':contactAlias', $alias, PDO::PARAM_STR);
$statement->execute();
if ($row = $statement->fetch()) {
$contactId = (int) $row['contact_id'];
}
return $contactId;
}
/**
* Get password security policy
*
* @throws PDOException
* @return array<string,mixed>
*/
public function getPasswordSecurityPolicy(): array
{
$result = $this->db->query(
"SELECT `custom_configuration` FROM `provider_configuration` WHERE `name` = 'local'"
);
$configuration = $result->fetch(PDO::FETCH_ASSOC);
if ($configuration === false || empty($configuration['custom_configuration'])) {
throw new Exception('Password security policy not found');
}
$customConfiguration = json_decode($configuration['custom_configuration'], true);
if (! array_key_exists('password_security_policy', $customConfiguration)) {
throw new Exception('Security Policy not found in custom configuration');
}
$securityPolicyData = $customConfiguration['password_security_policy'];
$securityPolicyData['password_expiration'] = [
'expiration_delay' => $securityPolicyData['password_expiration_delay'],
'excluded_users' => $this->getPasswordExpirationExcludedUsers(),
];
return $securityPolicyData;
}
/**
* Check if a password respects configured policy
*
* @param string $password
* @param int|null $contactId
*
* @throws Exception
* @return void
*/
public function respectPasswordPolicyOrFail(string $password, ?int $contactId): void
{
$passwordSecurityPolicy = $this->getPasswordSecurityPolicy();
$this->respectPasswordCharactersOrFail($passwordSecurityPolicy, $password);
if ($contactId !== null) {
$this->respectPasswordChangePolicyOrFail(
$passwordSecurityPolicy,
$password,
$contactId,
);
}
}
/**
* Find last password creation date by contact id
*
* @param int $contactId
*
* @throws PDOException
* @return DateTimeImmutable|null
*/
public function findLastPasswordCreationDate(int $contactId): ?DateTimeImmutable
{
$creationDate = null;
$statement = $this->db->prepare(
'SELECT creation_date
FROM contact_password
WHERE contact_id = :contactId
ORDER BY creation_date DESC LIMIT 1'
);
$statement->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$statement->execute();
if ($row = $statement->fetch()) {
$creationDate = (new DateTimeImmutable())->setTimestamp((int) $row['creation_date']);
}
return $creationDate;
}
/**
* Add new password to a contact
*
* @param int $contactId
* @param string $hashedPassword
*
* @throws PDOException
* @return void
*/
public function addPasswordByContactId(int $contactId, string $hashedPassword): void
{
$statement = $this->db->prepare(
'INSERT INTO `contact_password` (`password`, `contact_id`, `creation_date`)
VALUES (:password, :contactId, :creationDate)'
);
$statement->bindValue(':password', $hashedPassword, PDO::PARAM_STR);
$statement->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$statement->bindValue(':creationDate', time(), PDO::PARAM_INT);
$statement->execute();
}
/**
* Replace stored password for a contact
*
* @param int $contactId
* @param string $oldHashedPassword
* @param string $newHashedPassword
*
* @throws PDOException
* @return void
*/
public function replacePasswordByContactId(
int $contactId,
string $oldHashedPassword,
string $newHashedPassword,
): void {
$statement = $this->db->prepare(
'UPDATE `contact_password`
SET password = :newPassword
WHERE contact_id = :contactId
AND password = :oldPassword'
);
$statement->bindValue(':oldPassword', $oldHashedPassword, PDO::PARAM_STR);
$statement->bindValue(':newPassword', $newHashedPassword, PDO::PARAM_STR);
$statement->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$statement->execute();
}
/**
* add new contact password and delete old passwords
*
* @param int $contactId
* @param string $hashedPassword
*
* @throws PDOException
* @return void
*/
public function renewPasswordByContactId(int $contactId, string $hashedPassword): void
{
$this->addPasswordByContactId($contactId, $hashedPassword);
$this->deleteOldPasswords($contactId);
}
/**
* Get excluded users from password expiration policy
*
* @throws PDOException
* @return string[]
*/
private function getPasswordExpirationExcludedUsers(): array
{
$statement = $this->db->query(
"SELECT c.`contact_alias`
FROM `password_expiration_excluded_users` peeu
INNER JOIN `provider_configuration` pc ON pc.`id` = peeu.`provider_configuration_id`
AND pc.`name` = 'local'
INNER JOIN `contact` c ON c.`contact_id` = peeu.`user_id`
AND c.`contact_register` = 1"
);
$excludedUsers = [];
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$excludedUsers[] = $row['contact_alias'];
}
return $excludedUsers;
}
/**
* Check if a password respects configured policy about characters (length, special characters, ...)
*
* @param array<string,mixed> $passwordPolicy
* @param string $password
*
* @throws Exception
* @return void
*/
private function respectPasswordCharactersOrFail(array $passwordPolicy, string $password): void
{
$doesRespectPassword = true;
$errorMessage = sprintf(
_('Your password must be %d characters long'),
(int) $passwordPolicy['password_length']
);
if (strlen($password) < (int) $passwordPolicy['password_length']) {
$doesRespectPassword = false;
}
$characterRules = [
'has_uppercase_characters' => [
'pattern' => '/[A-Z]/',
'error_message' => _('uppercase characters'),
],
'has_lowercase_characters' => [
'pattern' => '/[a-z]/',
'error_message' => _('lowercase characters'),
],
'has_numbers' => [
'pattern' => '/[0-9]/',
'error_message' => _('numbers'),
],
'has_special_characters' => [
'pattern' => '/[' . SecurityPolicy::SPECIAL_CHARACTERS_LIST . ']/',
'error_message' => sprintf(_("special characters among '%s'"), SecurityPolicy::SPECIAL_CHARACTERS_LIST),
],
];
$characterPolicyErrorMessages = [];
foreach ($characterRules as $characterRule => $characterRuleParameters) {
if ((bool) $passwordPolicy[$characterRule] === true) {
$characterPolicyErrorMessages[] = $characterRuleParameters['error_message'];
if (! preg_match($characterRuleParameters['pattern'], $password)) {
$doesRespectPassword = false;
}
}
}
if ($doesRespectPassword === false) {
if ($characterPolicyErrorMessages !== []) {
$errorMessage .= ' ' . _('and must contain') . ' : '
. implode(', ', $characterPolicyErrorMessages) . '.';
}
throw new Exception($errorMessage);
}
}
/**
* Check if a user password respects configured policy when updated (delay, reuse)
*
* @param array<string,mixed> $passwordPolicy
* @param string $password
* @param int $contactId
*
* @throws Exception
* @return void
*/
private function respectPasswordChangePolicyOrFail(array $passwordPolicy, string $password, int $contactId): void
{
$passwordCreationDate = $this->findLastPasswordCreationDate($contactId);
if ($passwordCreationDate !== null) {
$delayBeforeNewPassword = (int) $passwordPolicy['delay_before_new_password'];
$isPasswordCanBeChanged = $passwordCreationDate->getTimestamp() + $delayBeforeNewPassword < time();
if (! $isPasswordCanBeChanged) {
throw new Exception(
_("You can't change your password because the delay before changing password is not over.")
);
}
}
if ((bool) $passwordPolicy['can_reuse_passwords'] === false) {
$statement = $this->db->prepare(
'SELECT id, password FROM `contact_password` WHERE `contact_id` = :contactId'
);
$statement->bindParam(':contactId', $contactId, PDO::PARAM_INT);
$statement->execute();
$passwordHistory = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($passwordHistory as $contactPassword) {
if (password_verify($password, $contactPassword['password'])) {
throw new Exception(
_(
'Your password has already been used. '
. 'Please choose a different password from the previous three.'
)
);
}
}
}
}
/**
* Delete old passwords to store only 3 last passwords
*
* @param int $contactId
*
* @throws PDOException
* @return void
*/
private function deleteOldPasswords(int $contactId): void
{
$statement = $this->db->prepare(
'SELECT creation_date
FROM `contact_password`
WHERE `contact_id` = :contactId
ORDER BY `creation_date` DESC'
);
$statement->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$statement->execute();
// If 3 or more passwords are saved, delete the oldest ones.
if (($result = $statement->fetchAll()) && count($result) > 3) {
$maxCreationDateToDelete = $result[3]['creation_date'];
$statement = $this->db->prepare(
'DELETE FROM `contact_password`
WHERE contact_id = :contactId
AND creation_date <= :creationDate'
);
$statement->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$statement->bindValue(':creationDate', $maxCreationDateToDelete, 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/class/centreonHostgroups.class.php | centreon/www/class/centreonHostgroups.class.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
*
*/
/**
* Class
*
* @class CentreonHostgroups
*/
class CentreonHostgroups
{
/** @var CentreonDB */
private $DB;
/** @var array */
private $relationCache = [];
/** @var array */
private $dataTree;
/**
* CentreonHostgroups constructor
*
* @param CentreonDB $pearDB
*/
public function __construct($pearDB)
{
$this->DB = $pearDB;
}
/**
* @param string|int|null $hg_id
*
* @throws PDOException
* @return array|void
*/
public function getHostGroupHosts($hg_id = null)
{
if (! $hg_id) {
return;
}
if (! count($this->relationCache)) {
$this->setHgHgCache();
}
$hosts = [];
$statement = $this->DB->prepare('SELECT hgr.host_host_id '
. 'FROM hostgroup_relation hgr, host h '
. 'WHERE hgr.hostgroup_hg_id = :hgId '
. 'AND h.host_id = hgr.host_host_id '
. 'ORDER by h.host_name');
$statement->bindValue(':hgId', (int) $hg_id, PDO::PARAM_INT);
$statement->execute();
while ($elem = $statement->fetchRow()) {
$ref[$elem['host_host_id']] = $elem['host_host_id'];
$hosts[] = $elem['host_host_id'];
}
$statement->closeCursor();
unset($elem);
if (isset($hostgroups) && count($hostgroups)) {
foreach ($hostgroups as $hg_id2) {
$ref[$hg_id2] = [];
$tmp = $this->getHostGroupHosts($hg_id2);
foreach ($tmp as $id) {
echo " host: {$id}<br>";
}
unset($tmp);
}
}
return $hosts;
}
/**
* Get Hostgroup Name
*
* @param int $hg_id
*
* @throws PDOException
* @return string
*/
public function getHostgroupName($hg_id)
{
static $names = [];
if (! isset($names[$hg_id])) {
$query = 'SELECT hg_name FROM hostgroup WHERE hg_id = ' . $this->DB->escape($hg_id);
$res = $this->DB->query($query);
if ($res->rowCount()) {
$row = $res->fetchRow();
$names[$hg_id] = $row['hg_name'];
}
}
return $names[$hg_id] ?? '';
}
/**
* Get Hostgroups ids and names from ids
*
* @param int[] $hostGroupsIds
*
* @throws PDOException
* @return array $hostsGroups [['id' => integer, 'name' => string],...]
*/
public function getHostsgroups($hostGroupsIds = []): array
{
$hostsGroups = [];
if (! empty($hostGroupsIds)) {
$filteredHgIds = $this->filteredArrayId($hostGroupsIds);
$hgParams = [];
if ($filteredHgIds !== []) {
/*
* Building the hgParams hash table in order to correctly
* bind ids as ints for the request.
*/
foreach ($filteredHgIds as $index => $filteredHgId) {
$hgParams[':hgId' . $index] = $filteredHgIds;
}
$stmt = $this->DB->prepare(
'SELECT hg_id, hg_name FROM hostgroup '
. 'WHERE hg_id IN ( ' . implode(',', array_keys($hgParams)) . ' )'
);
foreach ($hgParams as $index => $value) {
$stmt->bindValue($index, $value, PDO::PARAM_INT);
}
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hostsGroups[] = [
'id' => $row['hg_id'],
'name' => $row['hg_name'],
];
}
}
}
return $hostsGroups;
}
/**
* Get Hostgroup Id
*
* @param string $hg_name
*
* @throws PDOException
* @return int
*/
public function getHostgroupId($hg_name)
{
static $ids = [];
if (! isset($ids[$hg_name])) {
$query = "SELECT hg_id FROM hostgroup WHERE hg_name = '" . $this->DB->escape($hg_name) . "'";
$res = $this->DB->query($query);
if ($res->rowCount()) {
$row = $res->fetchRow();
$ids[$hg_name] = $row['hg_id'];
}
}
return $ids[$hg_name] ?? 0;
}
/**
* @param null $hg_id
*
* @throws PDOException
* @return array|void
*/
public function getHostGroupHostGroups($hg_id = null)
{
if (! $hg_id) {
return;
}
$hosts = [];
$DBRESULT = $this->DB->query(
'SELECT hg_child_id '
. 'FROM hostgroup_hg_relation, hostgroup '
. "WHERE hostgroup_hg_relation.hg_parent_id = '" . $this->DB->escape($hg_id) . "' "
. 'AND hostgroup.hg_id = hostgroup_hg_relation.hg_child_id '
. 'ORDER BY hostgroup.hg_name'
);
while ($elem = $DBRESULT->fetchRow()) {
$hosts[$elem['hg_child_id']] = $elem['hg_child_id'];
}
$DBRESULT->closeCursor();
unset($elem);
return $hosts;
}
/**
* @param $DB
*
* @throws PDOException
* @return array
*/
public function getAllHostgroupsInCache($DB)
{
$hostgroups = [];
$this->unsetCache();
$DBRESULT = $DB->query(
'SELECT * FROM hostgroup WHERE hg_id NOT IN (SELECT hg_child_id FROM hostgroup_hg_relation)'
);
while ($data = $DBRESULT->fetchRow()) {
$this->dataTree[$data['hg_id']] = $this->getHostGroupHosts($data['hg_id']);
}
$DBRESULT->closeCursor();
return $hostgroups;
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'hostgroup';
$parameters['currentObject']['id'] = 'hg_id';
$parameters['currentObject']['name'] = 'hg_name';
$parameters['currentObject']['comparator'] = 'hg_id';
switch ($field) {
case 'hg_hosts':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHost';
$parameters['externalObject']['table'] = 'host';
$parameters['externalObject']['id'] = 'host_id';
$parameters['externalObject']['name'] = 'host_name';
$parameters['externalObject']['comparator'] = 'host_id';
$parameters['relationObject']['table'] = 'hostgroup_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['comparator'] = 'hostgroup_hg_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
global $centreon;
$items = [];
if (empty($values)) {
return $items;
}
$hostgroups = [];
// $values structure: ['1,2,3,4'], keeping the foreach in case it could have more than one index
foreach ($values as $value) {
$hostgroups = array_merge($hostgroups, explode(',', $value));
}
// get list of authorized hostgroups
if (! $centreon->user->access->admin
&& $centreon->user->access->hasAccessToAllHostGroups === false
) {
$hgAcl = $centreon->user->access->getHostGroupAclConf(
null,
'broker',
['distinct' => true, 'fields' => ['hostgroup.hg_id'], 'get_row' => 'hg_id', 'keys' => ['hg_id'], 'conditions' => ['hostgroup.hg_id' => ['IN', $hostgroups]]],
true
);
}
// get list of selected hostgroups
$listValues = '';
$queryValues = [];
foreach ($hostgroups as $item) {
// the below explode may not be useful
$ids = explode('-', $item);
$listValues .= ':hgId_' . $ids[0] . ', ';
$queryValues['hgId_' . $ids[0]] = (int) $ids[0];
}
$listValues = rtrim($listValues, ', ');
$query = 'SELECT hg_id, hg_name FROM hostgroup WHERE hg_id IN (' . $listValues . ') ORDER BY hg_name ';
$stmt = $this->DB->prepare($query);
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
$stmt->execute();
while ($row = $stmt->fetch()) {
// hide unauthorized hostgroups
$hide = false;
if (
! $centreon->user->access->admin
&& $centreon->user->access->hasAccessToAllHostGroups === false
&& ! in_array($row['hg_id'], $hgAcl)
) {
$hide = true;
}
$items[] = ['id' => $row['hg_id'], 'text' => $row['hg_name'], 'hide' => $hide];
}
return $items;
}
/**
* @param $hgName
*
* @throws PDOException
* @return array
*/
public function getHostsByHostgroupName($hgName)
{
$hostList = [];
$query = 'SELECT host_name, host_id '
. 'FROM hostgroup_relation hgr, host h, hostgroup hg '
. 'WHERE hgr.host_host_id = h.host_id '
. 'AND hgr.hostgroup_hg_id = hg.hg_id '
. "AND h.host_activate = '1' "
. "AND hg.hg_name = '" . $this->DB->escape($hgName) . "'";
$result = $this->DB->query($query);
while ($elem = $result->fetchrow()) {
$hostList[] = ['host' => $elem['host_name'], 'host_id' => $elem['host_id'], 'hg_name' => $hgName];
}
return $hostList;
}
/**
* Returns a filtered array with only integer ids
*
* @param int[] $ids
* @return int[] filtered
*/
private function filteredArrayId(array $ids): array
{
return array_filter($ids, function ($id) {
return is_numeric($id);
});
}
/**
* @throws PDOException
* @return void
*/
private function setHgHgCache(): void
{
$this->relationCache = [];
$DBRESULT = $this->DB->query('SELECT /* SQL_CACHE */ hg_parent_id, hg_child_id FROM hostgroup_hg_relation');
while ($data = $DBRESULT->fetchRow()) {
if (! isset($this->relationCache[$data['hg_parent_id']])) {
$this->relationCache[$data['hg_parent_id']] = [];
}
$this->relationCache[$data['hg_parent_id']][$data['hg_child_id']] = 1;
}
$DBRESULT->closeCursor();
unset($data);
}
/**
* @return void
*/
private function unsetCache(): void
{
$this->dataTree = [];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonMetrics.class.php | centreon/www/class/centreonMetrics.class.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 _CENTREON_PATH_ . 'www/class/centreonInstance.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonCommand.class.php';
/**
* Class
*
* @class CentreonMetrics
*/
class CentreonMetrics
{
/** @var CentreonDB */
public $dbo;
/** @var CentreonDB */
protected $db;
/** @var CentreonInstance */
protected $instanceObj;
/** @var CentreonService */
protected $serviceObj;
/**
* CentreonMetrics constructor
*
* @param CentreonDB $db
*
* @throws PDOException
*/
public function __construct($db)
{
$this->db = $db;
$this->dbo = new CentreonDB('centstorage');
$this->instanceObj = new CentreonInstance($db);
$this->serviceObj = new CentreonService($db);
}
/**
* Get metrics information from ids to populat select2
*
* @param array $values list of metric ids
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [])
{
$metrics = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $v) {
$multiValues = explode(',', $v);
foreach ($multiValues as $item) {
$listValues .= ':metric' . $item . ',';
$queryValues['metric' . $item] = (int) $item;
}
}
$listValues = rtrim($listValues, ',');
} else {
$listValues = '""';
}
$queryService = "SELECT SQL_CALC_FOUND_ROWS m.metric_id, CONCAT(i.host_name,' - ', i.service_description,"
. "' - ', m.metric_name) AS fullname "
. 'FROM metrics m, index_data i '
. 'WHERE m.metric_id IN (' . $listValues . ') '
. 'AND i.id = m.index_id '
. 'ORDER BY fullname COLLATE utf8_general_ci';
$stmt = $this->dbo->prepare($queryService);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$metrics[] = [
'id' => $row['metric_id'],
'text' => $row['fullname'],
];
}
return $metrics;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonBroker.class.php | centreon/www/class/centreonBroker.class.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
*
*/
/**
* Class
*
* @class CentreonBroker
*/
class CentreonBroker
{
/** @var CentreonDB */
private $db;
/**
* CentreonBroker constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Reload centreon broker process
*
* @throws PDOException
* @return void
*/
public function reload(): void
{
if ($command = $this->getReloadCommand()) {
shell_exec(escapeshellcmd("sudo -n -- {$command}"));
}
}
/**
* Get command to reload centreon broker
*
* @throws PDOException
* @return string|null the command
*/
private function getReloadCommand(): ?string
{
$command = null;
$result = $this->db->query(
'SELECT broker_reload_command
FROM nagios_server
ORDER BY localhost DESC'
);
if ($row = $result->fetch()) {
$command = $row['broker_reload_command'];
}
return $command;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonTimeperiod.class.php | centreon/www/class/centreonTimeperiod.class.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
*
*/
/**
* Class
*
* @class CentreonTimeperiod
*/
class CentreonTimeperiod
{
/** @var CentreonDB */
protected $db;
/**
* CentreonTimeperiod constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':tp' . $v . ',';
$queryValues['tp' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected timeperiods
$query = 'SELECT tp_id, tp_name FROM timeperiod '
. 'WHERE tp_id IN (' . $listValues . ') ORDER BY tp_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['tp_id'], 'text' => $row['tp_name']];
}
return $items;
}
/**
* @param string $name
*
* @throws PDOException
* @return string
*/
public function getTimperiodIdByName($name)
{
$query = "SELECT tp_id FROM timeperiod
WHERE tp_name = '" . $this->db->escape($name) . "'";
$res = $this->db->query($query);
if (! $res->rowCount()) {
return null;
}
$row = $res->fetchRow();
return $row['tp_id'];
}
/**
* @param int $tpId
*
* @throws PDOException
* @return string
*/
public function getTimeperiodException($tpId)
{
$query = 'SELECT `exception_id` FROM `timeperiod_exceptions`
WHERE `timeperiod_id` = ' . (int) $tpId;
$res = $this->db->query($query);
if (! $res->rowCount()) {
return null;
}
$row = $res->fetchRow();
return $row['exception_id'];
}
/**
* Insert in database a command
*
* @param array $parameters Values to insert (command_name and command_line is mandatory)
* @throws Exception
*/
public function insert($parameters): void
{
$sQuery = 'INSERT INTO `timeperiod` '
. '(`tp_name`, `tp_alias`, `tp_sunday`, `tp_monday`, `tp_tuesday`, `tp_wednesday`, '
. '`tp_thursday`, `tp_friday`, `tp_saturday`) '
. "VALUES ('" . $parameters['name'] . "',"
. "'" . $parameters['alias'] . "',"
. "'" . $parameters['sunday'] . "',"
. "'" . $parameters['monday'] . "',"
. "'" . $parameters['tuesday'] . "',"
. "'" . $parameters['wednesday'] . "',"
. "'" . $parameters['thursday'] . "',"
. "'" . $parameters['friday'] . "',"
. "'" . $parameters['saturday'] . "')";
try {
$this->db->query($sQuery);
} catch (PDOException $e) {
throw new Exception('Error while insert timeperiod ' . $parameters['name']);
}
}
/**
* Update in database a command
*
* @param string|int $tp_id
* @param array $parameters
*
* @throws Exception
* @return void
*/
public function update($tp_id, $parameters): void
{
$sQuery = "UPDATE `timeperiod` SET `tp_alias` = '" . $parameters['alias'] . "', "
. "`tp_sunday` = '" . $parameters['sunday'] . "',"
. "`tp_monday` = '" . $parameters['monday'] . "',"
. "`tp_tuesday` = '" . $parameters['tuesday'] . "',"
. "`tp_wednesday` = '" . $parameters['wednesday'] . "',"
. "`tp_thursday` = '" . $parameters['thursday'] . "',"
. "`tp_friday` = '" . $parameters['friday'] . "',"
. "`tp_saturday` = '" . $parameters['saturday'] . "'"
. ' WHERE `tp_id` = ' . $tp_id;
try {
$this->db->query($sQuery);
} catch (PDOException $e) {
throw new Exception('Error while update timeperiod ' . $parameters['name']);
}
}
/**
* Insert in database a timeperiod exception
*
* @param int $tpId
* @param array $parameters Values to insert (days and timerange)
* @throws Exception
*/
public function setTimeperiodException($tpId, $parameters): void
{
foreach ($parameters as $exception) {
$sQuery = 'INSERT INTO `timeperiod_exceptions` '
. '(`timeperiod_id`, `days`, `timerange`) '
. 'VALUES (' . (int) $tpId . ','
. "'" . $exception['days'] . "',"
. "'" . $exception['timerange'] . "')";
try {
$this->db->query($sQuery);
} catch (PDOException $e) {
throw new Exception('Error while insert timeperiod exception' . $tpId);
}
}
}
/**
* Insert in database a timeperiod dependency
*
* @param int $timeperiodId
* @param int $depId
* @throws Exception
*/
public function setTimeperiodDependency($timeperiodId, $depId): void
{
$sQuery = 'INSERT INTO `timeperiod_include_relations` '
. '(`timeperiod_id`,`timeperiod_include_id`) '
. 'VALUES (' . (int) $timeperiodId . ',' . (int) $depId . ')';
try {
$this->db->query($sQuery);
} catch (PDOException $e) {
throw new Exception('Error while insert timeperiod dependency' . $timeperiodId);
}
}
/**
* Delete in database a timeperiod exception
*
* @param int $tpId
* @throws Exception
*/
public function deleteTimeperiodException($tpId): void
{
$sQuery = 'DELETE FROM `timeperiod_exceptions` WHERE `timeperiod_id` = ' . (int) $tpId;
try {
$res = $this->db->query($sQuery);
} catch (PDOException $e) {
throw new Exception('Error while delete timeperiod exception' . $tpId);
}
}
/**
* Delete in database a timeperiod include
*
* @param int $tpId
* @throws Exception
*/
public function deleteTimeperiodInclude($tpId): void
{
$sQuery = 'DELETE FROM `timeperiod_include_relations` WHERE `timeperiod_id` = ' . (int) $tpId;
try {
$this->db->query($sQuery);
} catch (PDOException $e) {
throw new Exception('Error while delete timeperiod include' . $tpId);
}
}
/**
* Delete timeperiod in database
*
* @param string $tp_name timperiod name
* @throws Exception
*/
public function deleteTimeperiodByName($tp_name): void
{
$sQuery = 'DELETE FROM timeperiod '
. 'WHERE tp_name = "' . $this->db->escape($tp_name) . '"';
try {
$this->db->query($sQuery);
} catch (PDOException $e) {
throw new Exception('Error while delete timperiod ' . $tp_name);
}
}
/**
* Returns array of Host linked to the timeperiod
*
* @param string $timeperiodName
* @param bool $register
*
* @throws Exception
* @return array
*/
public function getLinkedHostsByName($timeperiodName, $register = false)
{
$registerClause = '';
if ($register === '0' || $register === '1') {
$registerClause = 'AND h.host_register = "' . $register . '" ';
}
$linkedHosts = [];
$query = 'SELECT DISTINCT h.host_name '
. 'FROM host h, timeperiod t '
. 'WHERE (h.timeperiod_tp_id = t.tp_id OR h.timeperiod_tp_id2 = t.tp_id) '
. $registerClause
. 'AND t.tp_name = "' . $this->db->escape($timeperiodName) . '" ';
try {
$result = $this->db->query($query);
} catch (PDOException $e) {
throw new Exception('Error while getting linked hosts of ' . $timeperiodName);
}
while ($row = $result->fetchRow()) {
$linkedHosts[] = $row['host_name'];
}
return $linkedHosts;
}
/**
* Returns array of Service linked to the timeperiod
*
* @param string $timeperiodName
* @param bool $register
*
* @throws Exception
* @return array
*/
public function getLinkedServicesByName($timeperiodName, $register = false)
{
$registerClause = '';
if ($register === '0' || $register === '1') {
$registerClause = 'AND s.service_register = "' . $register . '" ';
}
$linkedServices = [];
$query = 'SELECT DISTINCT s.service_description '
. 'FROM service s, timeperiod t '
. 'WHERE (s.timeperiod_tp_id = t.tp_id OR s.timeperiod_tp_id2 = t.tp_id) '
. $registerClause
. 'AND t.tp_name = "' . $this->db->escape($timeperiodName) . '" ';
try {
$result = $this->db->query($query);
} catch (PDOException $e) {
throw new Exception('Error while getting linked services of ' . $timeperiodName);
}
while ($row = $result->fetchRow()) {
$linkedServices[] = $row['service_description'];
}
return $linkedServices;
}
/**
* Returns array of Contacts linked to the timeperiod
*
* @param string $timeperiodName
* @throws Exception
* @return array
*/
public function getLinkedContactsByName($timeperiodName)
{
$linkedContacts = [];
$query = 'SELECT DISTINCT c.contact_name '
. 'FROM contact c, timeperiod t '
. 'WHERE (c.timeperiod_tp_id = t.tp_id OR c.timeperiod_tp_id2 = t.tp_id) '
. 'AND t.tp_name = "' . $this->db->escape($timeperiodName) . '" ';
try {
$result = $this->db->query($query);
} catch (PDOException $e) {
throw new Exception('Error while getting linked contacts of ' . $timeperiodName);
}
while ($row = $result->fetchRow()) {
$linkedContacts[] = $row['contact_name'];
}
return $linkedContacts;
}
/**
* Returns array of Timeperiods linked to the timeperiod
*
* @param string $timeperiodName
* @throws Exception
* @return array
*/
public function getLinkedTimeperiodsByName($timeperiodName)
{
$linkedTimeperiods = [];
$query = 'SELECT DISTINCT t1.tp_name '
. 'FROM timeperiod t1, timeperiod_include_relations tir1, timeperiod t2 '
. 'WHERE t1.tp_id = tir1.timeperiod_id '
. 'AND t2.tp_id = tir1.timeperiod_include_id '
. 'AND t2.tp_name = "' . $this->db->escape($timeperiodName) . '" '
. 'UNION '
. 'SELECT DISTINCT t3.tp_name '
. 'FROM timeperiod t3, timeperiod_include_relations tir2, timeperiod t4 '
. 'WHERE t3.tp_id = tir2.timeperiod_include_id '
. 'AND t4.tp_id = tir2.timeperiod_id '
. 'AND t4.tp_name = "' . $this->db->escape($timeperiodName) . '" ';
try {
$result = $this->db->query($query);
} catch (PDOException $e) {
throw new Exception('Error while getting linked timeperiods of ' . $timeperiodName);
}
while ($row = $result->fetchRow()) {
$linkedTimeperiods[] = $row['tp_name'];
}
return $linkedTimeperiods;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonDowntime.class.php | centreon/www/class/centreonDowntime.class.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
*
*/
/**
* Class
*
* @class CentreonDowntime
* @description Class for cycle downtime management
*/
class CentreonDowntime
{
private const HOST_DOWNTIME = 'h';
private const SERVICE_DOWNTIME = 's';
private const TYPE_HOST = 'host';
private const TYPE_SERVICE = 'svc';
private const TYPE_HOST_GROUP = 'hostgrp';
private const TYPE_SERVICE_GROUP = 'svcgrp';
private const SERVICE_REGISTER_SERVICE_TEMPLATE = 0;
/** @var CentreonDB */
protected CentreonDB $db;
// $safe is the key to be bound
/** @var string */
protected string $search = '';
// $safeSearch is the value to bind in the prepared statement
/** @var string */
protected string $safeSearch = '';
/** @var int|null */
protected ?int $nbRows = null;
/** @var array */
protected array $remoteCommands = [];
/** @var string */
protected string $remoteCmdDir = '';
/** @var array|null */
protected ?array $periods = null;
/** @var array|null */
protected ?array $downtimes = null;
/**
* CentreonDowntime constructor
*
* @param CentreonDB $pearDB The connection to database centreon
* @param string|null $varlib Centreon dynamic dir
*/
public function __construct(CentreonDB $pearDB, ?string $varlib = null)
{
$this->db = $pearDB;
if (! is_null($varlib)) {
$this->remoteCmdDir = $varlib . '/centcore';
}
}
/**
* @throws PDOException
* @return void
*/
public function initPeriods(): void
{
if (! is_null($this->periods)) {
return;
}
$this->periods = [];
$statement = $this->db->query(
<<<'SQL'
SELECT dt_id, dtp_start_time, dtp_end_time, dtp_day_of_week, dtp_month_cycle,
dtp_day_of_month, dtp_fixed, dtp_duration
FROM downtime_period
SQL
);
while ($row = $statement->fetch()) {
$this->periods[$row['dt_id']][] = $row;
}
}
/**
* Set the string to filter the results
*
* The string search is set to filter
* In SQL, the string is "%$search%"
*
* @param string $search The string for filter
*/
public function setSearch(string $search = ''): void
{
$this->safeSearch = '';
if ($search !== '') {
$this->safeSearch = htmlentities($search, ENT_QUOTES, 'UTF-8');
$this->search = 'dt_name LIKE :search';
}
}
/**
* Get the number of rows to display, when a search filter is applied
*
* @return int The number of rows
*/
public function getNbRows(): int
{
// Get the number of rows if getList is call before
if (! is_null($this->nbRows)) {
return $this->nbRows;
}
$query = 'SELECT COUNT(*) FROM downtime';
if ($this->search) {
$query .= ' WHERE dt_name LIKE :search';
}
try {
$res = $this->db->prepare($query);
if ($this->search) {
$res->bindValue(':search', '%' . $this->safeSearch . '%');
}
$res->execute();
} catch (Throwable) {
return 0;
}
return (int) $res->fetchColumn();
}
/**
* Get the list of downtime, with applied search filter
*
* <code>
* $return_array =
* array(
* array(
* 'dt_id' => int, // The downtime id
* 'dt_name' => string, // The downtime name
* 'dt_description' => string, // The downtime description
* 'dt_activate' => int // 0 Downtime is deactivated, 1 Downtime is activated
* ),...
* )
* </code>
*
* @param int $num The page number
* @param int $limit The limit by page for pagination
* @param string|null $type The type of downtime (h: host, s: service)
*
* @throws PDOException
* @return array<array{
* dt_id: int,
* dt_name: string,
* dt_description: string,
* dt_activate: string
* }> The list of downtime
*/
public function getList(int $num, int $limit, ?string $type = null): array
{
$fromRecord = $num * $limit;
$searchSubRequest = $this->search !== '' ? 'AND ' . $this->search : '';
if ($type === self::HOST_DOWNTIME) {
$statement = $this->db->prepare(
<<<SQL
SELECT SQL_CALC_FOUND_ROWS dt_id, dt_name, dt_description, dt_activate
FROM downtime
WHERE (
downtime.dt_id IN(SELECT dt_id FROM downtime_host_relation)
OR downtime.dt_id IN (SELECT dt_id FROM downtime_hostgroup_relation))
{$searchSubRequest}
ORDER BY dt_name
LIMIT :from, :limit
SQL
);
} elseif ($type == self::SERVICE_DOWNTIME) {
$statement = $this->db->prepare(
<<<SQL
SELECT SQL_CALC_FOUND_ROWS dt_id, dt_name, dt_description, dt_activate
FROM downtime
WHERE (
downtime.dt_id IN (SELECT dt_id FROM downtime_service_relation)
OR downtime.dt_id IN (SELECT dt_id FROM downtime_servicegroup_relation))
{$searchSubRequest}
ORDER BY dt_name
LIMIT :from, :limit
SQL
);
} else {
$searchSubRequest = $this->search !== '' ? 'WHERE ' . $this->search : '';
$statement = $this->db->prepare(
<<<SQL
SELECT SQL_CALC_FOUND_ROWS dt_id, dt_name, dt_description, dt_activate
FROM downtime
{$searchSubRequest}
ORDER BY dt_name
LIMIT :from, :limit
SQL
);
}
try {
if (! empty($this->safeSearch)) {
$statement->bindValue(':search', '%' . $this->safeSearch . '%');
}
$statement->bindValue(':from', $fromRecord, PDO::PARAM_INT);
$statement->bindValue(':limit', $limit, PDO::PARAM_INT);
$statement->execute();
} catch (Throwable) {
return [];
}
$list = [];
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach ($statement as $row) {
$list[] = $row;
}
$result = $this->db->query('SELECT FOUND_ROWS()');
$this->nbRows = $result->fetchColumn();
return $list;
}
/**
* @param $id
*
* @throws PDOException
* @return array
*/
public function getPeriods($id)
{
$this->initPeriods();
$periods = [];
if (! isset($this->periods[$id])) {
return $periods;
}
foreach ($this->periods[$id] as $period) {
$days = $period['dtp_day_of_week'];
// Make a array if the cycle is all
if ($period['dtp_month_cycle'] == 'all') {
$days = preg_split('/\,/', $days);
}
// Convert HH:mm:ss to HH:mm
$start_time = substr($period['dtp_start_time'], 0, strrpos($period['dtp_start_time'], ':'));
$end_time = substr($period['dtp_end_time'], 0, strrpos($period['dtp_end_time'], ':'));
$periods[] = ['start_time' => $start_time, 'end_time' => $end_time, 'day_of_week' => $days, 'month_cycle' => $period['dtp_month_cycle'], 'day_of_month' => preg_split('/\,/', $period['dtp_day_of_month']), 'fixed' => $period['dtp_fixed'], 'duration' => $period['dtp_duration']];
}
return $periods;
}
/**
* Get DownTime information
*
* @param int $id The downtime id
*
* @return array{
* name: string,
* description: string,
* activate: string
* } Downtime information
*/
public function getInfos(int $id): array
{
try {
$res = $this->db->prepare('SELECT dt_name, dt_description, dt_activate FROM downtime WHERE dt_id = :id');
$res->bindValue(':id', $id, PDO::PARAM_INT);
$res->execute();
} catch (PDOException) {
return [
'name' => '',
'description' => '',
'activate' => '',
];
}
$row = $res->fetch();
return ['name' => $row['dt_name'], 'description' => $row['dt_description'], 'activate' => $row['dt_activate']];
}
/**
* Intends to return hosts, hostgroups, services, servicesgroups linked to the recurrent downtime
*
* @param int $downtimeId
*
* @throws PDOException
* @return array<string, array<int, array{id: string, activated: '0'|'1'}>>
*/
public function getRelations(int $downtimeId): array
{
$relations = [
'hosts' => [],
'hostgroups' => [],
'services' => [],
'servicegroups' => [],
];
foreach (array_keys($relations) as $resourceType) {
switch ($resourceType) {
case 'hosts':
$query = <<<'SQL'
SELECT
dhr.host_host_id AS resource_id,
h.host_activate AS activated
FROM downtime_host_relation dhr
INNER JOIN host h
ON dhr.host_host_id = h.host_id
WHERE
dt_id = :downtimeId;
SQL;
break;
case 'hostgroups':
$query = <<<'SQL'
SELECT
dhgr.hg_hg_id AS resource_id,
hg.hg_activate AS activated
FROM downtime_hostgroup_relation dhgr
INNER JOIN hostgroup hg
ON dhgr.hg_hg_id = hg.hg_id
WHERE
dt_id = :downtimeId;
SQL;
break;
case 'services':
$query = <<<'SQL'
SELECT CONCAT(dsr.host_host_id, CONCAT('-', dsr.service_service_id)) AS resource_id,
s.service_activate AS activated
FROM downtime_service_relation dsr
INNER JOIN service s
ON dsr.service_service_id = s.service_id
WHERE
dt_id = :downtimeId;
SQL;
break;
case 'servicegroups':
$query = <<<'SQL'
SELECT
dsgr.sg_sg_id AS resource_id,
sg.sg_activate AS activated
FROM downtime_servicegroup_relation dsgr
INNER JOIN servicegroup sg
ON dsgr.sg_sg_id = sg.sg_id
WHERE
dt_id = :downtimeId;
SQL;
break;
}
$statement = $this->db->prepare($query);
$statement->bindValue(':downtimeId', $downtimeId, PDO::PARAM_INT);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$statement->execute();
foreach ($statement as $record) {
$relations[$resourceType][] = [
'id' => $record['resource_id'],
'activated' => $record['activated'],
];
}
$statement->closeCursor();
}
return $relations;
}
/**
* Returns all downtimes configured for enabled hosts
*
* @throws PDOException
* @return array
*/
public function getForEnabledHosts(): array
{
$downtimes = [];
$request = <<<'SQL'
SELECT dt.dt_id,
dt.dt_activate,
dtp.dtp_start_time,
dtp.dtp_end_time,
dtp.dtp_day_of_week,
dtp.dtp_month_cycle,
dtp.dtp_day_of_month,
dtp.dtp_fixed,
dtp.dtp_duration,
h.host_id,
h.host_name,
NULL as service_id,
NULL as service_description
FROM downtime_period dtp
INNER JOIN downtime dt
ON dtp.dt_id = dt.dt_id
INNER JOIN downtime_host_relation dtr
ON dtp.dt_id = dtr.dt_id
INNER JOIN host h
ON dtr.host_host_id = h.host_id
WHERE h.host_activate = '1'
SQL;
$statement = $this->db->query($request);
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
$downtimes[] = $record;
}
return $downtimes;
}
/**
* Returns all downtimes configured for enabled services
*
* @throws PDOException
* @return array
*/
public function getForEnabledServices(): array
{
$downtimes = [];
$request = <<<'SQL'
SELECT dt.dt_id,
dt.dt_activate,
dtp.dtp_start_time,
dtp.dtp_end_time,
dtp.dtp_day_of_week,
dtp.dtp_month_cycle,
dtp.dtp_day_of_month,
dtp.dtp_fixed,
dtp.dtp_duration,
h.host_id,
h.host_name,
s.service_id,
s.service_description
FROM downtime_period dtp
INNER JOIN downtime dt
ON dtp.dt_id = dt.dt_id
INNER JOIN downtime_service_relation dtr
ON dtp.dt_id = dtr.dt_id
INNER JOIN service s
ON dtr.service_service_id = s.service_id
INNER JOIN host_service_relation hsr
ON hsr.service_service_id = s.service_id
INNER JOIN host h
ON hsr.host_host_id = h.host_id
AND h.host_id = dtr.host_host_id
WHERE s.service_activate = '1'
UNION
SELECT dt.dt_id,
dt.dt_activate,
dtp.dtp_start_time,
dtp.dtp_end_time,
dtp.dtp_day_of_week,
dtp.dtp_month_cycle,
dtp.dtp_day_of_month,
dtp.dtp_fixed,
dtp.dtp_duration,
s.service_description as obj_name,
dtr.service_service_id as obj_id,
h.host_name as host_name,
h.host_id
FROM downtime_period dtp
INNER JOIN downtime dt
ON dtp.dt_id = dt.dt_id
INNER JOIN downtime_service_relation dtr
ON dtp.dt_id = dtr.dt_id
INNER JOIN host h
ON dtr.host_host_id = h.host_id
INNER JOIN hostgroup_relation hgr
ON hgr.hostgroup_hg_id = h.host_id
INNER JOIN host_service_relation hsr
ON hsr.hostgroup_hg_id = hgr.hostgroup_hg_id
INNER JOIN service s
ON s.service_id = hsr.service_service_id
AND dtr.service_service_id = s.service_id
WHERE h.host_activate = '1'
SQL;
$statement = $this->db->query($request);
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
$downtimes[] = $record;
}
return $downtimes;
}
/**
* Returns all downtimes configured for enabled hostgroups
*
* @throws PDOException
* @return array
*/
public function getForEnabledHostgroups(): array
{
$downtimes = [];
$request = <<<'SQL'
SELECT dt.dt_id,
dt.dt_activate,
dtp.dtp_start_time,
dtp.dtp_end_time,
dtp.dtp_day_of_week,
dtp.dtp_month_cycle,
dtp.dtp_day_of_month,
dtp.dtp_fixed,
dtp.dtp_duration,
h.host_id,
h.host_name,
NULL as service_id,
NULL as service_description
FROM downtime_period dtp
INNER JOIN downtime dt
ON dtp.dt_id = dt.dt_id
INNER JOIN downtime_hostgroup_relation dhr
ON dtp.dt_id = dhr.dt_id
INNER JOIN hostgroup_relation hgr
ON dhr.hg_hg_id = hgr.hostgroup_hg_id
INNER JOIN host h
ON hgr.host_host_id = h.host_id
INNER JOIN hostgroup hg
ON hgr.hostgroup_hg_id = hg.hg_id
WHERE hg.hg_activate = '1'
SQL;
$statement = $this->db->query($request);
$statement->execute();
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
$downtimes[] = $record;
}
return $downtimes;
}
/**
* @throws PDOException
* @return array
*/
public function getForEnabledServicegroups()
{
$request = <<<'SQL'
SELECT dt.dt_id,
dt.dt_activate,
dtp.dtp_start_time,
dtp.dtp_end_time,
dtp.dtp_day_of_week,
dtp.dtp_month_cycle,
dtp.dtp_day_of_month,
dtp.dtp_fixed,
dtp.dtp_duration,
h.host_id,
h.host_name,
s.service_id,
s.service_description,
s.service_register
FROM downtime_period dtp
INNER JOIN downtime dt
ON dtp.dt_id = dt.dt_id
INNER JOIN downtime_servicegroup_relation dtr
ON dtp.dt_id = dtr.dt_id
INNER JOIN servicegroup_relation sgr
ON dtr.sg_sg_id = sgr.servicegroup_sg_id
INNER JOIN service s
ON sgr.service_service_id = s.service_id
INNER JOIN host h
ON sgr.host_host_id = h.host_id
INNER JOIN servicegroup sg
ON sgr.servicegroup_sg_id = sg.sg_id
WHERE sg.sg_activate = '1'
UNION DISTINCT
SELECT dt.dt_id,
dt.dt_activate,
dtp.dtp_start_time,
dtp.dtp_end_time,
dtp.dtp_day_of_week,
dtp.dtp_month_cycle,
dtp.dtp_day_of_month,
dtp.dtp_fixed,
dtp.dtp_duration,
h.host_id,
h.host_name,
s.service_id,
s.service_description,
s.service_register
FROM downtime_period dtp
INNER JOIN downtime dt
ON dtp.dt_id = dt.dt_id
INNER JOIN downtime_servicegroup_relation dtr
ON dtp.dt_id = dtr.dt_id
INNER JOIN servicegroup_relation sgr
ON dtr.sg_sg_id = sgr.servicegroup_sg_id
INNER JOIN host_service_relation hsr
ON sgr.hostgroup_hg_id = hsr.hostgroup_hg_id
INNER JOIN hostgroup_relation hgr
ON hsr.hostgroup_hg_id = hgr.hostgroup_hg_id
INNER JOIN service s
ON hsr.service_service_id = s.service_id
INNER JOIN host h
ON hgr.host_host_id = h.host_id
WHERE sgr.hostgroup_hg_id IS NOT NULL;
SQL;
$statement = $this->db->query($request);
$templateDowntimeInformation = [];
$downtimes = [];
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
if ((int) $record['service_register'] === self::SERVICE_REGISTER_SERVICE_TEMPLATE) {
$templateDowntimeInformation[(int) $record['service_id']] = [
'dt_id' => $record['dt_id'],
'dt_activate' => $record['dt_activate'],
'dtp_start_time' => $record['dtp_start_time'],
'dtp_end_time' => $record['dtp_end_time'],
'dtp_day_of_week' => $record['dtp_day_of_week'],
'dtp_month_cycle' => $record['dtp_month_cycle'],
'dtp_day_of_month' => $record['dtp_day_of_month'],
'dtp_fixed' => $record['dtp_fixed'],
'dtp_duration' => $record['dtp_duration'],
];
} else {
$downtimes[] = $record;
}
}
if ($templateDowntimeInformation !== []) {
foreach ($this->findServicesByServiceTemplateIds(array_keys($templateDowntimeInformation)) as $service) {
$downtimes[] = array_merge(
$templateDowntimeInformation[$service['service_template_model_stm_id']],
[
'host_id' => $service['host_id'],
'host_name' => $service['host_name'],
'service_id' => $service['service_id'],
'service_description' => $service['service_description'],
]
);
}
}
return $downtimes;
}
/**
* Get the list of all downtimes
*
* @throws PDOException
* @return array All downtimes
*/
public function getForEnabledResources()
{
if (! is_null($this->downtimes)) {
return $this->downtimes;
}
$downtimes = array_merge(
$this->getForEnabledHosts(),
$this->getForEnabledServices(),
$this->getForEnabledServicegroups(),
$this->getForEnabledHostgroups()
);
// Remove duplicate downtimes
$downtimes = array_intersect_key($downtimes, array_unique(array_map('serialize', $downtimes)));
sort($downtimes);
$this->downtimes = $downtimes;
return $this->downtimes;
}
/**
* The duplicate one or many downtime, with periods
*
* @param array $ids The list of downtime id to replicate
* @param array $nb The list of number of duplicate by downtime id
*
* @throws PDOException
*/
public function duplicate($ids, $nb): void
{
$ids = is_array($ids) === false ? [$ids] : array_keys($ids);
foreach ($ids as $id) {
if (isset($nb[$id])) {
$query = 'SELECT dt_id, dt_name, dt_description, dt_activate FROM downtime WHERE dt_id = :id';
try {
$statement = $this->db->prepare($query);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$statement->execute();
} catch (PDOException) {
return;
}
$row = $statement->fetch(PDO::FETCH_ASSOC);
$index = 1;
$i = 1;
while ($i <= $nb[$id]) {
if (! $this->downtimeExists($row['dt_name'] . '_' . $index)) {
$row['index'] = $index;
$this->duplicateDowntime($row);
$i++;
}
$index++;
}
}
}
}
/**
* Add a downtime
*
* @param string $name The downtime name
* @param string $desc The downtime description
* @param int $activate If the downtime is activated (0 Downtime is deactivated, 1 Downtime is activated)
* @return bool|int The id of downtime or false if in error
*/
public function add(string $name, string $desc, $activate): bool|int
{
if ($desc == '') {
$desc = $name;
}
$query = 'INSERT INTO downtime (dt_name, dt_description, dt_activate) VALUES (:name, :desc, :activate)';
try {
$statement = $this->db->prepare($query);
$statement->bindParam(':name', $name, PDO::PARAM_STR);
$statement->bindParam(':desc', $desc, PDO::PARAM_STR);
$statement->bindParam(':activate', $activate, PDO::PARAM_STR);
$statement->execute();
} catch (PDOException $e) {
return false;
}
$query = 'SELECT dt_id FROM downtime WHERE dt_name = :name';
$error = false;
try {
$statement = $this->db->prepare($query);
$statement->bindParam(':name', $name, PDO::PARAM_STR);
$statement->execute();
} catch (PDOException $e) {
$error = true;
}
if ($error || $statement->rowCount() == 0) {
return false;
}
$row = $statement->fetch(PDO::FETCH_ASSOC);
return $row['dt_id'];
}
/**
* Modify a downtime
*
* @param int $id The downtime id
* @param string $name The downtime name
* @param string $desc The downtime description
* @param string $activate If the downtime is activated (0 Downtime is deactivated, 1 Downtime is activated)
*
* @throws PDOException
*/
public function modify(int $id, string $name, string $desc, string $activate): void
{
if ($desc == '') {
$desc = $name;
}
$updateQuery = <<<'SQL'
UPDATE downtime SET
dt_name = :name,
dt_description = :desc,
dt_activate = :activate
WHERE dt_id = :id
SQL;
$statement = $this->db->prepare($updateQuery);
$statement->bindValue(':name', $name, PDO::PARAM_STR);
$statement->bindValue(':desc', $desc, PDO::PARAM_STR);
$statement->bindValue(':activate', $activate, PDO::PARAM_STR);
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
}
/**
* Add a period to a downtime
*
* <code>
* $infos =
* array(
* 'start_period' => string, // The start time of the period (HH:mm)
* 'end_period' => string, // The end time of the period (HH:mm)
* 'days' => array, // The days in week, it is a array with the day number in the week (1 to 7)
* // if month_cycle is all, first or last
* // The days of month if month_cycle is none
* 'month_cycle' => string, // The cycle method (all: all in month, first: first in month, last: last in month
* // , none: only the day of the month)
* 'fixed' => int, // If the downtime is fixed (0: flexible, 1: fixed)
* 'duration' => int, // If the downtime is fexible, the duration of the downtime
* )
* </code>
*
* @param int $id Downtime id
* @param array $infos The information for a downtime period
*
* @throws PDOException
*/
public function addPeriod(int $id, array $infos): void
{
if (trim($infos['duration']) !== '') {
$infos['duration'] = match (trim($infos['scale'])) {
'm' => $infos['duration'] * 60,
'h' => $infos['duration'] * 60 * 60,
'd' => $infos['duration'] * 60 * 60 * 24,
default => (int) $infos['duration'],
};
} else {
$infos['duration'] = null;
}
if (! isset($infos['days'])) {
$infos['days'] = [];
}
$query = <<<'SQL'
INSERT INTO downtime_period (
dt_id, dtp_start_time, dtp_end_time, dtp_day_of_week, dtp_month_cycle,
dtp_day_of_month, dtp_fixed, dtp_duration
) VALUES (
:id, :start_time, :end_time, :days, :month_cycle, :day_of_month, :fixed, :duration
)
SQL;
$statement = $this->db->prepare($query);
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->bindValue(':start_time', $infos['start_period'], PDO::PARAM_STR);
$statement->bindValue(':end_time', $infos['end_period'], PDO::PARAM_STR);
$statement->bindValue(':fixed', $infos['fixed'], PDO::PARAM_STR);
$statement->bindValue(':duration', $infos['duration'], PDO::PARAM_INT);
switch ($infos['period_type']) {
case 'weekly_basis':
$statement->bindValue(':days', implode(',', $infos['days']), PDO::PARAM_STR);
$statement->bindValue(':month_cycle', 'all', PDO::PARAM_STR);
$statement->bindValue(':day_of_month', null, PDO::PARAM_NULL);
break;
case 'monthly_basis':
$statement->bindValue(':days', null, PDO::PARAM_STR);
$statement->bindValue(':month_cycle', 'none', PDO::PARAM_STR);
$statement->bindValue(':day_of_month', implode(',', $infos['days']), PDO::PARAM_STR);
break;
case 'specific_date':
$statement->bindValue(':days', $infos['days'], PDO::PARAM_STR);
$statement->bindValue(':month_cycle', $infos['month_cycle'], PDO::PARAM_STR);
$statement->bindValue(':day_of_month', null, PDO::PARAM_NULL);
break;
}
$statement->execute();
}
/**
* Delete all periods for a downtime
*
* @param int $id The downtime id
*
* @throws PDOException
*/
public function deletePeriods(int $id): void
{
$stmt = $this->db->prepare('DELETE FROM downtime_period WHERE dt_id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
}
/**
* Add relations for downtime
*
* @param int $id The downtime id
* @param array $objIds The list of object id
* @param string $objType The object type (host, hostgrp, svc, svcgrp)
*
* @throws PDOException
*/
public function addRelations(int $id, array $objIds, string $objType): void
{
$statement = match($objType) {
self::TYPE_HOST => $this->db->prepare(
'INSERT INTO downtime_host_relation (dt_id, host_host_id) VALUES (:id, :obj_id)'
),
self::TYPE_HOST_GROUP => $this->db->prepare(
'INSERT INTO downtime_hostgroup_relation (dt_id, hg_hg_id) VALUES (:id, :obj_id)'
),
self::TYPE_SERVICE => $this->db->prepare(
<<<'SQL'
INSERT INTO downtime_service_relation (dt_id, host_host_id, service_service_id)
VALUES (:id, :host_id, :service_id)
SQL
),
self::TYPE_SERVICE_GROUP => $this->db->prepare(
'INSERT INTO downtime_servicegroup_relation (dt_id, sg_sg_id) VALUES (:id, :obj_id)'
),
default => null,
};
if ($statement === null) {
return;
}
$isAlreadyInTransaction = $this->db->inTransaction();
if (! $isAlreadyInTransaction) {
$this->db->beginTransaction();
}
try {
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonLog.class.php | centreon/www/class/centreonLog.class.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\Infrastructure\ExceptionLogger\ExceptionLogFormatter;
use Psr\Log\LogLevel;
/**
* Class
*
* @class CentreonUserLog
*/
class CentreonUserLog
{
public const TYPE_LOGIN = 1;
public const TYPE_SQL = 2;
public const TYPE_LDAP = 3;
public const TYPE_UPGRADE = 4;
/** @var CentreonUserLog */
private static $instance;
/** @var array */
private $errorType = [];
/** @var int */
private $uid;
/** @var string */
private $path;
/**
* CentreonUserLog constructor
*
* @param int $uid
* @param CentreonDB $pearDB
*
* @throws PDOException
*/
public function __construct($uid, $pearDB)
{
$this->uid = $uid;
// Get Log directory path
$DBRESULT = $pearDB->query("SELECT * FROM `options` WHERE `key` = 'debug_path'");
while ($res = $DBRESULT->fetchRow()) {
$optGen[$res['key']] = $res['value'];
}
$DBRESULT->closeCursor();
// Init log Directory
$this->path = (isset($optGen['debug_path']) && ! empty($optGen['debug_path']))
? $optGen['debug_path'] : _CENTREON_LOG_;
$this->errorType[self::TYPE_LOGIN] = $this->path . '/login.log';
$this->errorType[self::TYPE_SQL] = $this->path . '/sql-error.log';
$this->errorType[self::TYPE_LDAP] = $this->path . '/ldap.log';
$this->errorType[self::TYPE_UPGRADE] = $this->path . '/upgrade.log';
}
/**
* @param int $id
* @param string $str
* @param int $print
* @param int $page
* @param int $option
* @return void
*/
public function insertLog($id, $str, $print = 0, $page = 0, $option = 0): void
{
/*
* Construct alert message
* Take care before modifying this message pattern as it may break tools such as fail2ban
*/
$string = date('Y-m-d H:i:s') . '|' . $this->uid . "|{$page}|{$option}|{$str}";
// Display error on Standard exit
if ($print) {
echo htmlspecialchars($str);
}
// Replace special char
$string = str_replace('`', '', $string);
$string = str_replace('*', "\*", $string);
// Write Error in log file.
file_put_contents($this->errorType[$id], $string . "\n", FILE_APPEND);
}
/**
* @param int $uid
* @return void
*/
public function setUID($uid): void
{
$this->uid = $uid;
}
/**
* Singleton
*
* @param int $uid The user id
* @throws Exception
* @return CentreonUserLog
*/
public static function singleton($uid = 0)
{
if (is_null(self::$instance)) {
self::$instance = new CentreonUserLog($uid, CentreonDB::factory('centreon'));
}
return self::$instance;
}
}
/**
* Class
*
* @class CentreonLog
*/
class CentreonLog
{
/**
* Level Types from \Psr\Log\LogLevel
*/
public const LEVEL_DEBUG = LogLevel::DEBUG;
public const LEVEL_NOTICE = LogLevel::NOTICE;
public const LEVEL_INFO = LogLevel::INFO;
public const LEVEL_WARNING = LogLevel::WARNING;
public const LEVEL_ERROR = LogLevel::ERROR;
public const LEVEL_CRITICAL = LogLevel::CRITICAL;
public const LEVEL_ALERT = LogLevel::ALERT;
public const LEVEL_EMERGENCY = LogLevel::EMERGENCY;
/**
* Log files
*/
public const TYPE_LOGIN = 1;
public const TYPE_SQL = 2;
public const TYPE_LDAP = 3;
public const TYPE_UPGRADE = 4;
public const TYPE_PLUGIN_PACK_MANAGER = 5;
public const TYPE_BUSINESS_LOG = 6;
private const DEFAULT_LOG_FILES = [
self::TYPE_LOGIN => 'login.log',
self::TYPE_SQL => 'sql-error.log',
self::TYPE_LDAP => 'ldap.log',
self::TYPE_UPGRADE => 'upgrade.log',
self::TYPE_PLUGIN_PACK_MANAGER => 'plugin-pack-manager.log',
self::TYPE_BUSINESS_LOG => 'centreon-web.log',
];
/** @var array<int,string> */
private array $logFileHandler;
/** @var string */
private string $pathLogFile;
/**
* CentreonLog constructor
*
* @param array $customLogFiles
* @param string $pathLogFile
*/
public function __construct(array $customLogFiles = [], string $pathLogFile = '')
{
$this->setPathLogFile(empty($pathLogFile) ? _CENTREON_LOG_ : $pathLogFile);
// push default logs in log file handler
foreach (self::DEFAULT_LOG_FILES as $logTypeId => $logFileName) {
$this->pushLogFileHandler($logTypeId, $logFileName);
}
// push custom logs in log file handler
foreach ($customLogFiles as $logTypeId => $logFileName) {
$this->pushLogFileHandler($logTypeId, $logFileName);
}
}
/**
* Factory
* @param array $customLogs
* @param string $pathLogFile
* @return CentreonLog
*/
public static function create(array $customLogs = [], string $pathLogFile = ''): CentreonLog
{
return new CentreonLog($customLogs, $pathLogFile);
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $level LEVEL_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function log(
int $logTypeId,
string $level,
string $message,
array $customContext = [],
?Throwable $exception = null,
): void {
if (! empty($message)) {
$jsonContext = $this->serializeContext($customContext, $exception);
$level = (empty($level)) ? strtoupper(self::LEVEL_ERROR) : strtoupper($level);
$date = (new DateTime())->format(DateTimeInterface::RFC3339);
$log = sprintf('[%s] %s : %s | %s', $date, $level, $message, $jsonContext);
$response = file_put_contents($this->logFileHandler[$logTypeId], $log . "\n", FILE_APPEND);
}
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function debug(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_DEBUG, $message, $customContext, $exception);
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function notice(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_NOTICE, $message, $customContext, $exception);
}
/**
* @param int $logTypeId TYPE_ * constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function info(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_INFO, $message, $customContext, $exception);
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function warning(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_WARNING, $message, $customContext, $exception);
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function error(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_ERROR, $message, $customContext, $exception);
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function critical(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_CRITICAL, $message, $customContext, $exception);
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function alert(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_ALERT, $message, $customContext, $exception);
}
/**
* @param int $logTypeId TYPE_* constants
* @param string $message
* @param array $customContext
* @param Throwable|null $exception
* @return void
*/
public function emergency(int $logTypeId, string $message, array $customContext = [], ?Throwable $exception = null): void
{
$this->log($logTypeId, self::LEVEL_EMERGENCY, $message, $customContext, $exception);
}
/**
* @return array
*/
public function getLogFileHandler(): array
{
return $this->logFileHandler;
}
/**
* @param int $logTypeId
* @param string $logFileName
* @return CentreonLog
*/
public function pushLogFileHandler(int $logTypeId, string $logFileName): CentreonLog
{
$pathLogFileName = '';
$logFile = '';
$explodeFileName = explode(DIRECTORY_SEPARATOR, $logFileName);
if ($explodeFileName !== []) {
$logFile = $explodeFileName[count($explodeFileName) - 1];
unset($explodeFileName[count($explodeFileName) - 1]);
$pathLogFileName = implode(DIRECTORY_SEPARATOR, $explodeFileName);
}
$this->logFileHandler[$logTypeId] = ($pathLogFileName !== $this->pathLogFile)
? $this->pathLogFile . '/' . $logFile : $logFileName;
return $this;
}
/**
* @param string $pathLogFile
* @return CentreonLog
*/
public function setPathLogFile(string $pathLogFile): CentreonLog
{
$this->pathLogFile = $pathLogFile;
return $this;
}
// *********************************************** DEPRECATED *****************************************************//
/**
* @param int $id
* @param string $str
* @param int $print
* @param int $page
* @param int $option
* @return void
* @deprecated Instead used {@see CentreonLog::log()}
*/
public function insertLog($id, $str, $print = 0, $page = 0, $option = 0): void
{
$message = "{$page}|{$option}|{$str}";
if ($print) {
echo $str;
}
$this->log(logTypeId: $id, level: self::LEVEL_ERROR, message: $message);
}
/**
* @param array $customContext
* @param Throwable|null $exception
* @return string
*/
private function serializeContext(array $customContext, ?Throwable $exception = null): string
{
try {
$exceptionContext = [];
// Add default context with back trace and request infos
$defaultContext = [
'request_infos' => [
'uri' => isset($_SERVER['REQUEST_URI']) ? urldecode($_SERVER['REQUEST_URI']) : null,
'http_method' => $_SERVER['REQUEST_METHOD'] ?? null,
'server' => $_SERVER['SERVER_NAME'] ?? null,
],
];
// Add exception context with previous exception if exists
if (! is_null($exception)) {
$exceptionLogContext = ExceptionLogFormatter::format($customContext, $exception);
$exceptionContext = $exceptionLogContext['exception'] ?? null;
if (array_key_exists('exception', $exceptionLogContext)) {
unset($exceptionLogContext['exception']);
}
$customContext = $exceptionLogContext;
}
$context = [
'custom' => $customContext !== [] ? $customContext : null,
'exception' => $exceptionContext !== [] ? $exceptionContext : null,
'default' => $defaultContext,
];
return json_encode(
$context,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
} catch (JsonException $e) {
return sprintf(
'context: error while json encoding (JsonException: %s)',
$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/class/centreonNotification.class.php | centreon/www/class/centreonNotification.class.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
*
*/
/**
* Class
*
* @class CentreonNotification
*/
class CentreonNotification
{
public const HOST = 0;
public const SVC = 1;
public const HOST_ESC = 2;
public const SVC_ESC = 3;
/** @var CentreonDB */
protected $db;
/** @var array */
protected $svcTpl = [];
/** @var array */
protected $svcNotifType = [];
/** @var array */
protected $svcBreak = [1 => false, 2 => false];
/** @var array */
protected $hostNotifType = [];
/** @var array */
protected $notifiedHosts = [];
/** @var array */
protected $hostBreak = [1 => false, 2 => false];
/**
* CentreonNotification constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Get list of contact
*
* @throws PDOException
* @return array
*/
public function getList()
{
$sql = 'SELECT contact_id, contact_alias FROM contact ORDER BY contact_name';
$res = $this->db->query($sql);
$tab = [];
while ($row = $res->fetchRow()) {
$tab[$row['contact_id']] = $row['contact_alias'];
}
return $tab;
}
/**
* Get contact groups
*
* @param int $contactGroupId
*
* @throws PDOException
* @return array
*/
public function getContactGroupsById($contactGroupId)
{
$sql = 'SELECT cg_id, cg_name
FROM contactgroup cg
WHERE cg.cg_id = ' . $this->db->escape($contactGroupId);
$res = $this->db->query($sql);
$tab = [];
while ($row = $res->fetchRow()) {
$tab[$row['cg_id']] = $row['cg_name'];
}
return $tab;
}
/**
* Get contact groups
*
* @param int $contactId
*
* @throws PDOException
* @return array
*/
public function getContactGroups($contactId)
{
$sql = 'SELECT cg_id, cg_name
FROM contactgroup cg, contactgroup_contact_relation ccr
WHERE cg.cg_id = ccr.contactgroup_cg_id
AND ccr.contact_contact_id = ' . $contactId;
$res = $this->db->query($sql);
$tab = [];
while ($row = $res->fetchRow()) {
$tab[$row['cg_id']] = $row['cg_name'];
}
return $tab;
}
/**
* Get notifications
*
* @param int $notifType 0 for Hosts, 1 for Services, 2 for Host Escalations, 3 for Service Escalations
* @param int $contactId
*
* @throws PDOException
* @return array
*/
public function getNotifications($notifType, $contactId)
{
$contactId = $this->db->escape($contactId);
if ($this->isNotificationEnabled($contactId) === false) {
return [];
}
$contactgroups = $this->getContactGroups($contactId);
if ($notifType == self::HOST) {
$resources = $this->getHostNotifications($contactId, $contactgroups);
} elseif ($notifType == self::SVC) {
$resources = $this->getServiceNotifications($contactId, $contactgroups);
} elseif ($notifType == self::HOST_ESC || $notifType == self::SVC_ESC) {
$resources = $this->getEscalationNotifications($notifType, $contactgroups);
}
return $resources;
}
/**
* Get notifications
*
* @param int $notifType 0 for Hosts, 1 for Services, 2 for Host Escalations, 3 for Service Escalations
* @param int $contactgroupId
*
* @throws PDOException
* @return array
*/
public function getNotificationsContactGroup($notifType, $contactgroupId)
{
/*if (false === $this->isNotificationEnabled($contactId)) {
return array();
}*/
$contactgroups = $this->getContactGroupsById($contactgroupId);
if ($notifType == self::HOST) {
$resources = $this->getHostNotifications(-1, $contactgroups);
} elseif ($notifType == self::SVC) {
$resources = $this->getServiceNotifications(-1, $contactgroups);
} elseif ($notifType == self::HOST_ESC || $notifType == self::SVC_ESC) {
$resources = $this->getEscalationNotifications($notifType, $contactgroups);
}
return $resources;
}
/**
* Checks if notification is enabled
*
* @param int $contactId
*
* @throws PDOException
* @return bool true if notification is enabled, false otherwise
*/
protected function isNotificationEnabled($contactId)
{
$sql = 'SELECT contact_enable_notifications FROM contact WHERE contact_id = ' . $contactId;
$res = $this->db->query($sql);
if ($res->rowCount()) {
$row = $res->fetchRow();
if ($row['contact_enable_notifications']) {
return true;
}
}
return false;
}
/**
* Get host escalatiosn
*
* @param array $escalations
*
* @throws PDOException
* @return array
*/
protected function getHostEscalations($escalations)
{
$escalations = implode(',', array_keys($escalations));
$sql = 'SELECT h.host_id, h.host_name
FROM escalation_host_relation ehr, host h
WHERE h.host_id = ehr.host_host_id
AND ehr.escalation_esc_id IN (' . $escalations . ')
UNION
SELECT h.host_id, h.host_name
FROM escalation_hostgroup_relation ehr, hostgroup_relation hgr, host h
WHERE ehr.hostgroup_hg_id = hgr.hostgroup_hg_id
AND hgr.host_host_id = h.host_id
AND ehr.escalation_esc_id IN (' . $escalations . ')';
$res = $this->db->query($sql);
$tab = [];
while ($row = $res->fetchRow()) {
$tab[$row['host_id']] = $row['host_name'];
}
return $tab;
}
/**
* Get service escalations
*
* @param array $escalations
*
* @throws PDOException
* @return array
*/
protected function getServiceEscalations($escalations)
{
$escalationsList = implode('', array_keys($escalations));
$sql = 'SELECT h.host_id, h.host_name, s.service_id, s.service_description
FROM escalation_service_relation esr, host h, service s
WHERE h.host_id = esr.host_host_id
AND esr.service_service_id = s.service_id
AND esr.escalation_esc_id IN (' . $escalationsList . ')
UNION
SELECT h.host_id, h.host_name, s.service_id, s.service_description
FROM escalation_servicegroup_relation esr, servicegroup_relation sgr, host h, service s
WHERE esr.servicegroup_sg_id = sgr.servicegroup_sg_id
AND sgr.host_host_id = h.host_id
AND sgr.service_service_id = s.service_id
AND esr.escalation_esc_id IN (' . $escalationsList . ')';
$res = $this->db->query($sql);
$tab = [];
while ($row = $res->fetchRow()) {
if (! isset($tab[$row['host_id']])) {
$tab[$row['host_id']] = [];
}
$tab[$row['host_id']][$row['service_id']]['host_name'] = $row['host_name'];
$tab[$row['host_id']][$row['service_id']]['service_description'] = $row['service_description'];
}
return $tab;
}
/**
* Get escalation notifications
*
* @param $notifType
* @param array $contactgroups
*
* @throws PDOException
* @return array
*/
protected function getEscalationNotifications($notifType, $contactgroups)
{
if (! count($contactgroups)) {
return [];
}
$sql = 'SELECT ecr.escalation_esc_id, e.esc_name
FROM escalation_contactgroup_relation ecr, escalation e
WHERE e.esc_id = ecr.escalation_esc_id
AND ecr.contactgroup_cg_id IN (' . implode(',', array_keys($contactgroups)) . ')';
$res = $this->db->query($sql);
$escTab = [];
while ($row = $res->fetchRow()) {
$escTab[$row['escalation_esc_id']] = $row['esc_name'];
}
if ($escTab === []) {
return [];
}
if ($notifType == self::HOST_ESC) {
return $this->getHostEscalations($escTab);
}
return $this->getServiceEscalations($escTab);
}
/**
* Get Host Notifications
*
* @param int $contactId
* @param array $contactgroups
*
* @throws PDOException
* @return array
*/
protected function getHostNotifications($contactId, $contactgroups)
{
$sql = 'SELECT host_id, host_name, host_register, 1 as notif_type
FROM contact_host_relation chr, host h
WHERE chr.contact_id = ' . $contactId . '
AND chr.host_host_id = h.host_id ';
if (count($contactgroups)) {
$sql .= ' UNION
SELECT host_id, host_name, host_register, 2 as notif_type
FROM contactgroup_host_relation chr, host h
WHERE chr.contactgroup_cg_id IN (' . implode(',', array_keys($contactgroups)) . ')
AND chr.host_host_id = h.host_id ';
}
$res = $this->db->query($sql);
$this->notifiedHosts = [];
$templates = [];
while ($row = $res->fetchRow()) {
if ($row['host_register'] == 1) {
$this->notifiedHosts[$row['host_id']] = $row['host_name'];
} else {
$templates[$row['host_id']] = $row['host_name'];
$this->hostNotifType[$row['host_id']] = $row['notif_type'];
}
}
unset($res);
if ($this->notifiedHosts !== []) {
$sql2 = 'SELECT host_id, host_name
FROM host
WHERE host_id NOT IN (' . implode(',', array_keys($this->notifiedHosts)) . ") AND host_register = '1'";
} else {
$sql2 = "SELECT host_id, host_name FROM host WHERE host_register = '1'";
}
$res2 = $this->db->query(trim($sql2));
while ($row = $res2->fetchRow()) {
$this->hostBreak = [1 => false, 2 => false];
if ($this->getHostTemplateNotifications($row['host_id'], $templates) === true) {
$this->notifiedHosts[$row['host_id']] = $row['host_name'];
}
}
return $this->notifiedHosts;
}
/**
* Recursive method
*
* @param int $hostId
* @param array $templates
*
* @throws PDOException
* @return bool
*/
protected function getHostTemplateNotifications($hostId, $templates)
{
$sql = 'SELECT htr.host_tpl_id, ctr.contact_id, ctr2.contactgroup_cg_id
FROM host_template_relation htr
LEFT JOIN contact_host_relation ctr ON htr.host_host_id = ctr.host_host_id
LEFT JOIN contactgroup_host_relation ctr2 ON htr.host_host_id = ctr2.host_host_id
WHERE htr.host_host_id = :host_id
ORDER BY `order`';
$statement = $this->db->prepare($sql);
$statement->bindValue(':host_id', (int) $hostId, PDO::PARAM_INT);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
if ($row['contact_id']) {
$this->hostBreak[1] = true;
}
if ($row['contactgroup_cg_id']) {
$this->hostBreak[2] = true;
}
if (isset($templates[$row['host_tpl_id']])) {
if ($this->hostNotifType[$row['host_tpl_id']] == 1 && $this->hostBreak[1] == true) {
return false;
}
return ! ($this->hostNotifType[$row['host_tpl_id']] == 2 && $this->hostBreak[2] == true);
}
return $this->getHostTemplateNotifications($row['host_tpl_id'], $templates);
}
return false;
}
/**
* Get Service notifications
*
* @param int $contactId
* @param array $contactGroups
*
* @throws PDOException
* @return array
*/
protected function getServiceNotifications($contactId, $contactGroups)
{
$sql = 'SELECT h.host_id, h.host_name, s.service_id, s.service_description, s.service_register, 1 as notif_type
FROM contact_service_relation csr, service s
LEFT JOIN host_service_relation hsr ON hsr.service_service_id = s.service_id
LEFT JOIN host h ON h.host_id = hsr.host_host_id
WHERE csr.contact_id = ' . $contactId . "
AND csr.service_service_id = s.service_id
AND s.service_use_only_contacts_from_host != '1'
UNION
SELECT h.host_id, h.host_name, s.service_id, s.service_description, s.service_register, 1 as notif_type
FROM contact_service_relation csr, service s, host h, host_service_relation hsr, hostgroup_relation hgr
WHERE csr.contact_id = " . $contactId . "
AND csr.service_service_id = s.service_id
AND s.service_id = hsr.service_service_id
AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id
AND hgr.host_host_id = h.host_id
AND s.service_use_only_contacts_from_host != '1'";
if (count($contactGroups)) {
$contactGroups = implode(',', array_keys($contactGroups));
$sql .= ' UNION
SELECT h.host_id, h.host_name, s.service_id, s.service_description, s.service_register,
2 as notif_type
FROM contactgroup_service_relation csr, service s
LEFT JOIN host_service_relation hsr ON hsr.service_service_id = s.service_id
LEFT JOIN host h ON h.host_id = hsr.host_host_id
WHERE csr.contactgroup_cg_id IN (' . $contactGroups . ")
AND csr.service_service_id = s.service_id
AND s.service_use_only_contacts_from_host != '1'
UNION
SELECT h.host_id, h.host_name, s.service_id, s.service_description, s.service_register,
2 as notif_type
FROM contactgroup_service_relation csr, service s, host h, host_service_relation hsr,
hostgroup_relation hgr
WHERE csr.contactgroup_cg_id IN (" . $contactGroups . ")
AND csr.service_service_id = s.service_id
AND s.service_id = hsr.service_service_id
AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id
AND hgr.host_host_id = h.host_id
AND s.service_use_only_contacts_from_host != '1'";
}
$res = $this->db->query($sql);
$svcTab = [];
$svcList = [];
$templates = [];
while ($row = $res->fetchRow()) {
$svcList[$row['service_id']] = $row['service_id'];
if ($row['service_register'] == 1) {
if (! isset($svcTab[$row['host_id']])) {
$svcTab[$row['host_id']] = [];
}
$svcTab[$row['host_id']][$row['service_id']] = [];
$svcTab[$row['host_id']][$row['service_id']]['host_name'] = $row['host_name'];
$svcTab[$row['host_id']][$row['service_id']]['service_description'] = $row['service_description'];
} else {
$templates[$row['service_id']] = $row['service_description'];
$this->svcNotifType[$row['service_id']] = $row['notif_type'];
}
}
unset($res);
if (count($this->notifiedHosts)) {
$sql = 'SELECT h.host_id, h.host_name, s.service_id, s.service_description '
. 'FROM service s, host h, host_service_relation hsr '
. 'WHERE hsr.service_service_id = s.service_id '
. 'AND hsr.host_host_id = h.host_id '
. 'AND h.host_id IN (' . implode(',', array_keys($this->notifiedHosts)) . ')';
$res = $this->db->query($sql);
while ($row = $res->fetchRow()) {
$svcTab[$row['host_id']][$row['service_id']] = [];
$svcTab[$row['host_id']][$row['service_id']]['host_name'] = $row['host_name'];
$svcTab[$row['host_id']][$row['service_id']]['service_description'] = $row['service_description'];
}
unset($res);
}
if ($svcTab !== []) {
$tab = [];
foreach ($svcTab as $tmp) {
$tab = array_merge(array_keys($tmp), $tab);
}
$sql2 = 'SELECT service_id, service_description
FROM service
WHERE service_id NOT IN (' . implode(',', $tab) . ") AND service_register = '1'";
} else {
$sql2 = "SELECT service_id, service_description
FROM service
WHERE service_register = '1'";
}
$res2 = $this->db->query($sql2);
$sql3 = 'SELECT h.host_id, h.host_name, hsr.service_service_id as service_id
FROM host h, host_service_relation hsr
WHERE h.host_id = hsr.host_host_id
UNION
SELECT h.host_id, h.host_name, hsr.service_service_id
FROM host h, host_service_relation hsr, hostgroup_relation hgr
WHERE h.host_id = hgr.host_host_id
AND hgr.hostgroup_hg_id = hsr.hostgroup_hg_id';
$res3 = $this->db->query($sql3);
while ($row3 = $res3->fetchRow()) {
$list[$row3['service_id']] = $row3;
}
while ($row = $res2->fetchRow()) {
$this->svcBreak = [1 => false, 2 => false];
$flag = false;
if ($this->getServiceTemplateNotifications($row['service_id'], $templates) === true) {
if (array_key_exists($row['service_id'], $list)) {
$row3 = $list[$row['service_id']];
if (! isset($svcTab[$row3['host_id']])) {
$svcTab[$row3['host_id']] = [];
}
$svcTab[$row3['host_id']][$row['service_id']] = [];
$svcTab[$row3['host_id']][$row['service_id']]['host_name'] = $row3['host_name'];
$svcTab[$row3['host_id']][$row['service_id']]['service_description'] = $row['service_description'];
}
}
}
return $svcTab;
}
/**
* Recursive method
*
* @param int $serviceId
* @param array $templates
*
* @throws PDOException
* @return bool
*/
protected function getServiceTemplateNotifications($serviceId, $templates)
{
$tplId = 0;
if (! isset($this->svcTpl[$serviceId])) {
$sql = 'SELECT s.service_template_model_stm_id, csr.contact_id, csr2.contactgroup_cg_id
FROM service s
LEFT JOIN contact_service_relation csr ON csr.service_service_id = s.service_id
LEFT JOIN contactgroup_service_relation csr2 ON csr2.service_service_id = s.service_id
WHERE service_id = ' . $this->db->escape($serviceId);
$res = $this->db->query($sql);
$row = $res->fetchRow();
$tplId = $row['service_template_model_stm_id'];
} else {
$tplId = $this->svcTpl[$serviceId];
}
if ($row['contact_id']) {
$this->svcBreak[1] = true;
}
if ($row['contactgroup_cg_id']) {
$this->svcBreak[2] = true;
}
if (isset($templates[$tplId]) && $templates[$tplId]) {
if ($this->svcNotifType[$tplId] == 1 && $this->svcBreak[1] == true) {
return false;
}
return ! ($this->svcNotifType[$tplId] == 2 && $this->svcBreak[2] == true);
}
if ($tplId) {
return $this->getServiceTemplateNotifications($tplId, $templates);
}
return false;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonFeature.class.php | centreon/www/class/centreonFeature.class.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
*
*/
/**
* Class
*
* Manage new feature
*
* Format:
* $availableFeatures = array( array(
* 'name' => 'Header',
* 'version' => 2,
* 'description' => 'New header design user experience',
* 'visible' => true))
*
* @class CentreonFeature
*/
class CentreonFeature
{
/** @var CentreonDB */
protected $db;
/** @var array */
protected static $availableFeatures = [];
/**
* CentreonFeature constructor
*
* @param CentreonDB $db - The centreon database
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Return the list of new feature to test
*
* @param int $userId - The user id
*
* @throws PDOException
* @return array - The list of new feature to ask at the user
*/
public function toAsk($userId)
{
if (! is_numeric($userId)) {
throw new Exception('The user id is not numeric.');
}
$result = [];
if (count(self::$availableFeatures) != 0) {
$query = 'SELECT feature, feature_version FROM contact_feature WHERE contact_id = ' . $userId;
$res = $this->db->query($query);
$toAsk = [];
foreach (self::$availableFeatures as $feature) {
if ($feature['visible']) {
$version = $feature['name'] . '__' . $feature['version'];
$toAsk[$version] = $feature;
}
}
while ($row = $res->fetchRow()) {
$version = $row['feature'] . '__' . $row['feature_version'];
unset($toAsk[$version]);
}
foreach ($toAsk as $feature) {
$result[] = $feature;
}
}
return $result;
}
/**
* Return the list of features to test
*
* @return array
*/
public function getFeatures()
{
$result = [];
foreach (self::$availableFeatures as $feature) {
if ($feature['visible']) {
$result[] = $feature;
}
}
return $result;
}
/**
* Return the list of feature for an user and the activated value
*
* @param int $userId - The user id
*
* @throws PDOException
* @return array
*/
public function userFeaturesValue($userId)
{
if (! is_numeric($userId)) {
throw new Exception('The user id is not numeric.');
}
$query = 'SELECT feature, feature_version, feature_enabled FROM contact_feature WHERE contact_id = ' . $userId;
$res = $this->db->query($query);
$result = [];
while ($row = $res->fetchRow()) {
$result[] = ['name' => $row['feature'], 'version' => $row['feature_version'], 'enabled' => $row['feature_enabled']];
}
return $result;
}
/**
* Save the user choices for feature flipping
*
* @param int $userId - The user id
* @param array $features - The list of features
*
* @throws PDOException
*/
public function saveUserFeaturesValue($userId, $features): void
{
if (! is_numeric($userId)) {
throw new Exception('The user id is not numeric.');
}
foreach ($features as $name => $versions) {
foreach ($versions as $version => $value) {
$query = 'DELETE FROM contact_feature WHERE contact_id = ' . $userId . ' AND feature = "'
. $this->db->escape($name) . '" AND feature_version = "' . $this->db->escape($version) . '"';
$this->db->query($query);
$query = 'INSERT INTO contact_feature VALUES (' . $userId . ', "' . $this->db->escape($name) . '", "'
. $this->db->escape($version) . '", ' . (int) $value . ')';
$this->db->query($query);
}
}
}
/**
* Get if a feature is active for the application or an user
*
* @param string $name - The feature name
* @param string $version - The feature version
* @param null $userId - The user id if check for an user
*
* @throws Exception
* @return bool
*/
public function featureActive($name, $version, $userId = null)
{
foreach (self::$availableFeatures as $feature) {
if ($feature['name'] === $name && $feature['version'] === $version && ! $feature['visible']) {
return false;
}
}
if (is_null($userId)) {
return true;
}
if (! is_numeric($userId)) {
throw new Exception('The user id is not numeric.');
}
$query = 'SELECT feature_enabled FROM contact_feature
WHERE contact_id = ' . $userId . ' AND feature = "' . $this->db->escape($name) . '"
AND feature_version = "' . $this->db->escape($version) . '"';
try {
$res = $this->db->query($query);
} catch (Exception $e) {
return false;
}
if ($res->rowCount() === 0) {
return false;
}
$row = $res->fetch();
return $row['feature_enabled'] == 1;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonIssue.class.php | centreon/www/class/centreonIssue.class.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
*
*/
/**
* Class
*
* @class CentreonIssue
*/
class CentreonIssue
{
/** @var CentreonDB */
protected $dbb;
/**
* CentreonIssue constructor
*
* @param CentreonDB $dbb
*/
public function __construct($dbb)
{
$this->dbb = $dbb;
}
/**
* Get Children
*
* @param int $issueId
*
* @throws PDOException
* @return array
*/
public function getChildren($issueId)
{
$query = 'SELECT tb.issue_id, tb.host_id, tb.service_id, tb.start_time, tb.name, tb.description,
tb.state, tb.output
FROM (
SELECT i.issue_id,
i.host_id,
i.service_id,
i.start_time,
h.name,
s.description,
s.state,
s.output
FROM `hosts` h, `services` s, `issues` i, `issues_issues_parents` iip
WHERE h.host_id = i.host_id
AND s.service_id = i.service_id
AND s.host_id = h.host_id
AND i.issue_id = iip.child_id
AND iip.parent_id = ' . $this->dbb->escape($issueId) . '
UNION
SELECT i2.issue_id,
i2.host_id,
i2.service_id,
i2.start_time,
h2.name,
NULL,
h2.state,
h2.output
FROM `hosts` h2, `issues` i2, `issues_issues_parents` iip2
WHERE h2.host_id = i2.host_id
AND i2.service_id IS NULL
AND i2.issue_id = iip2.child_id
AND iip2.parent_id = ' . $this->dbb->escape($issueId) . '
) tb ';
$res = $this->dbb->query($query);
$childTab = [];
while ($row = $res->fetchRow()) {
foreach ($row as $key => $val) {
$childTab[$row['issue_id']][$key] = $val;
}
}
return $childTab;
}
/**
* Check if issue is parent
*
* @param int $issueId
*
* @throws PDOException
* @return bool
*/
public function isParent($issueId)
{
$query = 'SELECT parent_id
FROM issues_issues_parents
WHERE parent_id = ' . $this->dbb->escape($issueId) . ' LIMIT 1';
$res = $this->dbb->query($query);
return (bool) ($res->rowCount());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonServicegroups.class.php | centreon/www/class/centreonServicegroups.class.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
*
*/
/**
* Class
*
* @class CentreonServicegroups
*/
class CentreonServicegroups
{
/** @var CentreonDB */
private $DB;
/** @var */
private $relationCache;
/** @var */
private $dataTree;
/**
* CentreonServicegroups constructor
*
* @param CentreonDB $pearDB
*/
public function __construct($pearDB)
{
$this->DB = $pearDB;
}
/**
* @param null $sgId
*
* @throws PDOException
* @return array|void
*/
public function getServiceGroupServices($sgId = null)
{
if (! $sgId) {
return;
}
$services = [];
$query = 'SELECT host_host_id, service_service_id '
. 'FROM servicegroup_relation '
. 'WHERE servicegroup_sg_id = ' . $sgId . ' '
. 'AND host_host_id IS NOT NULL '
. 'UNION '
. 'SELECT hgr.host_host_id, hsr.service_service_id '
. 'FROM servicegroup_relation sgr, host_service_relation hsr, hostgroup_relation hgr '
. 'WHERE sgr.servicegroup_sg_id = ' . $sgId . ' '
. 'AND sgr.hostgroup_hg_id = hsr.hostgroup_hg_id '
. 'AND hsr.service_service_id = sgr.service_service_id '
. 'AND sgr.hostgroup_hg_id = hgr.hostgroup_hg_id ';
$res = $this->DB->query($query);
while ($row = $res->fetchRow()) {
$services[] = [$row['host_host_id'], $row['service_service_id']];
}
$res->closeCursor();
return $services;
}
/**
* Get service groups id and name from ids
*
* @param int[] $serviceGroupsIds
* @return array $retArr [['id' => integer, 'name' => string],...]
*/
public function getServicesGroups($serviceGroupsIds = [])
{
$servicesGroups = [];
if (! empty($serviceGroupsIds)) {
/* checking here that the array provided as parameter
* is exclusively made of integers (servicegroup ids)
*/
$filteredSgIds = $this->filteredArrayId($serviceGroupsIds);
$sgParams = [];
if ($filteredSgIds !== []) {
/*
* Building the sgParams hash table in order to correctly
* bind ids as ints for the request.
*/
foreach ($filteredSgIds as $index => $filteredSgId) {
$sgParams[':sgId' . $index] = $filteredSgId;
}
$stmt = $this->DB->prepare(
'SELECT sg_id, sg_name FROM servicegroup '
. 'WHERE sg_id IN ( ' . implode(',', array_keys($sgParams)) . ' )'
);
foreach ($sgParams as $index => $value) {
$stmt->bindValue($index, $value, PDO::PARAM_INT);
}
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$servicesGroups[] = [
'id' => $row['sg_id'],
'name' => $row['sg_name'],
];
}
}
}
return $servicesGroups;
}
/**
* @param type $field
* @return string
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'servicegroup';
$parameters['currentObject']['id'] = 'sg_id';
$parameters['currentObject']['name'] = 'sg_name';
$parameters['currentObject']['comparator'] = 'sg_id';
switch ($field) {
case 'sg_hServices':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonService';
$parameters['relationObject']['table'] = 'servicegroup_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['additionalField'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'servicegroup_sg_id';
break;
case 'sg_tServices':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonServicetemplates';
$parameters['externalObject']['objectOptions'] = ['withHosttemplate' => true];
$parameters['relationObject']['table'] = 'servicegroup_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['additionalField'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'servicegroup_sg_id';
break;
case 'sg_hgServices':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonService';
$parameters['externalObject']['objectOptions'] = ['hostgroup' => true];
$parameters['relationObject']['table'] = 'servicegroup_relation';
$parameters['relationObject']['field'] = 'hostgroup_hg_id';
$parameters['relationObject']['additionalField'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'servicegroup_sg_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
if (empty($values)) {
return $items;
}
global $centreon;
$sgAcl = [];
// get list of authorized servicegroups
if (
! $centreon->user->access->admin
&& $centreon->user->access->hasAccessToAllServiceGroups === false
) {
$sgAcl = $centreon->user->access->getServiceGroupAclConf(
null,
'broker',
['distinct' => true, 'fields' => ['servicegroup.sg_id'], 'get_row' => 'sg_id', 'keys' => ['sg_id'], 'conditions' => ['servicegroup.sg_id' => ['IN', $values]]],
true
);
}
$queryValues = [];
$whereCondition = '';
if (! empty($values)) {
foreach ($values as $key => $value) {
$serviceGroupIds = explode(',', $value);
foreach ($serviceGroupIds as $serviceGroupId) {
$queryValues[':sg_' . $serviceGroupId] = (int) $serviceGroupId;
}
}
$whereCondition = ' WHERE sg_id IN (' . implode(',', array_keys($queryValues)) . ')';
}
$request = <<<SQL
SELECT
sg_id,
sg_name
FROM servicegroup
{$whereCondition}
ORDER BY sg_name
SQL;
$statement = $this->DB->prepare($request);
foreach ($queryValues as $key => $value) {
$statement->bindValue($key, $value, PDO::PARAM_INT);
}
$statement->execute();
while ($record = $statement->fetch(PDO::FETCH_ASSOC)) {
// hide unauthorized servicegroups
$hide = false;
if (
! $centreon->user->access->admin
&& $centreon->user->access->hasAccessToAllServiceGroups === false
&& ! in_array($record['sg_id'], $sgAcl)
) {
$hide = true;
}
$items[] = [
'id' => $record['sg_id'],
'text' => $record['sg_name'],
'hide' => $hide,
];
}
return $items;
}
/**
* @param string $sgName
*
* @throws Throwable
* @return array<array{service:string,service_id:int,host:string,sg_name:string}>
*/
public function getServicesByServicegroupName(string $sgName): array
{
$serviceList = [];
$query = <<<'SQL'
SELECT service_description, service_id, host_name
FROM servicegroup_relation sgr, service s, servicegroup sg, host h
WHERE sgr.service_service_id = s.service_id
AND sgr.servicegroup_sg_id = sg.sg_id
AND s.service_activate = '1'
AND s.service_register = '1'
AND sgr.host_host_id = h.host_id
AND sg.sg_name = :sgName
SQL;
$statement = $this->DB->prepare($query);
$statement->bindValue(':sgName', $this->DB->escape($sgName), PDO::PARAM_STR);
$statement->execute();
while ($elem = $statement->fetch()) {
/** @var array{service_description:string,service_id:int,host_name:string} $elem */
$serviceList[] = [
'service' => $elem['service_description'],
'service_id' => $elem['service_id'],
'host' => $elem['host_name'],
'sg_name' => $sgName,
];
}
return $serviceList;
}
/**
* @param string $sgName
*
* @throws Throwable
* @return array<array{service:string,service_id:int,host:string,sg_name:string}>
*/
public function getServicesThroughtServiceTemplatesByServicegroupName(string $sgName): array
{
$serviceList = [];
$query = <<<'SQL'
SELECT s.service_description, s.service_id, h.host_name
FROM `servicegroup_relation` sgr
JOIN `servicegroup` sg
ON sg.sg_id = sgr.servicegroup_sg_id
JOIN `service` st
ON st.service_id = sgr.service_service_id
AND st.service_activate = '1'
AND st.service_register = '0'
JOIN `service` s
ON s.service_template_model_stm_id = st.service_id
AND s.service_activate = '1'
AND s.service_register = '1'
JOIN `host_service_relation` hsrel
ON hsrel.service_service_id = s.service_id
JOIN `host` h
ON h.host_id = hsrel.host_host_id
WHERE sg.sg_name = :sgName
SQL;
$statement = $this->DB->prepare($query);
$statement->bindValue(':sgName', $this->DB->escape($sgName), PDO::PARAM_STR);
$statement->execute();
while ($elem = $statement->fetch()) {
/** @var array{service_description:string,service_id:int,host_name:string} $elem */
$serviceList[] = [
'service' => $elem['service_description'],
'service_id' => $elem['service_id'],
'host' => $elem['host_name'],
'sg_name' => $sgName,
];
}
return $serviceList;
}
/**
* @param $sgName
* @return int|mixed
*/
public function getServicesGroupId($sgName)
{
static $ids = [];
if (! isset($ids[$sgName])) {
$query = "SELECT sg_id FROM servicegroup WHERE sg_name = '" . $this->DB->escape($sgName) . "'";
$res = $this->DB->query($query);
if ($res->numRows()) {
$row = $res->fetchRow();
$ids[$sgName] = $row['sg_id'];
}
}
return $ids[$sgName] ?? 0;
}
/**
* Returns a filtered array with only integer ids
*
* @param int[] $ids
* @return int[] filtered
*/
private function filteredArrayId(array $ids): array
{
return array_filter($ids, function ($id) {
return is_numeric($id);
});
}
/**
* @param array<int|string, int|string> $list
* @param string $prefix
*
* @return array{0: array<string, mixed>, 1: string}
*/
private function createMultipleBindQuery(array $list, string $prefix): array
{
$bindValues = [];
foreach ($list as $index => $id) {
$bindValues[$prefix . $index] = $id;
}
return [$bindValues, implode(', ', array_keys($bindValues))];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraphStatus.class.php | centreon/www/class/centreonGraphStatus.class.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
*
*/
/**
* Class
*
* @class CentreonGraphStatus
* @description Class for get status for a service and return this on JSON
*/
class CentreonGraphStatus
{
/** @var CentreonDB */
public $pearDB;
/** @var CentreonDB */
public $pearDBMonitoring;
/** @var int */
public $index;
/** @var int */
public $startTime;
/** @var int */
public $endTime;
/** @var string */
public $statusPath;
/** @var array */
public $generalOpt;
/** @var array */
public $rrdCachedOptions;
/** @var */
public $arguments;
/** @var */
public $rrdOptions;
/**
* CentreonGraphStatus Constructor
*
* @param int $index The index data id
* @param int $start The start time
* @param int $end The end time
*
* @throws RuntimeException
*/
public function __construct($index, $start, $end)
{
$this->pearDB = new CentreonDB();
$this->pearDBMonitoring = new CentreonDB('centstorage');
$this->index = $index;
$this->startTime = $start;
$this->endTime = $end;
$this->statusPath = $this->getStatusPath();
$this->generalOpt = $this->getOptions();
$this->rrdCachedOptions = $this->getRrdCachedOptions();
}
/**
* Get the metrics
*
* @throws RuntimeException
* @return array|array[]
*/
public function getData()
{
$this->setRRDOption('imgformat', 'JSONTIME');
$this->setRRDOption('start', $this->startTime);
$this->setRRDOption('end', $this->endTime);
$path = $this->statusPath . '/' . $this->index . '.rrd';
if (file_exists($path) === false) {
throw new RuntimeException();
}
$this->addArgument('DEF:v1=' . $path . ':value:AVERAGE');
$this->addArgument('VDEF:v1Average=v1,AVERAGE');
$this->addArgument('LINE1:v1#0000ff:v1');
$jsonData = $this->getJsonStream();
$metrics = ['critical' => [], 'warning' => [], 'ok' => [], 'unknown' => []];
$lastStatus = null;
$interval = [];
foreach ($jsonData['data'] as $row) {
$time = (string) $row[0];
$value = $row[1];
if (is_null($value)) {
$currentStatus = 'unknown';
} elseif ($value < 75) {
$currentStatus = 'critical';
} elseif ($value == 100) {
$currentStatus = 'ok';
} elseif ($value > 74) {
$currentStatus = 'warning';
} else {
$currentStatus = 'unknown';
}
if (is_null($lastStatus)) {
$interval = ['start' => $time, 'end' => null];
$lastStatus = $currentStatus;
} elseif ($lastStatus !== $currentStatus) {
$interval['end'] = $time;
$metrics[$lastStatus][] = $interval;
$lastStatus = $currentStatus;
$interval = ['start' => $time, 'end' => null];
}
}
$interval['end'] = $time;
$metrics[$lastStatus][] = $interval;
return $metrics;
}
/**
* Flush status rrdfile from cache
*
* @param int $indexData The index data id
*
* @return bool
*/
public function flushRrdCached($indexData)
{
if (! isset($this->rrdCachedOptions['rrd_cached_option'])
|| ! in_array($this->rrdCachedOptions['rrd_cached_option'], ['unix', 'tcp'])
) {
return true;
}
$errno = 0;
$errstr = '';
if ($this->rrdCachedOptions['rrd_cached_option'] === 'tcp') {
$sock = fsockopen('127.0.0.1', trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr);
} elseif ($this->rrdCachedOptions['rrd_cached_option'] === 'unix') {
$sock = fsockopen('unix://' . trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr);
} else {
return false;
}
if ($sock === false) {
return false;
}
if (fputs($sock, "BATCH\n") === false) {
@fclose($sock);
return false;
}
if (fgets($sock) === false) {
@fclose($sock);
return false;
}
$fullpath = realpath($this->statusPath . $indexData . '.rrd');
$cmd = 'FLUSH ' . $fullpath;
if (fputs($sock, $cmd . "\n") === false) {
@fclose($sock);
return false;
}
if (fputs($sock, ".\n") === false) {
@fclose($sock);
return false;
}
if (fgets($sock) === false) {
@fclose($sock);
return false;
}
fputs($sock, "QUIT\n");
@fclose($sock);
return true;
}
/**
* Get the index data id for a service
*
* @param int $hostId The host id
* @param int $serviceId The service id
* @param CentreonDB $dbc The database connection to centreon_storage
*
* @throws OutOfRangeException
* @throws PDOException
* @return int
*/
public static function getIndexId($hostId, $serviceId, $dbc)
{
$query = 'SELECT id, 1 AS REALTIME FROM index_data WHERE host_id = ' . $hostId . ' AND service_id = '
. $serviceId;
$res = $dbc->query($query);
$row = $res->fetch();
if ($row == false) {
throw new OutOfRangeException();
}
return $row['id'];
}
/**
* Get general options
*
* @throws RuntimeException
* @return array The list of genreal options
*/
protected function getOptions()
{
$result = [];
$query = "SELECT `key`, `value` FROM options
WHERE `key` IN ('rrdtool_path_bin', 'rrdcached_enabled', 'debug_rrdtool', 'debug_path')";
try {
$res = $this->pearDB->query($query);
} catch (PDOException $e) {
throw new RuntimeException();
}
while ($row = $res->fetch()) {
$result[$row['key']] = $row['value'];
}
return $result;
}
/**
* Get the RRDCacheD options of local RRD Broker
*
* @throws PDOException
* @return array of RRDCacheD options
*/
protected function getRrdCachedOptions()
{
$result = $this->pearDB->query(
"SELECT config_key, config_value
FROM cfg_centreonbroker_info AS cbi
INNER JOIN cfg_centreonbroker AS cb ON (cb.config_id = cbi.config_id)
INNER JOIN nagios_server AS ns ON (ns.id = cb.ns_nagios_server)
WHERE ns.localhost = '1'
AND cbi.config_key IN ('rrd_cached_option', 'rrd_cached')"
);
$rrdCachedOptions = [];
while ($row = $result->fetch()) {
$this->rrdCachedOptions[$row['config_key']] = $row['config_value'];
}
return $rrdCachedOptions;
}
/**
* Get the status RRD path
*
* @throws PDOException
* @throws RuntimeException
* @return string The status RRD path
*/
protected function getStatusPath()
{
$query = 'SELECT RRDdatabase_status_path FROM config';
$res = $this->pearDBMonitoring->query($query);
$row = $res->fetch();
if ($row === null) {
throw new RuntimeException('Missing status directory configuration');
}
return $row['RRDdatabase_status_path'];
}
/**
* Add argument rrdtool
*
* @param string $arg
*
* @return void
*/
protected function addArgument($arg)
{
$this->arguments[] = $arg;
}
/**
* Add argument rrdtool
*
* @param string $name the key
* @param string $value
*
* @return void
*/
protected function setRRDOption($name, $value = null)
{
if (str_contains($value, ' ')) {
$value = "'" . $value . "'";
}
$this->rrdOptions[$name] = $value;
}
/**
* Log message
*
* @param string $message
*
* @return void
*/
private function log($message): void
{
if ($this->generalOpt['debug_rrdtool']
&& is_writable($this->generalOpt['debug_path'])) {
error_log(
'[' . date('d/m/Y H:i') . '] RDDTOOL : ' . $message . " \n",
3,
$this->generalOpt['debug_path'] . 'rrdtool.log'
);
}
}
/**
* Get rrdtool result
*
* @return mixed
*/
private function getJsonStream()
{
$this->flushRrdcached($this->index);
$commandLine = '';
$commandLine = ' graph - ';
foreach ($this->rrdOptions as $key => $value) {
$commandLine .= '--' . $key;
if (isset($value)) {
if (preg_match('/\'/', $value)) {
$value = "'" . preg_replace('/\'/', ' ', $value) . "'";
}
$commandLine .= '=' . $value;
}
$commandLine .= ' ';
}
foreach ($this->arguments as $arg) {
$commandLine .= ' ' . $arg . ' ';
}
$commandLine = preg_replace('/(\\$|`)/', '', $commandLine);
$this->log($commandLine);
if (is_writable($this->generalOpt['debug_path'])) {
$stderr = ['file', $this->generalOpt['debug_path'] . '/rrdtool.log', 'a'];
} else {
$stderr = ['pipe', 'a'];
}
$descriptorspec = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => $stderr];
$process = proc_open($this->generalOpt['rrdtool_path_bin'] . ' - ', $descriptorspec, $pipes, null, null);
if (is_resource($process)) {
fwrite($pipes[0], $commandLine);
fclose($pipes[0]);
$str = stream_get_contents($pipes[1]);
$returnValue = proc_close($process);
$str = preg_replace('/OK u:.*$/', '', $str);
$rrdData = json_decode($str, true);
}
return $rrdData;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraphNg.class.php | centreon/www/class/centreonGraphNg.class.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__ . '/centreonDuration.class.php';
require_once __DIR__ . '/centreonGMT.class.php';
require_once __DIR__ . '/centreonACL.class.php';
require_once __DIR__ . '/centreonHost.class.php';
require_once __DIR__ . '/centreonService.class.php';
require_once __DIR__ . '/centreonSession.class.php';
require_once __DIR__ . '/../include/common/common-Func.php';
/**
* Class
*
* @class MetricUtils
* @description Singleton Class for topological sorting
*/
class MetricUtils
{
/** @var MetricUtils|null */
private static $instance = null;
/**
* MetricUtils constructor
*/
private function __construct()
{
}
/**
* Singleton create method
*
* @return MetricUtils
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new MetricUtils();
}
return self::$instance;
}
/**
* Function to do a topological sort on a directed acyclic graph
*
* @param mixed $data nodes listing
* @param mixed $dependency nodes link between them
*
* @return mixed nodes listing sorted
*/
public function topologicalSort($data, $dependency)
{
$order = [];
$preProcessing = [];
$order = array_diff_key($data, $dependency);
$data = array_diff_key($data, $order);
foreach ($data as $i => $v) {
if (! $this->processTopoSort($i, $dependency, $order, $preProcessing)) {
return false;
}
}
return $order;
}
/**
* Process Topological Sort
*
* @param int $pointer
* @param mixed $dependency
* @param mixed $order
* @param mixed $preProcessing
*
* @return bool
*/
private function processTopoSort($pointer, &$dependency, &$order, &$preProcessing)
{
if (isset($preProcessing[$pointer])) {
return false;
}
$preProcessing[$pointer] = $pointer;
foreach ($dependency[$pointer] as $i => $v) {
if (isset($dependency[$v])) {
if (! $this->processTopoSort($v, $dependency, $order, $preProcessing)) {
return false;
}
}
$order[$v] = $v;
unset($preProcessing[$v]);
}
$order[$pointer] = $pointer;
unset($preProcessing[$pointer]);
return true;
}
}
/**
* Class
*
* @class CentreonGraphNg
*/
class CentreonGraphNg
{
/** @var array */
public $listMetricsId = [];
/** @var array */
public $vmetrics = [];
/** @var false */
public $multipleServices = false;
/** @var */
protected $db;
/** @var */
protected $dbCs;
/** @var MetricUtils|null */
protected $metricUtils;
/** @var */
protected $rrdOptions;
/** @var array */
protected $arguments = [];
/** @var */
protected $debug;
/** @var int */
protected $userId;
/** @var */
protected $generalOpt;
/** @var mixed */
protected $dbPath;
/** @var mixed */
protected $dbStatusPath;
/** @var null[] */
protected $indexData = [
'host_id' => null,
'host_name' => null,
'service_id' => null,
'service_description' => null,
];
/** @var */
protected $templateId;
/** @var array */
protected $templateInformations = [];
/** @var array */
protected $metrics = [];
/** @var array */
protected $indexIds = [];
/** @var null */
protected $dsDefault = null;
/** @var null */
protected $colorCache = null;
/** @var null */
protected $componentsDsCache = null;
/** @var array */
protected $extraDatas = [];
/** @var array */
protected $cacheAllMetrics = [];
/** @var array */
protected $vnodes = [];
/** @var array */
protected $vnodesDependencies = [];
/** @var array */
protected $vmetricsOrder = [];
/** @var */
protected $graphData;
/** @var */
protected $rrdCachedOptions;
/**
* CentreonGraphNg constructor
*
* @param int $userId
*/
public function __construct($userId)
{
$this->initDatabase();
$this->metricUtils = MetricUtils::getInstance();
$this->userId = $userId;
$stmt = $this->dbCs->prepare('SELECT RRDdatabase_path, RRDdatabase_status_path FROM config');
$stmt->execute();
$config = $stmt->fetch(PDO::FETCH_ASSOC);
$this->dbPath = $config['RRDdatabase_path'];
$this->dbStatusPath = $config['RRDdatabase_status_path'];
$stmt = $this->db->prepare('SELECT `key`, `value` FROM options');
$stmt->execute();
$this->generalOpt = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
// Get RRDCacheD options
$stmt = $this->db->query(
"SELECT config_key, config_value
FROM cfg_centreonbroker_info AS cbi
INNER JOIN cfg_centreonbroker AS cb ON (cb.config_id = cbi.config_id)
INNER JOIN nagios_server AS ns ON (ns.id = cb.ns_nagios_server)
WHERE ns.localhost = '1'
AND cbi.config_key IN ('rrd_cached_option', 'rrd_cached')"
);
while ($row = $stmt->fetch()) {
$this->rrdCachedOptions[$row['config_key']] = $row['config_value'];
}
}
/**
* Set if a graph has multiple services
*
* @param int $multiple set multiple value
*
* @return void
*/
public function setMultipleServices($multiple): void
{
$this->multipleServices = $multiple;
}
/**
* Get graph result
*
* @param int $start unix timestamp start date
* @param int $end unix timestamp end date
*
* @return array graph result
*/
public function getGraph($start, $end)
{
/**
* For the title and also get the graph template
* With multiple index_id, we get the last
* Need to think about it
*/
$this->getIndexData();
$this->extraDatas['start'] = $start;
$this->extraDatas['end'] = $end;
$this->setRRDOption('start', $start);
$this->setRRDOption('end', $end);
$this->setTemplate();
$this->init();
$this->initCurveList();
$this->createLegend();
return $this->getJsonStream();
}
/**
* Initiate the Graph objects
*
* @return void
*/
public function init(): void
{
$this->setRRDOption('imgformat', 'JSONTIME');
if (isset($this->templateInformations['vertical_label'])) {
$this->extraDatas['vertical-label'] = $this->templateInformations['vertical_label'];
}
$this->setRRDOption('slope-mode');
if (isset($this->templateInformations['base']) && $this->templateInformations['base']) {
$this->extraDatas['base'] = $this->templateInformations['base'];
}
if (isset($this->templateInformations['width']) && $this->templateInformations['width']) {
$this->extraDatas['width'] = $this->templateInformations['width'];
$this->setRRDOption('width', $this->templateInformations['width']);
}
if (isset($this->templateInformations['height']) && $this->templateInformations['height']) {
$this->extraDatas['height'] = $this->templateInformations['height'];
$this->setRRDOption('height', $this->templateInformations['height']);
}
if (isset($this->templateInformations['lower_limit']) && $this->templateInformations['lower_limit'] != null) {
$this->extraDatas['lower-limit'] = $this->templateInformations['lower_limit'];
$this->setRRDOption('lower-limit', $this->templateInformations['lower_limit']);
}
if (isset($this->templateInformations['upper_limit']) && $this->templateInformations['upper_limit'] != '') {
$this->extraDatas['upper-limit'] = $this->templateInformations['upper_limit'];
$this->setRRDOption('upper-limit', $this->templateInformations['upper_limit']);
} elseif (isset($this->templateInformations['']) && $this->templateInformations['size_to_max']) {
$this->extraDatas['size-to-max'] = $this->templateInformations['size_to_max'];
}
$this->extraDatas['scaled'] = 1;
if (isset($this->templateInformations['scaled']) && $this->templateInformations['scaled'] == '0') {
$this->extraDatas['scaled'] = 0;
}
}
/**
* Add metrics for a service
*
* @param int $hostId
* @param int $serviceId
*
* @return void
*/
public function addServiceMetrics($hostId, $serviceId): void
{
$indexId = null;
$stmt = $this->dbCs->prepare(
"SELECT
m.index_id, host_id, service_id, metric_id, metric_name,
unit_name, min, max, warn, warn_low, crit, crit_low
FROM metrics AS m, index_data AS i
WHERE i.host_id = :host_id
AND i.service_id = :service_id
AND i.id = m.index_id
AND m.hidden = '0'"
);
$stmt->bindParam(':host_id', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$stmt->execute();
$metrics = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($metrics as $metric) {
$indexId = $metric['index_id'];
$this->addIndexId($metric['index_id']);
$this->addRealMetric($metric);
}
$stmt = $this->db->prepare(
"SELECT *
FROM virtual_metrics
WHERE index_id = :index_id
AND vmetric_activate = '1'"
);
$stmt->bindParam(':index_id', $indexId, PDO::PARAM_INT);
$stmt->execute();
$vmetrics = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($vmetrics as $vmetric) {
$this->addVirtualMetric($vmetric);
}
}
/**
* Add metrics for a service
*
* @param int $hostId
* @param int $serviceId
* @param mixed $metricsSelected
*
* @return void
*/
public function addServiceCustomMetrics($hostId, $serviceId, $metricsSelected): void
{
$indexId = null;
$stmt = $this->dbCs->prepare(
"SELECT
m.index_id, host_id, service_id, metric_id, metric_name,
unit_name, min, max, warn, warn_low, crit, crit_low
FROM metrics AS m, index_data AS i
WHERE i.host_id = :host_id
AND i.service_id = :service_id
AND i.id = m.index_id
AND m.hidden = '0'"
);
$stmt->bindParam(':host_id', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$stmt->execute();
$metrics = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($metrics as $metric) {
$indexId = $metric['index_id'];
$this->addIndexId($metric['index_id']);
if (isset($metricsSelected[$metric['metric_id']])) {
$this->addRealMetric($metric);
} else {
// this metric will be hidden
$this->addRealMetric($metric, 1);
}
}
$stmt = $this->db->prepare(
"SELECT *
FROM virtual_metrics
WHERE index_id = :index_id
AND vmetric_activate = '1'"
);
$stmt->bindParam(':index_id', $indexId, PDO::PARAM_INT);
$stmt->execute();
$vmetrics = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($vmetrics as $vmetric) {
$this->addVirtualMetric($vmetric);
}
}
/**
* Add a metric
*
* @param int $metricId
* @param int $isVirtual
*
* @return void
*/
public function addMetric($metricId, $isVirtual = 0): void
{
if ($isVirtual == 0) {
$stmt = $this->dbCs->prepare(
"SELECT m.index_id, host_id, service_id, metric_id, metric_name,
unit_name, min, max, warn, warn_low, crit, crit_low
FROM metrics AS m, index_data AS i
WHERE m.metric_id = :metric_id
AND m.hidden = '0'
AND m.index_id = i.id"
);
$stmt->bindParam(':metric_id', $metricId, PDO::PARAM_INT);
$stmt->execute();
$metric = $stmt->fetch(PDO::FETCH_ASSOC);
if (is_null($metric)) {
return;
}
$this->addIndexId($metric['index_id']);
$this->addRealMetric($metric);
return;
}
$stmt = $this->db->prepare(
"SELECT *
FROM virtual_metrics
WHERE vmetric_id = :vmetric_id
AND vmetric_activate = '1'"
);
$stmt->bindParam(':vmetric_id', $metricId, PDO::PARAM_INT);
$stmt->execute();
$vmetric = $stmt->fetch(PDO::FETCH_ASSOC);
if (is_null($vmetric)) {
return;
}
$this->addIndexId($vmetric['index_id']);
$this->addVirtualMetric($vmetric);
/**
* Brutal: we get all vmetrics and metrics, with hidden
*/
$metrics = $this->getRealMetricsByIndexId($vmetric['index_id']);
foreach ($metrics as $metric) {
$this->addIndexId($metric['index_id']);
$this->addRealMetric($metric, 1);
}
$vmetrics = $this->getVirtualMetricsByIndexId($vmetric['index_id']);
foreach ($vmetrics as $vmetric) {
$this->addVirtualMetric($vmetric);
}
}
/**
* Create Legend on the graph
*
* @return void
*/
public function createLegend(): void
{
foreach ($this->metrics as $metricId => $tm) {
if ($tm['hidden'] == 1) {
continue;
}
$arg = 'LINE1:v' . $metricId . '#0000ff:v' . $metricId;
$this->addArgument($arg);
$this->legendAddPrint($tm, $metricId);
}
foreach ($this->vmetricsOrder as $vmetricId) {
if ($this->vmetrics[$vmetricId]['hidden'] == 1) {
continue;
}
$arg = 'LINE1:vv' . $vmetricId . '#0000ff:vv' . $vmetricId;
$this->addArgument($arg);
$this->legendAddPrint($this->vmetrics[$vmetricId], $vmetricId, 1);
}
}
/**
* Assign graph template
*
* @param int $templateId
*
* @return void
*/
public function setTemplate($templateId = null): void
{
if ($this->multipleServices) {
return;
}
if (! isset($templateId) || ! $templateId) {
if ($this->indexData['host_name'] != '_Module_Meta') {
$this->getDefaultGraphTemplate();
} else {
$stmt = $this->db->prepare('SELECT graph_id FROM meta_service WHERE `meta_name` = :meta_name');
$stmt->bindParam(':meta_name', $this->indexData['service_description'], PDO::PARAM_STR);
$stmt->execute();
$meta = $stmt->fetch(PDO::FETCH_ASSOC);
$this->templateId = $meta['graph_id'];
}
} else {
$this->templateId = htmlentities($_GET['template_id'], ENT_QUOTES, 'UTF-8');
}
$stmt = $this->db->prepare('SELECT * FROM giv_graphs_template WHERE graph_id = :graph_id');
$stmt->bindParam(':graph_id', $this->templateId, PDO::PARAM_INT);
$stmt->execute();
$this->templateInformations = $stmt->fetch(PDO::FETCH_ASSOC);
}
/**
* Add argument rrdtool
*
* @param string $arg
*
* @return void
*/
public function addArgument($arg): void
{
$this->arguments[] = $arg;
}
/**
* Add argument rrdtool
*
* @param string $name the key
* @param string $value
*
* @return void
*/
public function setRRDOption($name, $value = null): void
{
if ($value !== null && str_contains($value, ' ')) {
$value = "'" . $value . "'";
}
$this->rrdOptions[$name] = $value;
}
/**
* Get rrdtool result
*
* @return mixed
*/
public function getJsonStream()
{
$commandLine = '';
$this->flushRrdcached($this->listMetricsId);
$commandLine = ' graph - ';
foreach ($this->rrdOptions as $key => $value) {
$commandLine .= '--' . $key;
if (isset($value)) {
if (preg_match('/\'/', $value)) {
$value = "'" . preg_replace('/\'/', ' ', $value) . "'";
}
$commandLine .= '=' . $value;
}
$commandLine .= ' ';
}
foreach ($this->arguments as $arg) {
$commandLine .= ' ' . $arg . ' ';
}
$commandLine = preg_replace('/(\\$|`)/', '', $commandLine);
$this->log($commandLine);
if (is_writable($this->generalOpt['debug_path']['value'])) {
$stderr = ['file', $this->generalOpt['debug_path']['value'] . '/rrdtool.log', 'a'];
} else {
$stderr = ['pipe', 'a'];
}
$descriptorspec = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => $stderr];
$process = proc_open(
$this->generalOpt['rrdtool_path_bin']['value'] . ' - ',
$descriptorspec,
$pipes,
null,
null
);
$this->extraDatas['multiple_services'] = $this->multipleServices;
$this->graphData = ['global' => $this->extraDatas, 'metrics' => []];
foreach ($this->metrics as $metric) {
if ($metric['hidden'] == 1) {
continue;
}
$this->graphData['metrics'][] = $metric;
}
foreach ($this->vmetricsOrder as $vmetricId) {
if ($this->vmetrics[$vmetricId]['hidden'] == 1) {
continue;
}
$this->graphData['metrics'][] = $this->vmetrics[$vmetricId];
}
if (is_resource($process)) {
fwrite($pipes[0], $commandLine);
fclose($pipes[0]);
$str = stream_get_contents($pipes[1]);
$returnValue = proc_close($process);
$str = preg_replace('/OK u:.*$/', '', $str);
$rrdData = json_decode($str, true);
}
$this->formatByMetrics($rrdData);
return $this->graphData;
}
/**
* Check argument
*
* @param string $name
* @param mixed $tab
* @param string $defaultValue
*
* @return string
*/
public function checkArgument($name, $tab, $defaultValue)
{
if (isset($name, $tab)) {
if (isset($tab[$name])) {
return htmlentities($tab[$name], ENT_QUOTES, 'UTF-8');
}
return htmlentities($defaultValue, ENT_QUOTES, 'UTF-8');
}
return '';
}
/**
* Get curve color
*
* @param int $indexId
* @param int $metricId
*
* @return string
*/
public function getOVDColor($indexId, $metricId)
{
if (is_null($this->colorCache)) {
$this->colorCache = [];
}
if (! isset($this->colorCache[$indexId])) {
$stmt = $this->db->prepare(
'SELECT metric_id, rnd_color FROM `ods_view_details` WHERE `index_id` = :index_id'
);
$stmt->bindParam(':index_id', $indexId, PDO::PARAM_INT);
$stmt->execute();
$this->colorCache[$indexId] = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
}
if (
isset($this->colorCache[$indexId][$metricId])
&& preg_match("/^\#[a-f0-9]{6,6}/i", $this->colorCache[$indexId][$metricId]['rnd_color'])
) {
return $this->colorCache[$indexId][$metricId]['rnd_color'];
}
$lRndcolor = $this->getRandomWebColor();
$stmt = $this->db->prepare(
'INSERT INTO `ods_view_details` (rnd_color, index_id, metric_id) VALUES (:rnd_color, :index_id, :metric_id)'
);
$stmt->bindParam(':rnd_color', $lRndcolor, PDO::PARAM_STR);
$stmt->bindParam(':index_id', $indexId, PDO::PARAM_INT);
$stmt->bindParam(':metric_id', $metricId, PDO::PARAM_INT);
$stmt->execute();
return $lRndcolor;
}
/**
* Get random color in a predefined list
*
* @return string
*/
public function getRandomWebColor()
{
$webSafeColors = ['#000033', '#000066', '#000099', '#0000cc', '#0000ff', '#003300', '#003333', '#003366', '#003399', '#0033cc', '#0033ff', '#006600', '#006633', '#006666', '#006699', '#0066cc', '#0066ff', '#009900', '#009933', '#009966', '#009999', '#0099cc', '#0099ff', '#00cc00', '#00cc33', '#00cc66', '#00cc99', '#00cccc', '#00ccff', '#00ff00', '#00ff33', '#00ff66', '#00ff99', '#00ffcc', '#00ffff', '#330000', '#330033', '#330066', '#330099', '#3300cc', '#3300ff', '#333300', '#333333', '#333366', '#333399', '#3333cc', '#3333ff', '#336600', '#336633', '#336666', '#336699', '#3366cc', '#3366ff', '#339900', '#339933', '#339966', '#339999', '#3399cc', '#3399ff', '#33cc00', '#33cc33', '#33cc66', '#33cc99', '#33cccc', '#33ccff', '#33ff00', '#33ff33', '#33ff66', '#33ff99', '#33ffcc', '#33ffff', '#660000', '#660033', '#660066', '#660099', '#6600cc', '#6600ff', '#663300', '#663333', '#663366', '#663399', '#6633cc', '#6633ff', '#666600', '#666633', '#666666', '#666699', '#6666cc', '#6666ff', '#669900', '#669933', '#669966', '#669999', '#6699cc', '#6699ff', '#66cc00', '#66cc33', '#66cc66', '#66cc99', '#66cccc', '#66ccff', '#66ff00', '#66ff33', '#66ff66', '#66ff99', '#66ffcc', '#66ffff', '#990000', '#990033', '#990066', '#990099', '#9900cc', '#9900ff', '#993300', '#993333', '#993366', '#993399', '#9933cc', '#9933ff', '#996600', '#996633', '#996666', '#996699', '#9966cc', '#9966ff', '#999900', '#999933', '#999966', '#999999', '#9999cc', '#9999ff', '#99cc00', '#99cc33', '#99cc66', '#99cc99', '#99cccc', '#99ccff', '#99ff00', '#99ff33', '#99ff66', '#99ff99', '#99ffcc', '#99ffff', '#cc0000', '#cc0033', '#cc0066', '#cc0099', '#cc00cc', '#cc00ff', '#cc3300', '#cc3333', '#cc3366', '#cc3399', '#cc33cc', '#cc33ff', '#cc6600', '#cc6633', '#cc6666', '#cc6699', '#cc66cc', '#cc66ff', '#cc9900', '#cc9933', '#cc9966', '#cc9999', '#cc99cc', '#cc99ff', '#cccc00', '#cccc33', '#cccc66', '#cccc99', '#cccccc', '#ccccff', '#ccff00', '#ccff33', '#ccff66', '#ccff99', '#ccffcc', '#ccffff', '#ff0000', '#ff0033', '#ff0066', '#ff0099', '#ff00cc', '#ff00ff', '#ff3300', '#ff3333', '#ff3366', '#ff3399', '#ff33cc', '#ff33ff', '#ff6600', '#ff6633', '#ff6666', '#ff6699', '#ff66cc', '#ff66ff', '#ff9900', '#ff9933', '#ff9966', '#ff9999', '#ff99cc', '#ff99ff', '#ffcc00', '#ffcc33', '#ffcc66', '#ffcc99', '#ffcccc', '#ffccff'];
return $webSafeColors[rand(0, sizeof($webSafeColors) - 1)];
}
/**
* Returns index data id
*
* @param int $hostId
* @param int $serviceId
*
* @return int
*/
public function getIndexDataId($hostId, $serviceId)
{
$stmt = $this->dbCs->prepare(
'SELECT id FROM index_data WHERE host_id = :host_id AND service_id = :service_id'
);
$stmt->bindParam(':host_id', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return is_null($row) ? 0 : $row['id'];
}
/**
* Returns true if status graph exists
*
* @param int $hostId
* @param int $serviceId
*
* @return bool
*/
public function statusGraphExists($hostId, $serviceId)
{
$id = $this->getIndexDataId($hostId, $serviceId);
return (bool) (is_file($this->dbStatusPath . '/' . $id . '.rrd'));
}
/**
* Get Curve Config
*
* @param mixed $metric
*
* @return mixed curve config
*/
protected function getCurveDsConfig($metric)
{
$dsData = null;
if (is_null($this->componentsDsCache)) {
$stmt = $this->db->prepare('SELECT * FROM giv_components_template ORDER BY host_id DESC');
$stmt->execute();
$this->componentsDsCache = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$dsDataAssociated = null;
$dsDataRegular = null;
foreach ($this->componentsDsCache as $dsVal) {
$metricPattern = '/^' . str_replace('/', '\/', $dsVal['ds_name']) . '$/i';
$metricPattern = str_replace('*', '.*', $metricPattern);
if (
isset($metric['host_id'], $metric['service_id'])
&& ($dsVal['host_id'] == $metric['host_id'] || $dsVal['host_id'] == '')
&& ($dsVal['service_id'] == $metric['service_id'] || $dsVal['service_id'] == '')
&& preg_match($metricPattern, $metric['metric_name'])
) {
$dsDataAssociated = $dsVal;
break;
}
if (
is_null($dsDataRegular)
&& preg_match('/^' . preg_quote($dsVal['ds_name'], '/') . '$/i', $metric['metric_name'])
) {
$dsDataRegular = $dsVal;
}
}
if (! is_null($dsDataAssociated)) {
$dsData = $dsDataAssociated;
} elseif (! is_null($dsDataRegular)) {
$dsData = $dsDataRegular;
}
if (is_null($dsData)) {
if (is_null($this->dsDefault)) {
$stmt = $this->db->prepare(
"SELECT ds_min, ds_max, ds_minmax_int, ds_last, ds_average, ds_total,
ds_tickness, ds_color_line_mode, ds_color_line, ds_invert
FROM giv_components_template WHERE default_tpl1 = '1'"
);
$stmt->execute();
$this->dsDefault = $stmt->fetch(PDO::FETCH_ASSOC);
}
$dsData = $this->dsDefault;
}
if ($dsData['ds_color_line_mode'] == '1') {
$dsData['ds_color_line'] = $this->getOVDColor($metric['index_id'], $metric['metric_id']);
}
return $dsData;
}
/**
* Clean up ds name in Legend
*
* @param string $dsname
*
* @return string
*/
protected function cleanupDsNameForLegend($dsname)
{
return str_replace(["'", '\\'], [' ', '\\\\'], $dsname);
}
/**
* Flush metrics in rrdcached
*
* @param mixed $metricsId The list of metrics
*
* @return bool
*/
protected function flushRrdcached($metricsId)
{
if (
! isset($this->rrdCachedOptions['rrd_cached_option'])
|| ! in_array($this->rrdCachedOptions['rrd_cached_option'], ['unix', 'tcp'])
) {
return true;
}
$errno = 0;
$errstr = '';
if ($this->rrdCachedOptions['rrd_cached_option'] === 'tcp') {
$sock = fsockopen('127.0.0.1', trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr);
} elseif ($this->rrdCachedOptions['rrd_cached_option'] === 'unix') {
$sock = fsockopen('unix://' . trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr);
} else {
return false;
}
if ($sock === false) {
$this->log('socket connection: ' . $errstr);
return false;
}
if (fputs($sock, "BATCH\n") === false) {
fclose($sock);
return false;
}
if (fgets($sock) === false) {
fclose($sock);
return false;
}
foreach ($metricsId as $metricId) {
$fullpath = realpath($this->dbPath . $metricId . '.rrd');
$cmd = 'FLUSH ' . $fullpath;
if (fputs($sock, $cmd . "\n") === false) {
fclose($sock);
return false;
}
}
if (fputs($sock, ".\n") === false) {
fclose($sock);
return false;
}
if (fgets($sock) === false) {
fclose($sock);
return false;
}
fputs($sock, "QUIT\n");
fclose($sock);
return true;
}
/**
* Connect to databases
*
* @return void
*/
private function initDatabase(): void
{
$this->db = new CentreonDB(CentreonDB::LABEL_DB_CONFIGURATION);
$this->dbCs = new CentreonDB(CentreonDB::LABEL_DB_REALTIME);
}
/**
* Get Legend
*
* @param mixed $metric
*
* @return string
*/
private function getLegend($metric)
{
$legend = '';
if (isset($metric['ds_data']['ds_legend']) && strlen($metric['ds_data']['ds_legend']) > 0) {
$legend = str_replace('"', '\"', $metric['ds_data']['ds_legend']);
} else {
if (! isset($metric['ds_data']['ds_name']) || ! preg_match('/DS/', $metric['ds_data']['ds_name'], $matches)) {
$legend = $this->cleanupDsNameForLegend($metric['metric']);
} else {
$legend = ($metric['ds_data']['ds_name'] ?? '');
}
$legend = str_replace(':', "\:", $legend);
}
return $legend;
}
/**
* Manage Virtual Metrics
*
* @return int|void
*/
private function manageMetrics()
{
$this->vmetricsOrder = [];
if (count($this->vmetrics) == 0) {
return 0;
}
foreach ($this->vmetrics as $vmetricId => &$tm) {
$this->vnodes[$vmetricId] = $vmetricId;
$rpns = explode(',', $tm['rpn_function']);
foreach ($rpns as &$rpn) {
if (isset($this->cacheAllMetrics['r:' . $rpn])) {
$rpn = 'v' . $this->cacheAllMetrics['r:' . $rpn];
} elseif (isset($this->cacheAllMetrics['v:' . $rpn])) {
$vmetricIdChild = $this->cacheAllMetrics['v:' . $rpn];
$this->vnodesDependencies[$vmetricId][] = $vmetricIdChild;
$rpn = 'vv' . $vmetricIdChild;
}
}
$tm['rpn_function'] = implode(',', $rpns);
}
$this->vmetricsOrder = $this->metricUtils->topologicalSort($this->vnodes, $this->vnodesDependencies);
}
/**
* Add a regular metric (not virtual)
*
* @param mixed $metric
* @param int $hidden
*
* @return void
*/
private function addRealMetric($metric, $hidden = null): void
{
if (! $this->CheckDBAvailability($metric['metric_id'])) {
return;
}
if (isset($this->metrics[$metric['metric_id']])) {
return;
}
$this->log('found metric ' . $metric['metric_id']);
/**
* List of id metrics for rrdcached
*/
$this->listMetricsId[] = $metric['metric_id'];
$this->metrics[$metric['metric_id']] = ['index_id' => $metric['index_id'], 'metric_id' => $metric['metric_id'], 'metric' => $metric['metric_name'], 'metric_legend' => $this->cleanupDsNameForLegend($metric['metric_name']), 'unit' => $metric['unit_name'], 'hidden' => 0, 'min' => $metric['min'], 'max' => $metric['max'], 'virtual' => 0];
$this->cacheAllMetrics['r:' . $metric['metric_name']] = $metric['metric_id'];
$dsData = $this->getCurveDsConfig($metric);
$this->metrics[$metric['metric_id']]['ds_data'] = $dsData;
$this->metrics[$metric['metric_id']]['legend'] = $this->getLegend($this->metrics[$metric['metric_id']]);
$this->metrics[$metric['metric_id']]['stack']
= (isset($dsData['ds_stack']) && $dsData['ds_stack'] ? $dsData['ds_stack'] : 0);
$this->metrics[$metric['metric_id']]['warn'] = $metric['warn'];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraphCurve.class.php | centreon/www/class/centreonGraphCurve.class.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
*
*/
/**
* Class
*
* @class CentreonGraphCurve
*/
class CentreonGraphCurve
{
/** @var CentreonDB */
protected $db;
/**
* CentreonGraphCurve constructor
*
* @param $pearDB
*/
public function __construct($pearDB)
{
$this->db = $pearDB;
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'giv_components_template';
$parameters['currentObject']['id'] = 'compo_id';
$parameters['currentObject']['name'] = 'name';
$parameters['currentObject']['comparator'] = 'compo_id';
switch ($field) {
case 'host_id':
$parameters['type'] = 'simple';
$parameters['currentObject']['additionalField'] = 'service_id';
$parameters['externalObject']['object'] = 'centreonService';
$parameters['externalObject']['table'] = 'giv_components_template';
$parameters['externalObject']['id'] = 'service_id';
$parameters['externalObject']['name'] = 'service_description';
$parameters['externalObject']['comparator'] = 'service_id';
break;
case 'compo_id':
$parameters['type'] = 'simple';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':compo' . $v . ',';
$queryValues['compo' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
$selectedGraphCurves = 'WHERE compo_id IN (' . $listValues . ') ';
} else {
$selectedGraphCurves = '""';
}
$queryGraphCurve = 'SELECT DISTINCT compo_id as id, name FROM giv_components_template '
. $selectedGraphCurves . ' ORDER BY name';
$stmt = $this->db->prepare($queryGraphCurve);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($data = $stmt->fetch()) {
$graphCurveList[] = ['id' => $data['id'], 'text' => $data['name']];
}
return $graphCurveList;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonCriticality.class.php | centreon/www/class/centreonCriticality.class.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
*
*/
/**
* Class
*
* @class CentreonCriticality
* @description Class for managing criticality object
*/
class CentreonCriticality
{
/** @var CentreonDB */
protected $db;
/** @var array */
protected $tree;
/**
* CentreonCriticality constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Get data of a criticality object
*
* @param int $critId
* @param bool $service
*
* @throws PDOException
* @return array
*/
public function getData($critId, $service = false)
{
if ($service === false) {
return $this->getDataForHosts($critId);
}
return $this->getDataForServices($critId);
}
/**
* Get data of a criticality object for hosts
*
* @param int $critId
*
* @throws PDOException
* @return array
*/
public function getDataForHosts($critId)
{
static $data = [];
if (! isset($data[$critId])) {
$sql = 'SELECT hc_id, hc_name, level, icon_id, hc_comment
FROM hostcategories
WHERE level IS NOT NULL
ORDER BY level DESC';
$res = $this->db->query($sql);
while ($row = $res->fetchRow()) {
if (! isset($data[$row['hc_id']])) {
$row['name'] = $row['hc_name'];
$data[$row['hc_id']] = $row;
}
}
}
return $data[$critId] ?? null;
}
/**
* Get data of a criticality object for services
*
* @param int $critId
*
* @throws PDOException
* @return array
*/
public function getDataForServices($critId)
{
static $data = [];
if (! isset($data[$critId])) {
$sql = 'SELECT sc_id, sc_name, level, icon_id, sc_description
FROM service_categories
WHERE level IS NOT NULL
ORDER BY level DESC';
$res = $this->db->query($sql);
while ($row = $res->fetchRow()) {
if (! isset($data[$row['sc_id']])) {
$row['name'] = $row['sc_name'];
$data[$row['sc_id']] = $row;
}
}
}
return $data[$critId] ?? null;
}
/**
* Get list of criticality
*
* @param string $searchString
* @param string $orderBy
* @param string $sort
* @param int $offset
* @param int $limit
* @param mixed $service
* @paaram bool $service
* @return array
*/
public function getList(
$searchString = null,
$orderBy = 'level',
$sort = 'ASC',
$offset = null,
$limit = null,
$service = false,
) {
if ($service === false) {
$elements = $this->getListForHosts(
$searchString,
$orderBy,
$sort,
$offset,
$limit
);
} else {
$elements = $this->getListForServices(
$searchString,
$orderBy,
$sort,
$offset,
$limit
);
}
return $elements;
}
/**
* Get real time host criticality id
*
* @param mixed $db
* @param mixed $hostId
*/
public function getRealtimeHostCriticalityId($db, $hostId)
{
static $ids = null;
if (is_null($ids)) {
$sql = "SELECT cvs.host_id, cvs.value as criticality
FROM customvariables cvs
WHERE cvs.name='CRITICALITY_ID'
AND cvs.service_id IS NULL";
$res = $db->query($sql);
$ids = [];
while ($row = $res->fetchRow()) {
$ids[$row['host_id']] = $row['criticality'];
}
}
return $ids[$hostId] ?? 0;
}
/**
* Get real time service criticality id
*
* @param mixed $db
* @param mixed $serviceId
*/
public function getRealtimeServiceCriticalityId($db, $serviceId)
{
static $ids = null;
if (is_null($ids)) {
$sql = "SELECT cvs.service_id, cvs.value as criticality
FROM customvariables cvs
WHERE cvs.name='CRITICALITY_ID'
AND cvs.service_id IS NOT NULL";
$res = $db->query($sql);
$ids = [];
while ($row = $res->fetchRow()) {
$ids[$row['service_id']] = $row['criticality'];
}
}
return $ids[$serviceId] ?? 0;
}
/**
* Create a buffer with all criticality informations
*
* @param $service_id
* return array
*
* @throws PDOException
* @return int|mixed
*/
public function criticitiesConfigOnSTpl($service_id)
{
global $pearDB, $critCache;
if (! count($this->tree)) {
$request = "SELECT service_id, service_template_model_stm_id FROM service
WHERE service_register = '0' AND service_activate = '1' ORDER BY service_template_model_stm_id ASC";
$RES = $pearDB->query($request);
while ($data = $RES->fetchRow()) {
$this->tree[$data['service_id']] = $this->getServiceCriticality($data['service_id']);
}
}
if (isset($this->tree[$service_id]) && $this->tree[$service_id] != 0) {
return $this->tree[$service_id];
}
return 0;
}
/**
* Get list of host criticalities
*
* @param null $searchString
* @param string $orderBy
* @param string $sort
* @param null $offset
* @param null $limit
*
* @throws PDOException
* @return array
*/
protected function getListForHosts(
$searchString = null,
$orderBy = 'level',
$sort = 'ASC',
$offset = null,
$limit = null,
) {
$sql = 'SELECT hc_id, hc_name, level, icon_id, hc_comment
FROM hostcategories
WHERE level IS NOT NULL ';
if (! is_null($searchString) && $searchString != '') {
$sql .= " AND hc_name LIKE '%" . $this->db->escape($searchString) . "%' ";
}
if (! is_null($orderBy) && ! is_null($sort)) {
$sql .= " ORDER BY {$orderBy} {$sort} ";
}
if (! is_null($offset) && ! is_null($limit)) {
$sql .= " LIMIT {$offset},{$limit}";
}
$res = $this->db->query($sql);
$elements = [];
while ($row = $res->fetchRow()) {
$elements[$row['hc_id']] = [];
$elements[$row['hc_id']]['hc_name'] = $row['hc_name'];
$elements[$row['hc_id']]['level'] = $row['level'];
$elements[$row['hc_id']]['icon_id'] = $row['icon_id'];
$elements[$row['hc_id']]['comments'] = $row['hc_comment'];
}
return $elements;
}
/**
* Get list of service criticalities
*
* @param null $searchString
* @param string $orderBy
* @param string $sort
* @param null $offset
* @param null $limit
*
* @throws PDOException
* @return array
*/
protected function getListForServices(
$searchString = null,
$orderBy = 'level',
$sort = 'ASC',
$offset = null,
$limit = null,
) {
$sql = 'SELECT sc_id, sc_name, level, icon_id, sc_description
FROM service_categories
WHERE level IS NOT NULL ';
if (! is_null($searchString) && $searchString != '') {
$sql .= " AND sc_name LIKE '%" . $this->db->escape($searchString) . "%' ";
}
if (! is_null($orderBy) && ! is_null($sort)) {
$sql .= " ORDER BY {$orderBy} {$sort} ";
}
if (! is_null($offset) && ! is_null($limit)) {
$sql .= " LIMIT {$offset},{$limit}";
}
$res = $this->db->query($sql);
$elements = [];
while ($row = $res->fetchRow()) {
$elements[$row['sc_id']] = [];
$elements[$row['sc_id']]['sc_name'] = $row['sc_name'];
$elements[$row['sc_id']]['level'] = $row['level'];
$elements[$row['sc_id']]['icon_id'] = $row['icon_id'];
$elements[$row['sc_id']]['description'] = $row['sc_description'];
}
return $elements;
}
/**
* Get service criticality
*
* @param $service_id
* return array
*
* @throws PDOException
* @return int|mixed
*/
protected function getServiceCriticality($service_id)
{
global $pearDB;
if (! isset($service_id) || $service_id == 0) {
return 0;
}
$request = "SELECT service_id, service_template_model_stm_id FROM service
WHERE service_register = '0' AND service_activate = '1'
AND service_id = {$service_id} ORDER BY service_template_model_stm_id ASC";
$RES = $pearDB->query($request);
if (isset($RES) && $RES->rowCount()) {
while ($data = $RES->fetchRow()) {
$request2 = "select sr.* FROM service_categories_relation sr, service_categories sc
WHERE sr.sc_id = sc.sc_id
AND sr.service_service_id = '" . $data['service_id'] . "'
AND sc.level IS NOT NULL";
$RES2 = $pearDB->query($request2);
if ($RES2->rowCount() != 0) {
$criticity = $RES2->fetchRow();
if ($criticity['sc_id'] && isset($criticity['sc_id'])) {
return $criticity['sc_id'];
}
return 0;
}
return $this->getServiceCriticality($data['service_template_model_stm_id']);
}
}
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonEscalation.class.php | centreon/www/class/centreonEscalation.class.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
*
*/
/**
* Class
*
* @class CentreonEscalation
*/
class CentreonEscalation
{
/** @var CentreonDB */
protected $db;
/**
* CentreonEscalation constructor
*
* @param CentreonDB $pearDB
*/
public function __construct($pearDB)
{
$this->db = $pearDB;
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'escalation';
$parameters['currentObject']['id'] = 'esc_id';
$parameters['currentObject']['name'] = 'esc_name';
$parameters['currentObject']['comparator'] = 'esc_id';
switch ($field) {
case 'esc_cgs':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonContactgroup';
$parameters['relationObject']['table'] = 'escalation_contactgroup_relation';
$parameters['relationObject']['field'] = 'contactgroup_cg_id';
$parameters['relationObject']['comparator'] = 'escalation_esc_id';
break;
case 'esc_hServices':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonService';
$parameters['relationObject']['table'] = 'escalation_service_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['additionalField'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'escalation_esc_id';
break;
case 'esc_hosts':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHost';
$parameters['relationObject']['table'] = 'escalation_host_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['comparator'] = 'escalation_esc_id';
break;
case 'esc_hgs':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHostgroups';
$parameters['relationObject']['table'] = 'escalation_hostgroup_relation';
$parameters['relationObject']['field'] = 'hostgroup_hg_id';
$parameters['relationObject']['comparator'] = 'escalation_esc_id';
break;
case 'esc_sgs':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonServicegroups';
$parameters['relationObject']['table'] = 'escalation_servicegroup_relation';
$parameters['relationObject']['field'] = 'servicegroup_sg_id';
$parameters['relationObject']['comparator'] = 'escalation_esc_id';
break;
case 'esc_metas':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonMeta';
$parameters['relationObject']['table'] = 'escalation_meta_service_relation';
$parameters['relationObject']['field'] = 'meta_service_meta_id';
$parameters['relationObject']['comparator'] = 'escalation_esc_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
global $centreon;
$items = [];
// get list of authorized host categories
if (! $centreon->user->access->admin) {
$hcAcl = $centreon->user->access->getHostCategories();
}
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':hc' . $v . ',';
$queryValues['hc' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected host categories
$query = 'SELECT hc_id, hc_name FROM hostcategories '
. 'WHERE hc_id IN (' . $listValues . ') ORDER BY hc_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetchRow()) {
// hide unauthorized host categories
$hide = false;
if (! $centreon->user->access->admin && count($hcAcl) && ! in_array($row['hc_id'], array_keys($hcAcl))) {
$hide = true;
}
$items[] = ['id' => $row['hc_id'], 'text' => $row['hc_name'], 'hide' => $hide];
}
return $items;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraph.class.php | centreon/www/class/centreonGraph.class.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
*
*/
// this class need also others classes
require_once _CENTREON_PATH_ . 'www/class/centreonDuration.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonACL.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonSession.class.php';
require_once _CENTREON_PATH_ . 'www/include/common/common-Func.php';
/**
* Class
*
* @class CentreonGraph
* @description Class for XML/Ajax request
*/
class CentreonGraph
{
// Percentage over Max limit
public const OVER_MAX_LIMIT_PCT = 3;
// Engine infinite values
public const ENGINE_HIGH_INFINITE = 340282346638528860000000000000000000000;
public const ENGINE_LOW_INFINITE = -340282346638528860000000000000000000000;
/** @var array|null */
public $colorCache;
/** @var array */
public $listMetricsId;
/** @var int */
public $areaNb;
/** @var SimpleXMLElement */
public $XML;
/** @var CentreonGMT */
public $GMT;
/** @var string */
public $user_id;
/** @var bool */
public $onecurve;
/** @var bool */
public $checkcurve;
// Objects
/** @var CentreonDB */
protected $DB;
/** @var CentreonDB */
protected $DBC;
/** @var CentreonHost */
protected $hostObj;
/** @var CentreonService */
protected $serviceObj;
// private vars
/** @var array */
protected $RRDoptions;
/** @var array */
protected $arguments;
/** @var int */
protected $argcount;
/** @var array */
protected $options;
/** @var array */
protected $colors;
/** @var array */
protected $fonts;
/** @var int */
protected $flag;
/** @var */
protected $maxLimit;
// Variables
/** @var int */
protected $debug;
/** @var int|mixed */
protected $compress;
/** @var array */
protected $generalOpt;
/** @var array|string|string[] */
protected $filename;
/** @var string */
protected $commandLine;
/** @var mixed */
protected $dbPath;
/** @var mixed */
protected $dbStatusPath;
/** @var string */
protected $index;
/** @var string[] */
protected $indexData = [
'host_name' => '',
'service_description' => '',
];
/** @var string|int */
protected $templateId;
/** @var array */
protected $templateInformations;
/** @var string */
protected $gprintScaleOption;
/** @var string|int */
protected $graphID;
/** @var array */
protected $metricsEnabled;
/** @var array */
protected $rmetrics;
/** @var array */
protected $vmetrics;
/** @var int[] */
protected $mpointer;
/** @var array */
protected $mlist;
/** @var array */
protected $vname;
/** @var array */
protected $metrics;
/** @var int */
protected $longer;
/** @var array */
protected $rrdCachedOptions;
/**
* CentreonGraph constructor
*
* <code>
* $obj = new CentreonBGRequest($_GET["session_id"], 1, 1, 0, 1);
* </code>
*
* @param string $user_id
* @param int $index
* @param int $debug
* @param int $compress
*
* @throws PDOException
*/
public function __construct($user_id, $index = null, $debug = 0, $compress = null)
{
if (! isset($debug)) {
$this->debug = 0;
}
(! isset($compress)) ? $this->compress = 1 : $this->compress = $compress;
// User ID / Contact ID
$this->user_id = $user_id;
$this->index = htmlentities($index, ENT_QUOTES, 'UTF-8');
// Enable Database Connexions
$this->DB = new CentreonDB();
$this->DBC = new CentreonDB('centstorage');
// Init Objects
$this->hostObj = new CentreonHost($this->DB);
$this->serviceObj = new CentreonService($this->DB);
// Timezone management
$this->GMT = new CentreonGMT();
$this->GMT->getMyGTMFromUser($this->user_id, $this->DB);
$this->RRDoptions = [];
$this->arguments = [];
$this->options = [];
$this->colors = [];
$this->fonts = [];
$this->argcount = 0;
$this->flag = 0;
// Set default parameters
$this->setRRDOption('width', 500);
$this->setRRDOption('height', 120);
$this->getIndexData();
$this->filename = $this->indexData['host_name'] . '-' . $this->indexData['service_description'];
$this->filename = str_replace(['/', '\\'], ['-', '-'], $this->filename);
$this->colorCache = null;
$this->templateInformations = [];
$this->metricsEnabled = [];
$this->rmetrics = [];
$this->vmetrics = [];
$this->mpointer = [0, 0];
$this->mlist = [];
$this->vname = [];
$this->metrics = [];
$this->onecurve = false;
$this->checkcurve = false;
$DBRESULT = $this->DBC->query('SELECT RRDdatabase_path, RRDdatabase_status_path FROM config LIMIT 1');
$config = $DBRESULT->fetch();
$this->dbPath = $config['RRDdatabase_path'];
$this->dbStatusPath = $config['RRDdatabase_status_path'];
unset($config);
$DBRESULT->closeCursor();
$DBRESULT = $this->DB->query('SELECT * FROM options');
while ($opt = $DBRESULT->fetch()) {
$this->generalOpt[$opt['key']] = $opt['value'];
}
$DBRESULT->closeCursor();
unset($opt);
// Get RRDCacheD options
$result = $this->DB->query(
"SELECT config_key, config_value
FROM cfg_centreonbroker_info AS cbi
INNER JOIN cfg_centreonbroker AS cb ON (cb.config_id = cbi.config_id)
INNER JOIN nagios_server AS ns ON (ns.id = cb.ns_nagios_server)
WHERE ns.localhost = '1'
AND cbi.config_key IN ('rrd_cached_option', 'rrd_cached')"
);
while ($row = $result->fetch()) {
$this->rrdCachedOptions[$row['config_key']] = $row['config_value'];
}
if (isset($index)) {
$DBRESULT = $this->DB->prepare('SELECT `metric_id`
FROM `ods_view_details`
WHERE `index_id` = :index_id
AND `contact_id` = :user_id');
$DBRESULT->bindValue(':index_id', $this->index, PDO::PARAM_INT);
$DBRESULT->bindValue(':user_id', $this->user_id, PDO::PARAM_INT);
$DBRESULT->execute();
$metrics_cache = [];
if ($DBRESULT->rowCount()) {
while ($tmp_metrics = $DBRESULT->fetch()) {
$metrics_cache[$tmp_metrics['metric_id']] = 1;
}
}
$DBRESULT->closeCursor();
$DBRESULT = $this->DBC->prepare("SELECT metric_id
FROM metrics
WHERE index_id = :index_id
AND `hidden` = '0'
ORDER BY `metric_name`");
$DBRESULT->bindValue(':index_id', $this->index, PDO::PARAM_INT);
$DBRESULT->execute();
$count = 0;
$odsm = [];
while ($milist = $DBRESULT->fetch()) {
$odsm[$milist['metric_id']] = 1;
$count++;
}
// only one metric => warning/critical threshold curves can be displayed
if ($count === 1) {
$this->onecurve = true;
}
$DBRESULT->closeCursor();
$DBRESULT = $this->DB->prepare("SELECT vmetric_id metric_id
FROM virtual_metrics
WHERE index_id = :index_id
AND (`hidden` = '0' OR `hidden` IS NULL)
AND vmetric_activate = '1'
ORDER BY `vmetric_name`");
$DBRESULT->bindValue(':index_id', $this->index, PDO::PARAM_INT);
$DBRESULT->execute();
while ($milist = $DBRESULT->fetch()) {
$vmilist = 'v' . $milist['metric_id'];
$odsm[$vmilist] = 1;
}
$DBRESULT->closeCursor();
$insertViewDetailsStatement = $this->DB->prepareQuery(
<<<'SQL'
INSERT INTO `ods_view_details`
(`metric_id`, `contact_id`, `all_user`, `index_id`)
VALUES (:metric_id, :user_id, '0', :index_id)
SQL
);
foreach (array_keys($odsm) as $mid) {
if (! isset($metrics_cache[$mid])) {
$this->DB->executePreparedQuery($insertViewDetailsStatement, [
':metric_id' => $mid,
':user_id' => $this->user_id,
':index_id' => $this->index,
]);
}
}
}
}
/**
* @param string|array $metrics
*
* @return void
*/
public function setMetricList($metrics): void
{
if (is_array($metrics) && count($metrics)) {
$this->metricsEnabled = array_keys($metrics);
} elseif ($metrics != '') {
$this->metricsEnabled = [$metrics];
}
if (is_array($this->metricsEnabled) && (count($this->metricsEnabled) == 1)) {
$this->onecurve = true;
}
}
/**
* Initiate the Graph objects
*
* @return void
*/
public function init(): void
{
$this->setRRDOption('interlaced');
$this->setRRDOption('imgformat', 'PNG');
if (isset($this->templateInformations['vertical_label'])) {
$this->setRRDOption('vertical-label', $this->templateInformations['vertical_label']);
}
if ($this->generalOpt['rrdtool_version'] != '1.0') {
$this->setRRDOption('slope-mode');
}
if (isset($this->templateInformations['base']) && $this->templateInformations['base']) {
$this->setRRDOption('base', $this->templateInformations['base']);
}
if (isset($this->templateInformations['width']) && $this->templateInformations['width']) {
$this->setRRDOption('width', $this->templateInformations['width']);
}
if (isset($this->templateInformations['height']) && $this->templateInformations['height']) {
$this->setRRDOption('height', $this->templateInformations['height']);
}
// Init Graph Template Value
if (isset($this->templateInformations['lower_limit']) && $this->templateInformations['lower_limit'] != null) {
$this->setRRDOption('lower-limit', $this->templateInformations['lower_limit']);
}
if (isset($this->templateInformations['upper_limit']) && $this->templateInformations['upper_limit'] != '') {
$this->setRRDOption('upper-limit', $this->templateInformations['upper_limit']);
}
if (
(isset($this->templateInformations['lower_limit'])
&& $this->templateInformations['lower_limit'] != null)
|| (isset($this->templateInformations['upper_limit'])
&& $this->templateInformations['upper_limit'] != null)
) {
$this->setRRDOption('rigid');
$this->setRRDOption('alt-autoscale-max');
}
$this->gprintScaleOption = '%s';
if (isset($this->templateInformations['scaled']) && $this->templateInformations['scaled'] == '0') {
// Disable y-axis scaling
$this->setRRDOption('units-exponent', 0);
// Suppress Scaling in Text Output
$this->gprintScaleOption = '';
}
}
/**
* @throws PDOException
* @return void
*/
public function initCurveList(): void
{
// Check if metrics are enabled
if (isset($this->metricsEnabled) && count($this->metricsEnabled) > 0) {
$l_rmEnabled = [];
$l_vmEnabled = [];
// Separate real and virtual metrics
foreach ($this->metricsEnabled as $l_id) {
if (preg_match('/^v/', $l_id)) {
$l_vmEnabled[] = $l_id;
} else {
$l_rmEnabled[] = $l_id;
}
}
// Create selector for reals metrics
if ($l_rmEnabled !== []) {
$l_rselector
= implode(
',',
array_map(['CentreonGraph', 'quote'], $l_rmEnabled)
);
$this->log('initCurveList with selector [real]= ' . $l_rselector);
}
if ($l_vmEnabled !== []) {
$l_vselector
= implode(
',',
array_map(['CentreonGraph', 'vquote'], $l_vmEnabled)
);
$this->log('initCurveList with selector [virtual]= ' . $l_vselector);
}
} else {
$l_rselector = "index_id = '" . $this->index . "'";
$l_vselector = $l_rselector;
$this->log("initCurveList with selector= {$l_rselector}");
}
// Manage reals metrics
if (isset($l_rselector)) {
$queryCondition = 'metric_id IN (:l_rselector)';
if (! isset($this->metricsEnabled) || count($this->metricsEnabled) <= 0) {
$queryCondition = 'index_id = :index_id';
}
$query = <<<SQL
SELECT
host_id,
service_id,
metric_id,
metric_name,
unit_name,
replace(format(warn,9),',','') warn,
replace(format(crit,9),',','') crit
FROM metrics AS m, index_data AS i
WHERE index_id = id
AND {$queryCondition}
AND m.hidden = '0'
ORDER BY m.metric_name
SQL;
$DBRESULT = $this->DBC->prepare($query);
if (isset($this->metricsEnabled) && count($this->metricsEnabled) > 0) {
$DBRESULT->bindParam(':l_rselector', $l_rselector);
} else {
$DBRESULT->bindParam(':index_id', $this->index);
}
$DBRESULT->execute();
$rmetrics = $DBRESULT->fetchAll(PDO::FETCH_ASSOC);
foreach ($rmetrics as $rmetric) {
$this->mlist[$rmetric['metric_id']] = $this->mpointer[0]++;
$this->rmetrics[] = $rmetric;
}
$DBRESULT->closeCursor();
}
// Manage virtuals metrics
if (isset($l_vselector)) {
$queryCondition = 'vmetric_id IN (:l_vselector)';
if (! isset($this->metricsEnabled) || count($this->metricsEnabled) <= 0) {
$queryCondition = 'index_id = :index_id';
}
$query = <<<SQL
SELECT
vmetric_id
FROM virtual_metrics
WHERE {$queryCondition}
ORDER BY vmetric_name
SQL;
$DBRESULT = $this->DB->prepare($query);
if (isset($this->metricsEnabled) && count($this->metricsEnabled) > 0) {
$DBRESULT->bindParam(':l_vselector', $l_vselector);
} else {
$DBRESULT->bindParam(':index_id', $this->index);
}
$DBRESULT->execute();
$vmetrics = $DBRESULT->fetchAll(PDO::FETCH_ASSOC);
foreach ($vmetrics as $vmetric) {
$this->manageVMetric($vmetric['vmetric_id'], null, null);
}
$DBRESULT->closeCursor();
}
// Merge all metrics
$mmetrics = array_merge($this->rmetrics, $this->vmetrics);
$DBRESULT->closeCursor();
$this->listMetricsId = [];
$components_ds_cache = null;
foreach ($mmetrics as $key => $metric) {
// Check if RRD database is available.
if ($this->CheckDBAvailability($metric['metric_id'])) {
$this->log('found metric ' . $metric['metric_id']);
// List of id metrics for rrdcached
$this->listMetricsId[] = $metric['metric_id'];
if (
isset($this->metricsEnabled)
&& count($this->metricsEnabled)
&& ! in_array($metric['metric_id'], $this->metricsEnabled)
) {
if (isset($metric['need'])) {
$metric['need'] = 1; // Hidden Metric
} else {
$this->log('metric disabled ' . $metric['metric_id']);
continue;
}
}
if (isset($metric['virtual'])) {
$this->metrics[$metric['metric_id']]['virtual'] = $metric['virtual'];
}
$this->metrics[$metric['metric_id']]['metric_id'] = $metric['metric_id'];
$this->metrics[$metric['metric_id']]['metric'] = $this->cleanupDsName($metric['metric_name']);
$this->metrics[$metric['metric_id']]['metric_legend'] = $this->cleanupDsNameForLegend(
$metric['metric_name']
);
$this->metrics[$metric['metric_id']]['unit'] = $metric['unit_name'];
if (! isset($metric['need']) || $metric['need'] != 1) {
if (is_null($components_ds_cache)) {
$components_ds_cache = $this->DB->getAll(
'SELECT * FROM giv_components_template ORDER BY host_id DESC'
);
}
$ds_data_associated = null;
$ds_data_regular = null;
foreach ($components_ds_cache as $dsVal) {
// Prepare pattern for metrics
$metricPattern = '/^' . str_replace('/', '\/', $dsVal['ds_name']) . '$/i';
$metricPattern = str_replace('\\*', '.*', $metricPattern);
// Check associated
if (($dsVal['host_id'] == $metric['host_id'] || $dsVal['host_id'] == '')
&& ($dsVal['service_id'] == $metric['service_id'] || $dsVal['service_id'] == '')
&& preg_match($metricPattern, $metric['metric_name'])) {
$ds_data_associated = $dsVal;
if ($dsVal['ds_legend'] != '') {
$this->metrics[$metric['metric_id']]['metric_legend'] = $dsVal['ds_legend'];
}
break;
}
if (preg_match($metricPattern, $metric['metric_name']) && $dsVal['ds_legend'] != '') {
$this->metrics[$metric['metric_id']]['metric_legend'] = $dsVal['ds_legend'];
}
// Check regular
if (
is_null($ds_data_regular)
&& preg_match('/^' . preg_quote($dsVal['ds_name'], '/') . '$/i', $metric['metric_name'])
) {
$ds_data_regular = $dsVal;
}
}
$ds_data = null;
if (! is_null($ds_data_associated)) {
$ds_data = $ds_data_associated;
} elseif (! is_null($ds_data_regular)) {
$ds_data = $ds_data_regular;
}
if (! isset($ds_data) && ! $ds_data) {
/** *******************************************
* Get default info in default template
*/
$DBRESULT3 = $this->DB->prepare(
"SELECT ds_min, ds_max, ds_minmax_int, ds_last, ds_average, ds_total, ds_tickness,
ds_color_line_mode, ds_color_line
FROM giv_components_template
WHERE default_tpl1 = '1' LIMIT 1"
);
$DBRESULT3->execute();
if ($DBRESULT3->rowCount()) {
foreach ($DBRESULT3->fetch() as $key => $ds_val) {
$ds[$key] = $ds_val;
}
}
$DBRESULT3->closeCursor();
$ds_data = $ds;
}
if ($ds_data['ds_color_line_mode'] == '1') {
// Get random color. Only line will be set
$ds_data['ds_color_line'] = $this->getOVDColor($metric['metric_id']);
}
/** **********************************
* Fetch Datas
*/
foreach ($ds_data as $key => $ds_d) {
if ($key == 'ds_transparency') {
$transparency = dechex(255 - ($ds_d * 255) / 100);
if (strlen($transparency) == 1) {
$transparency = '0' . $transparency;
}
$this->metrics[$metric['metric_id']][$key] = $transparency;
unset($transparency);
} else {
$this->metrics[$metric['metric_id']][$key] = $ds_d;
}
}
$escaped_chars_nb = 0;
if (isset($ds_data['ds_legend']) && strlen($ds_data['ds_legend']) > 0) {
$counter = 0;
$this->metrics[$metric['metric_id']]['legend'] = str_replace(
'"',
'\"',
html_entity_decode($ds_data['ds_legend'], ENT_COMPAT, 'UTF-8'),
$counter
);
$escaped_chars_nb += $counter;
} else {
if (! isset($ds_data['ds_name']) || ! preg_match('/DS/', $ds_data['ds_name'], $matches)) {
$this->metrics[$metric['metric_id']]['legend'] = $this->cleanupDsNameForLegend(
$metric['metric_name'],
true
);
} else {
$this->metrics[$metric['metric_id']]['legend'] = (
$ds_data['ds_name'] ?? ''
);
}
$this->metrics[$metric['metric_id']]['legend'] = str_replace(
':',
"\:",
$this->metrics[$metric['metric_id']]['legend'],
$counter
);
$escaped_chars_nb += $counter;
}
if ($metric['unit_name'] != '') {
$this->metrics[$metric['metric_id']]['legend'] .= ' (' . $metric['unit_name'] . ')';
}
// Checks whether or not string must be decoded
$lgd = $this->metrics[$metric['metric_id']]['legend'];
if (preg_match('!!u', mb_convert_encoding($lgd, 'ISO-8859-1'))) {
$this->metrics[$metric['metric_id']]['legend'] = mb_convert_encoding($lgd, 'ISO-8859-1');
}
$this->metrics[$metric['metric_id']]['legend_len']
= mb_strlen($this->metrics[$metric['metric_id']]['legend'], 'UTF-8') - $escaped_chars_nb;
$this->metrics[$metric['metric_id']]['stack']
= isset($ds_data['ds_stack']) && $ds_data['ds_stack'] ? $ds_data['ds_stack'] : 0;
if ($this->onecurve) {
if (
isset($metric['warn'])
&& $metric['warn'] != 0
&& $metric['warn'] != self::ENGINE_LOW_INFINITE
&& $metric['warn'] != self::ENGINE_HIGH_INFINITE
) {
$this->metrics[$metric['metric_id']]['warn'] = $metric['warn'];
if (! isset($ds_data['ds_color_area_warn']) || empty($ds_data['ds_color_area_warn'])) {
$this->metrics[$metric['metric_id']]['ds_color_area_warn'] = '#ff9a13';
}
}
if (
isset($metric['crit'])
&& $metric['crit'] != 0
&& $metric['crit'] != self::ENGINE_LOW_INFINITE
&& $metric['crit'] != self::ENGINE_HIGH_INFINITE
) {
$this->metrics[$metric['metric_id']]['crit'] = $metric['crit'];
if (! isset($ds_data['ds_color_area_crit']) || empty($ds_data['ds_color_area_crit'])) {
$this->metrics[$metric['metric_id']]['ds_color_area_crit'] = '#e00b3d';
}
}
}
if (isset($metric['need'])) {
$this->metrics[$metric['metric_id']]['need'] = $metric['need'];
} else {
$this->metrics[$metric['metric_id']]['ds_order'] = (
isset($ds_data['ds_order']) && $ds_data['ds_order'] ? $ds_data['ds_order'] : 0
);
}
} else {
// the metric is need for a CDEF metric, but not display
$this->metrics[$metric['metric_id']]['need'] = $metric['need'];
$this->metrics[$metric['metric_id']]['ds_order'] = '0';
}
if (isset($metric['def_type'])) {
$this->metrics[$metric['metric_id']]['def_type'] = $metric['def_type'];
}
if (isset($metric['cdef_order'])) {
$this->metrics[$metric['metric_id']]['cdef_order'] = $metric['cdef_order'];
}
if (isset($metric['rpn_function'])) {
$this->metrics[$metric['metric_id']]['rpn_function'] = $metric['rpn_function'];
}
if (isset($metric['ds_hidecurve'])) {
$this->metrics[$metric['metric_id']]['ds_hidecurve'] = $metric['ds_hidecurve'];
}
}
}
$DBRESULT->closeCursor();
// Sort by ds_order,then legend
uasort($this->metrics, ['CentreonGraph', 'cmpmultiple']);
// add data definitions for each metric
$cpt = 0;
$lcdef = [];
$this->longer = 0;
if (isset($this->metrics)) {
foreach ($this->metrics as $key => &$tm) {
if (! isset($tm['virtual']) && isset($tm['need']) && $tm['need'] == 1) {
$this->addArgument('DEF:v' . $cpt . '=' . $this->dbPath . $key . '.rrd:value:AVERAGE');
$this->vname[$tm['metric']] = 'v' . $cpt;
$cpt++;
continue;
}
if (isset($tm['virtual'])) {
$lcdef[$key] = $tm;
$this->vname[$tm['metric']] = 'vv' . $cpt;
$cpt++;
} else {
if (isset($tm['ds_invert']) && $tm['ds_invert']) {
// Switching RRD options lower-limit & upper-limit
if ($this->onecurve
&& isset($this->RRDoptions['lower-limit'])
&& $this->RRDoptions['lower-limit']
&& isset($this->RRDoptions['upper-limit'])
&& $this->RRDoptions['upper-limit']
) {
$this->switchRRDLimitOption(
$this->RRDoptions['lower-limit'],
$this->RRDoptions['upper-limit']
);
}
$this->addArgument('DEF:vi' . $cpt . '=' . $this->dbPath . $key . '.rrd:value:AVERAGE');
$this->addArgument('CDEF:v' . $cpt . '=vi' . $cpt . ',-1,*');
if (isset($tm['warn']) && $tm['warn'] != 0) {
$tm['warn'] *= -1;
}
if (isset($tm['crit']) && $tm['crit'] != 0) {
$tm['crit'] *= -1;
}
} else {
$this->addArgument('DEF:v' . $cpt . '=' . $this->dbPath . $key . '.rrd:value:AVERAGE');
}
if ($this->onecurve && isset($tm['warn']) && $tm['warn'] != 0
&& isset($tm['crit']) && $tm['crit'] != 0
) {
$l_CMP = ',' . self::getCmpOperator($tm) . ',';
$this->addArgument(
'CDEF:ok' . $cpt . '=v' . $cpt . ',' . $tm['warn'] . $l_CMP . $tm['warn'] . ',v'
. $cpt . ',IF'
);
$this->addArgument(
'CDEF:oc' . $cpt . '=v' . $cpt . ',' . $tm['crit'] . $l_CMP . 'v' . $cpt . ','
. $tm['crit'] . ',-,0,IF'
);
$this->addArgument(
'CDEF:ow' . $cpt . '=v' . $cpt . ',' . $tm['warn'] . $l_CMP . 'v' . $cpt . ','
. $tm['warn'] . ',-,oc' . $cpt . ',-,0,IF'
);
$this->areaNb = $cpt;
}
$this->vname[$tm['metric']] = 'v' . $cpt;
$cpt++;
}
if (! isset($tm['virtual'])) {
if ($tm['legend_len'] > $this->longer) {
$this->longer = $tm['legend_len'];
}
}
}
}
$deftype = [0 => 'CDEF', 1 => 'VDEF'];
uasort($lcdef, ['CentreonGraph', 'cmpcdeforder']);
foreach ($lcdef as $key => &$tm) {
$rpn = $this->subsRPN($tm['rpn_function'], $this->vname);
$arg = $deftype[$tm['def_type']] . ':' . $this->vname[$tm['metric']] . '=' . $rpn;
if (isset($tm['ds_invert']) && $tm['ds_invert']) {
$this->addArgument($arg . ',-1,*');
// Switching RRD options lower-limit & upper-limit
if ($this->onecurve) {
$this->switchRRDLimitOption($this->RRDoptions['lower-limit'], $this->RRDoptions['upper-limit']);
}
if (isset($tm['warn']) && $tm['warn'] != 0) {
$tm['warn'] *= -1;
}
if (isset($tm['crit']) && $tm['crit'] != 0) {
$tm['crit'] *= -1;
}
} else {
$this->addArgument($arg);
}
if ($this->onecurve && isset($tm['warn']) && $tm['warn'] != 0 && isset($tm['crit']) && $tm['crit'] != 0) {
$l_CMP = ',' . self::getCmpOperator($tm) . ',';
$nb = substr($this->vname[$tm['metric']], 2, strlen($this->vname[$tm['metric']]) - 2);
$this->addArgument(
'CDEF:ok' . $nb . '=' . $this->vname[$tm['metric']] . ',' . $tm['warn']
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGMT.class.php | centreon/www/class/centreonGMT.class.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
*
*/
// file centreon.config.php may not exist in test environment
$configFile = realpath(__DIR__ . '/../../config/centreon.config.php');
if ($configFile !== false) {
include_once $configFile;
}
require_once realpath(__DIR__ . '/centreonDBInstance.class.php');
/**
* Class
*
* @class CentreonGMT
*/
class CentreonGMT
{
/** @var int */
public $use = 1;
/** @var array|null */
protected $timezoneById = null;
/** @var array */
protected $timezones;
/** @var string|null */
protected $myGMT = null;
/** @var array */
protected $aListTimezone;
/** @var array */
protected $myTimezone;
/** @var array */
protected $hostLocations = [];
/** @var array */
protected $pollerLocations = [];
/**
* Default timezone setted in adminstration/options
* @var string|null
*/
protected $sDefaultTimezone = null;
/**
* CentreonGMT constructor
*/
public function __construct()
{
}
/**
* @return int
*/
public function used()
{
return $this->use;
}
/**
* @param $value
*
* @return void
*/
public function setMyGMT($value): void
{
$this->myGMT = $value;
}
/**
* @return array
*/
public function getGMTList()
{
if (is_null($this->timezoneById)) {
$this->getList();
}
return $this->timezoneById;
}
/**
* @return string|null
*/
public function getMyGMT()
{
return $this->myGMT;
}
/**
* This method return timezone of user
*
* @return string
*/
public function getMyTimezone()
{
if (is_null($this->timezoneById)) {
$this->getList();
}
if (is_null($this->myTimezone)) {
if (! is_null($this->myGMT) && isset($this->timezoneById[$this->myGMT])) {
$this->myTimezone = $this->timezoneById[$this->myGMT];
} else {
$this->getCentreonTimezone();
if (! empty($this->sDefaultTimezone) && ! empty($this->timezoneById[$this->sDefaultTimezone])) {
$this->myTimezone = $this->timezoneById[$this->sDefaultTimezone];
} else { // if we take the empty PHP
$this->myTimezone = date_default_timezone_get();
}
}
}
$this->myTimezone = trim($this->myTimezone);
return $this->myTimezone;
}
/**
* @param string $format
* @param string $date
* @param string|null $gmt
*
* @throws Exception
* @return string
*/
public function getDate($format, $date, $gmt = null)
{
$return = '';
if (! $date) {
$date = 'N/A';
}
if ($date == 'N/A') {
return $date;
}
if (! isset($gmt)) {
$gmt = $this->myGMT;
}
if (empty($gmt)) {
$gmt = date_default_timezone_get();
}
if (isset($date, $gmt)) {
$sDate = new DateTime();
$sDate->setTimestamp($date);
$sDate->setTimezone(new DateTimeZone($this->getActiveTimezone($gmt)));
$return = $sDate->format($format);
}
return $return;
}
/**
* @param string $date
* @param string|null $gmt
*
* @throws Exception
* @return int|string
*/
public function getCurrentTime($date = 'N/A', $gmt = null)
{
if ($date == 'N/A') {
return $date;
}
if (is_null($gmt)) {
$gmt = $this->myGMT;
}
$sDate = new DateTime();
$sDate->setTimestamp($date);
$sDate->setTimezone(new DateTimeZone($this->getActiveTimezone($gmt)));
return $sDate->getTimestamp();
}
/**
* @param string $date
* @param string|null $gmt
* @param int $reverseOffset
*
* @throws Exception
* @return string
*/
public function getUTCDate($date, $gmt = null, $reverseOffset = 1)
{
$return = '';
if (! isset($gmt)) {
$gmt = $this->myGMT;
}
if (isset($date, $gmt)) {
if (! is_numeric($date)) {
$sDate = new DateTime($date);
} else {
$sDate = new DateTime();
$sDate->setTimestamp($date);
}
$sDate->setTimezone(new DateTimeZone($this->getActiveTimezone($gmt)));
$iTimestamp = $sDate->getTimestamp();
$sOffset = $sDate->getOffset();
$return = $iTimestamp + ($sOffset * $reverseOffset);
}
return $return;
}
/**
* @param string $date
* @param string|null $gmt
* @param int $reverseOffset
*
* @throws Exception
* @return string
*/
public function getUTCDateFromString($date, $gmt = null, $reverseOffset = 1)
{
$return = '';
if (! isset($gmt)) {
$gmt = $this->myGMT;
}
if ($gmt == null) {
$gmt = date_default_timezone_get();
}
if (isset($date, $gmt)) {
if (! is_numeric($date)) {
$sDate = new DateTime($date);
} else {
$sDate = new DateTime();
$sDate->setTimestamp($date);
}
$localDate = new DateTime();
$sDate->setTimezone(new DateTimeZone($this->getActiveTimezone($gmt)));
$iTimestamp = $sDate->getTimestamp();
$sOffset = $sDate->getOffset();
$sLocalOffset = $localDate->getOffset();
$return = $iTimestamp - (($sOffset - $sLocalOffset) * $reverseOffset);
}
return $return;
}
/**
* @param $gmt
* @return string
*/
public function getDelaySecondsForRRD($gmt)
{
$str = '';
if ($gmt) {
if ($gmt > 0) {
$str .= '+';
}
} else {
return '';
}
}
/**
* @param $sid
*
* @return int|void
*/
public function getMyGMTFromSession($sid = null)
{
if (! isset($sid)) {
return 0;
}
try {
$query = 'SELECT `contact_location` FROM `contact`, `session` '
. 'WHERE `session`.`user_id` = `contact`.`contact_id` '
. 'AND `session_id` = :session_id LIMIT 1';
$statement = CentreonDBInstance::getDbCentreonInstance()->prepare($query);
$statement->bindValue(':session_id', $sid, PDO::PARAM_STR);
$statement->execute();
$this->myGMT = ($info = $statement->fetch()) ? $info['contact_location'] : 0;
} catch (PDOException $e) {
$this->myGMT = 0;
}
}
/**
* @param $userId
* @param CentreonDB $DB
*
* @return int|mixed|string|null
*/
public function getMyGTMFromUser($userId, $DB = null)
{
if (! empty($userId)) {
try {
$DBRESULT = CentreonDBInstance::getDbCentreonInstance()->query('SELECT `contact_location` FROM `contact` '
. 'WHERE `contact`.`contact_id` = ' . $userId . ' LIMIT 1');
$info = $DBRESULT->fetchRow();
$DBRESULT->closeCursor();
$this->myGMT = $info['contact_location'];
} catch (PDOException $e) {
$this->myGMT = 0;
}
} else {
$this->myGMT = 0;
}
return $this->myGMT;
}
/**
* @param string|int $host_id
* @param string $date_format
*
* @throws Exception
* @return DateTime
*/
public function getHostCurrentDatetime($host_id, $date_format = 'c')
{
$locations = $this->getHostLocations();
$timezone = $locations[$host_id] ?? '';
$sDate = new DateTime();
$sDate->setTimezone(new DateTimeZone($this->getActiveTimezone($timezone)));
return $sDate;
}
/**
* @param $date
* @param string|int $hostId
* @param string $dateFormat
* @param int $reverseOffset
*
* @throws Exception
* @return string
*/
public function getUTCDateBasedOnHostGMT($date, $hostId, $dateFormat = 'c', $reverseOffset = 1)
{
$locations = $this->getHostLocations();
if (isset($locations[$hostId]) && $locations[$hostId] != '0') {
$date = $this->getUTCDate($date, $locations[$hostId], $reverseOffset);
}
return date($dateFormat, $date);
}
/**
* @param string $date
* @param string|int $hostId
* @param string $dateFormat
*
* @throws Exception
* @return float|int|string
*/
public function getUTCTimestampBasedOnHostGMT($date, $hostId, $dateFormat = 'c')
{
$locations = $this->getHostLocations();
if (isset($locations[$hostId]) && $locations[$hostId] != '0') {
$date = $this->getUTCDate($date, $locations[$hostId]);
}
return $date;
}
/**
* @param $hostId
*
* @return mixed|null
*/
public function getUTCLocationHost($hostId)
{
$locations = $this->getHostLocations();
return $locations[$hostId] ?? null;
}
/**
* Get the list of timezone
*
* @return array
*/
public function getList()
{
$queryList = 'SELECT timezone_id, timezone_name, timezone_offset FROM timezone ORDER BY timezone_name asc';
try {
$res = CentreonDBInstance::getDbCentreonInstance()->query($queryList);
} catch (PDOException $e) {
return [];
}
$this->timezoneById = [];
while ($row = $res->fetchRow()) {
$this->timezones[$row['timezone_name']] = $row['timezone_id'];
$this->timezoneById[$row['timezone_id']] = $row['timezone_name'];
$this->aListTimezone[$row['timezone_id']] = $row;
}
return $this->timezoneById;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':timezone' . $v . ',';
$queryValues['timezone' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected timezones
$query = 'SELECT timezone_id, timezone_name FROM timezone '
. 'WHERE timezone_id IN (' . $listValues . ') ORDER BY timezone_name ';
$stmt = CentreonDBInstance::getDbCentreonInstance()->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['timezone_id'], 'text' => $row['timezone_name']];
}
return $items;
}
/**
* Get list of timezone of host
* @return array
*/
public function getHostLocations()
{
if (count($this->hostLocations)) {
return $this->hostLocations;
}
$this->getPollerLocations();
$this->hostLocations = [];
$query = 'SELECT host_id, instance_id, timezone FROM hosts WHERE enabled = 1 ';
try {
$res = CentreonDBInstance::getDbCentreonStorageInstance()->query($query);
while ($row = $res->fetchRow()) {
if ($row['timezone'] == '' && isset($this->pollerLocations[$row['instance_id']])) {
$this->hostLocations[$row['host_id']] = $this->pollerLocations[$row['instance_id']];
} else {
$this->hostLocations[$row['host_id']] = str_replace(':', '', $row['timezone']);
}
}
} catch (PDOException $e) {
// Nothing to do
}
return $this->hostLocations;
}
/**
* Get list of timezone of pollers
* @return array
*/
public function getPollerLocations()
{
if (count($this->pollerLocations)) {
return $this->pollerLocations;
}
$query = 'SELECT ns.id, t.timezone_name '
. 'FROM cfg_nagios cfgn, nagios_server ns, timezone t '
. 'WHERE cfgn.nagios_activate = "1" '
. 'AND cfgn.nagios_server_id = ns.id '
. 'AND cfgn.use_timezone = t.timezone_id ';
try {
$res = CentreonDBInstance::getDbCentreonInstance()->query($query);
while ($row = $res->fetchRow()) {
$this->pollerLocations[$row['id']] = $row['timezone_name'];
}
} catch (Exception $e) {
// Nothing to do
}
return $this->pollerLocations;
}
/**
* Get default timezone setted in admintration/options
*
* @return string
*/
public function getCentreonTimezone()
{
if (is_null($this->sDefaultTimezone)) {
$sTimezone = '';
$query = "SELECT `value` FROM `options` WHERE `key` = 'gmt' LIMIT 1";
try {
$res = CentreonDBInstance::getDbCentreonInstance()->query($query);
$row = $res->fetchRow();
$sTimezone = $row['value'];
} catch (Exception $e) {
// Nothing to do
}
$this->sDefaultTimezone = $sTimezone;
}
return $this->sDefaultTimezone;
}
/**
* This method verifies the timezone which is to be used in the other appellants methods.
* In priority, it uses timezone of the object, else timezone of centreon, then lattest timezone PHP
*
* @param string $gmt
* @return string timezone
*/
public function getActiveTimezone($gmt)
{
$sTimezone = '';
if (is_null($this->timezoneById)) {
$this->getList();
}
if (isset($this->timezones[$gmt])) {
$sTimezone = $gmt;
} elseif (isset($this->timezoneById[$gmt])) {
$sTimezone = $this->timezoneById[$gmt];
} else {
$this->getCentreonTimezone();
if (! empty($this->sDefaultTimezone) && ! empty($this->timezones[$this->sDefaultTimezone])) {
$sTimezone = $this->timezones[$this->sDefaultTimezone];
} else { // if we take the empty PHP
$sTimezone = date_default_timezone_get();
}
}
return $sTimezone;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonConfigCentreonBroker.php | centreon/www/class/centreonConfigCentreonBroker.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;
use Centreon\Domain\Log\Logger;
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\FeatureFlags;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
require_once _CENTREON_PATH_ . 'www/class/centreon-config/centreonMainCfg.class.php';
require_once _CENTREON_PATH_ . 'www/include/common/vault-functions.php';
/**
* Class
*
* @class CentreonConfigCentreonBroker
* @description Class for Centreon Broker configuration
*/
class CentreonConfigCentreonBroker
{
use VaultTrait;
/** @var int */
public $nbSubGroup = 1;
/** @var array */
public $arrayMultiple = [];
/** @var CentreonDB */
private $db;
/** @var array */
private $attrText = ['size' => '120'];
/** @var array */
private $attrInt = ['size' => '10', 'class' => 'v_number'];
/** @var string */
private $globalCommandFile = null;
/** @var array<int|string,mixed>|null */
private $tagsCache = null;
/** @var array<int|string,mixed>|null */
private $logsCache = null;
/** @var array<int|string,string>|null */
private $logsLevelCache = null;
/** @var array<int,string>|null */
private $typesCache = null;
/** @var array<int,string>|null */
private $typesNameCache = null;
/** @var array */
private $blockCache = [];
/** @var array */
private $fieldtypeCache = [];
/** @var array */
private $blockInfoCache = [];
/** @var array */
private $listValues = [];
/** @var array */
private $defaults = [];
/** @var array */
private $attrsAdvSelect = ['style' => 'width: 270px; height: 70px;'];
/** @var string */
private $advMultiTemplate = '<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>{javascript}';
/**
* CentreonConfigCentreonBroker construtor
*
* @param CentreonDB $db The connection to centreon database
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Serialize inner data
* @return array
*/
public function __sleep()
{
$this->db = null;
return ['attrText', 'attrInt', 'tagsCache', 'typesCache', 'blockCache', 'blockInfoCache', 'listValues', 'defaults', 'fieldtypeCache'];
}
/**
* Set the database
*
* @param CentreonDB $db The connection to centreon database
*/
public function setDb($db): void
{
$this->db = $db;
}
/**
* Return the list of tags
*
* @return array
*/
public function getTags()
{
if (! is_null($this->tagsCache)) {
return $this->tagsCache;
}
$query = 'SELECT cb_tag_id, tagname
FROM cb_tag
ORDER BY tagname';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$this->tagsCache = [];
while ($row = $res->fetchRow()) {
$this->tagsCache[$row['cb_tag_id']] = $row['tagname'];
}
return $this->tagsCache;
}
/**
* Return the list of logs option
*
* @return array
*/
public function getLogsOption()
{
if (! is_null($this->logsCache)) {
return $this->logsCache;
}
$query = 'SELECT log.`id`, log.`name` FROM `cb_log` log';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$this->logsCache = [];
while ($row = $res->fetchRow()) {
$this->logsCache[$row['id']] = $row['name'];
}
return $this->logsCache;
}
/**
* Return the list of logs level
*
* @return array
*/
public function getLogsLevel()
{
if (! is_null($this->logsLevelCache)) {
return $this->logsLevelCache;
}
$query = 'SELECT `id`, `name` FROM `cb_log_level`';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$this->logsLevelCache = [];
while ($row = $res->fetchRow()) {
$this->logsLevelCache[$row['id']] = $row['name'];
}
return $this->logsLevelCache;
}
/**
* Get the tagname
*
* @param int $tagId The tag id
* @return string|null null in error
*/
public function getTagName($tagId)
{
if (! is_null($this->tagsCache) && isset($this->tagsCache[$tagId])) {
return $this->tagsCache[$tagId];
}
$query = 'SELECT tagname FROM cb_tag WHERE cb_tag_id = %d';
try {
$res = $this->db->query(sprintf($query, $tagId));
} catch (PDOException $e) {
return null;
}
$row = $res->fetch();
if (is_null($row)) {
return null;
}
return $row['tagname'];
}
/**
* Get the typename
*
* @param int $typeId The type id
* @return string|null null in error
*/
public function getTypeShortname($typeId)
{
if (! is_null($this->typesCache) && isset($this->typesCache[$typeId])) {
return $this->typesCache[$typeId];
}
$query = 'SELECT type_shortname FROM cb_type WHERE cb_type_id = %d';
try {
$res = $this->db->query(sprintf($query, $typeId));
} catch (PDOException $e) {
return null;
}
$row = $res->fetch();
if (is_null($row)) {
return null;
}
$this->typesCache[$typeId] = $row['type_shortname'];
return $this->typesCache[$typeId];
}
/**
* Get the Centreon Broker type name
*
* @param int $typeId The type id
* @return string|null null in error
*/
public function getTypeName($typeId)
{
if (! is_null($this->typesNameCache) && isset($this->typesNameCache[$typeId])) {
return $this->typesNameCache[$typeId];
}
$query = 'SELECT type_name FROM cb_type WHERE cb_type_id = %d';
try {
$res = $this->db->query(sprintf($query, $typeId));
} catch (PDOException $e) {
return null;
}
$row = $res->fetch();
if (is_null($row)) {
return null;
}
$this->typesNameCache[$typeId] = $row['type_name'];
return $this->typesNameCache[$typeId];
}
/**
* Return the list of config block
*
* The id is 'tag_id'_'type_id'
* The name is "module_name - type_name"
*
* @param int $tagId The tag id
* @return array
*/
public function getListConfigBlock($tagId)
{
if (isset($this->blockCache[$tagId])) {
return $this->blockCache[$tagId];
}
$query = 'SELECT m.name, t.cb_type_id, t.type_name, ttr.cb_type_uniq
FROM cb_module m, cb_type t, cb_tag_type_relation ttr
WHERE m.cb_module_id = t.cb_module_id AND ttr.cb_type_id = t.cb_type_id AND ttr.cb_tag_id = %d';
try {
$res = $this->db->query(sprintf($query, $tagId));
} catch (PDOException $e) {
return [];
}
$this->blockCache[$tagId] = [];
while ($row = $res->fetch()) {
$name = $row['name'] . ' - ' . $row['type_name'];
$id = $tagId . '_' . $row['cb_type_id'];
$this->blockCache[$tagId][] = ['id' => $id, 'name' => $name, 'unique' => $row['cb_type_uniq']];
}
return $this->blockCache[$tagId];
}
/**
* Create the HTML_QuickForm object with element for a block
*
* @param string $blockId The block id ('tag_id'_'type_id')
* @param int $page The centreon page id
* @param int $formId The form post
* @param int $config_id
* @throws HTML_QuickForm_Error
* @return HTML_QuickFormCustom
*/
public function quickFormById($blockId, $page, $formId = 1, $config_id = 0)
{
[$tagId, $typeId] = explode('_', $blockId);
$fields = $this->getBlockInfos($typeId);
$tag = $this->getTagName($tagId);
$this->nbSubGroup = 1;
$qf = new HTML_QuickFormCustom('form_' . $formId, 'post', '?p=' . $page);
$qf->addElement(
'text',
$tag . '[' . $formId . '][name]',
_('Name'),
array_merge(
$this->attrText,
['id' => $tag . '[' . $formId . '][name]', 'class' => 'v_required', 'onBlur' => "this.value = this.value.replace(/ /g, '_')"]
)
);
$type = $this->getTypeShortname($typeId);
$qf->addElement('hidden', $tag . '[' . $formId . '][type]');
$qf->setDefaults([$tag . '[' . $formId . '][type]' => $type]);
$typeName = $this->getTypeName($typeId);
$qf->addElement('header', 'typeName', $typeName);
$qf->addElement('hidden', $tag . '[' . $formId . '][blockId]');
$qf->setDefaults([$tag . '[' . $formId . '][blockId]' => $blockId]);
foreach ($fields as $field) {
$parentGroup = '';
$isMultiple = false;
$elementName = $this->getElementName($tag, $formId, $field, $isMultiple);
if ($isMultiple && $field['group'] !== '') {
$displayNameGroup = '';
$parentGroup = $this->getParentGroups($field['group'], $isMultiple, $displayNameGroup);
$parentGroup = $parentGroup . '_' . $formId;
}
$elementType = null;
$elementAttr = [];
$default = null;
$displayName = _($field['displayname']);
switch ($field['fieldtype']) {
case 'int':
$elementType = 'text';
$elementAttr = $this->attrInt;
if ($field['hook_name'] != '') {
$elementAttr = array_merge($elementAttr, ['onchange' => $field['hook_name'] . '.onChange(' . $field['hook_arguments'] . ')(this)', 'data-ontab-fn' => $field['hook_name'], 'data-ontab-arg' => $field['hook_arguments']]);
}
break;
case 'select':
$elementType = 'select';
$elementAttr = $this->getListValues($field['id']);
$default = $this->getDefaults($field['id']);
break;
case 'radio':
$tmpRadio = [];
if ($isMultiple && $parentGroup != '') {
$elementAttr = array_merge($elementAttr, ['parentGroup' => $parentGroup, 'displayNameGroup' => $displayNameGroup]);
}
if ($field['hook_name'] != '') {
$elementAttr = array_merge($elementAttr, ['onchange' => $field['hook_name'] . '.onChange(' . $field['hook_arguments'] . ')(this)', 'data-ontab-fn' => $field['hook_name'], 'data-ontab-arg' => $field['hook_arguments']]);
}
foreach ($this->getListValues($field['id']) as $key => $value) {
$elementAttr['id'] = uniqid('qf_' . $key . '_#index#');
$tmpRadio[] = $qf->createElement(
'radio',
$field['fieldname'],
null,
_($value),
$key,
$elementAttr
);
}
$qf->addGroup($tmpRadio, $elementName, _($field['displayname']), ' ');
$default = $this->getDefaults($field['id']);
break;
case 'password':
$elementType = 'password';
$elementAttr = $this->attrText;
break;
case 'multiselect':
$displayName = [_($field['displayname']), _('Available'), _('Selected')];
$elementType = 'advmultiselect';
$elementAttr = $this->getListValues($field['id']);
break;
case 'text':
default:
$elementType = 'text';
$elementAttr = $this->attrText;
break;
}
// If get information for read-only in database
if (! is_null($field['value']) && $field['value'] !== false) {
$elementType = null;
$roValue = $this->getInfoDb($field['value']);
$field['value'] = $roValue;
if (is_array($roValue)) {
$qf->addElement('select', $elementName, $displayName, $roValue);
} else {
$qf->addElement('text', $elementName, $displayName, $this->attrText);
}
$qf->freeze($elementName);
}
// Add required informations
if ($field['required'] && is_null($field['value']) && $elementType != 'select') {
$elementAttr = array_merge($elementAttr, ['id' => $elementName, 'class' => 'v_required']);
}
$elementAttrSelect = [];
if ($isMultiple && $parentGroup != '') {
if ($elementType != 'select') {
$elementAttr = array_merge($elementAttr, ['parentGroup' => $parentGroup, 'displayNameGroup' => $displayNameGroup]);
if ($field['hook_name'] != '') {
$elementAttr = array_merge($elementAttr, ['onchange' => $field['hook_name'] . '.onChange(' . $field['hook_arguments'] . ')(this)', 'data-ontab-fn' => $field['hook_name'], 'data-ontab-arg' => $field['hook_arguments']]);
}
} else {
$elementAttrSelect = ['parentGroup' => $parentGroup, 'displayNameGroup' => $displayNameGroup];
if ($field['hook_name'] != '') {
$elementAttrSelect = array_merge($elementAttrSelect, ['onchange' => $field['hook_name'] . '.onChange(' . $field['hook_arguments'] . ')(this)', 'data-ontab-fn' => $field['hook_name'], 'data-ontab-arg' => $field['hook_arguments']]);
}
}
}
// Add elements
if (! is_null($elementType)) {
if ($elementType == 'advmultiselect') {
$el = $qf->addElement(
$elementType,
$elementName,
$displayName,
$elementAttr,
$this->attrsAdvSelect,
SORT_ASC
);
$el->setButtonAttributes('add', ['value' => _('Add'), 'class' => 'btc bt_success']);
$el->setButtonAttributes('remove', ['value' => _('Remove'), 'class' => 'btc bt_danger']);
$el->setElementTemplate($this->advMultiTemplate);
} else {
$el = $qf->addElement($elementType, $elementName, $displayName, $elementAttr, $elementAttrSelect);
}
}
// Defaults values
if (! is_null($field['value']) && $field['value'] !== false) {
if ($field['fieldtype'] != 'radio') {
$qf->setDefaults([$elementName => $field['value']]);
} else {
$qf->setDefaults([$elementName . '[' . $field['fieldname'] . ']' => $field['value']]);
}
} elseif (! is_null($default)) {
if ($field['fieldtype'] != 'radio') {
$qf->setDefaults([$elementName => $default]);
} else {
$qf->setDefaults([$elementName . '[' . $field['fieldname'] . ']' => $default]);
}
}
}
return $qf;
}
/**
* Generate Cdata tag
*
* @throws Exception
* @return void
*/
public function generateCdata(): void
{
$cdata = CentreonData::getInstance();
if (isset($this->arrayMultiple)) {
foreach ($this->arrayMultiple as $key => $multipleGroup) {
ksort($multipleGroup);
$cdata->addJsData('clone-values-' . $key, htmlspecialchars(
json_encode($multipleGroup),
ENT_QUOTES
));
$cdata->addJsData('clone-count-' . $key, count($multipleGroup));
}
}
}
/**
* Get informations for a block
*
* @param int $typeId The type id
*
* @return array|false
*/
public function getBlockInfos($typeId)
{
if (isset($this->blockInfoCache[$typeId])) {
return $this->blockInfoCache[$typeId];
}
// Get the list of fields for a block
$fields = [];
$query = <<<'SQL'
SELECT field.cb_field_id, field.fieldname, field.displayname, field.fieldtype, field.description, field.external,
field.cb_fieldgroup_id, field_grp.groupname,
field_rel.is_required, field_rel.order_display, field_rel.jshook_name, field_rel.jshook_arguments
FROM cb_field field
INNER JOIN cb_type_field_relation field_rel
ON field_rel.cb_field_id = field.cb_field_id
AND (field_rel.cb_type_id = :type_id
OR field_rel.cb_type_id IN (
SELECT cb_type_id
FROM cb_type type
INNER JOIN cb_module_relation module_rel
ON module_rel.cb_module_id = type.cb_module_id
AND module_rel.inherit_config = 1
AND type.cb_module_id IN (
SELECT module_depend_id
FROM cb_module_relation module_rel2
INNER JOIN cb_type type2
ON type2.cb_module_id = module_rel2.cb_module_id
AND module_rel2.inherit_config = 1
AND type2.cb_type_id = :type_id
)
)
)
LEFT JOIN cb_fieldgroup field_grp
ON field_grp.cb_fieldgroup_id = field.cb_fieldgroup_id
AND field_grp.multiple = 1
ORDER BY field_rel.order_display;
SQL;
try {
$statement = $this->db->prepare($query);
$statement->bindValue(':type_id', $typeId, PDO::PARAM_INT);
$statement->execute();
} catch (PDOException $e) {
return false;
}
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$field = [];
$field['id'] = $row['cb_field_id'];
$field['fieldname'] = $row['fieldname'];
$field['displayname'] = $row['displayname'];
$field['fieldtype'] = $row['fieldtype'];
$field['description'] = $row['description'];
$field['required'] = $row['is_required'];
$field['order'] = $row['order_display'];
$field['group'] = $row['cb_fieldgroup_id'];
$field['group_name'] = $row['groupname'];
$field['hook_name'] = $row['jshook_name'];
$field['hook_arguments'] = $row['jshook_arguments'];
$field['value'] = ! is_null($row['external']) && $row['external'] != '' ? $row['external'] : null;
$fields[] = $field;
}
usort($fields, [$this, 'sortField']);
$this->blockInfoCache[$typeId] = $fields;
return $this->blockInfoCache[$typeId];
}
/**
* Return a cb type id for the shortname given
*
* @param string $typeName
*
* @throws PDOException
* @return int|null
*/
public function getTypeId($typeName)
{
$typeId = null;
$queryGetType = "SELECT cb_type_id FROM cb_type WHERE type_shortname = '{$typeName}'";
$res = $this->db->query($queryGetType);
if ($res) {
while ($row = $res->fetch()) {
$typeId = $row['cb_type_id'];
}
}
return $typeId;
}
/**
* Insert a configuration into the database
*
* @param array $values The post array
* @return bool
*/
public function insertConfig(array $values): bool
{
$objMain = new CentreonMainCfg();
// Insert the Centreon Broker configuration
$columnNames = $this->getColumnNamesForQuery($values);
$query = 'INSERT INTO cfg_centreonbroker ('
. implode(', ', $columnNames)
. ') VALUES (:'
. implode(', :', $columnNames)
. ')';
try {
$stmt = $this->db->prepare($query);
$stmt->bindValue(':config_name', $values['name'], PDO::PARAM_STR);
$stmt->bindValue(':config_filename', $values['filename'], PDO::PARAM_STR);
$stmt->bindValue(':ns_nagios_server', $values['ns_nagios_server'], PDO::PARAM_STR);
$stmt->bindValue(':config_activate', $values['activate']['activate'], PDO::PARAM_STR);
$stmt->bindValue(':daemon', $values['activate_watchdog']['activate_watchdog'], PDO::PARAM_STR);
$stmt->bindValue(':cache_directory', $values['cache_directory'], PDO::PARAM_STR);
$stmt->bindValue(':log_directory', $values['log_directory'] ?? null, PDO::PARAM_STR);
$stmt->bindValue(':log_filename', $values['log_filename'] ?? null, PDO::PARAM_STR);
$stmt->bindValue(
':event_queue_max_size',
(int) $this->checkEventMaxQueueSizeValue($values['event_queue_max_size']),
PDO::PARAM_INT
);
$stmt->bindValue(
':event_queues_total_size',
! empty($values['event_queues_total_size']) ? (int) $values['event_queues_total_size'] : null,
PDO::PARAM_INT
);
$stmt->bindValue(':command_file', $values['command_file'] ?? null, PDO::PARAM_STR);
$stmt->bindValue(
':pool_size',
! empty($values['pool_size']) ? (int) $values['pool_size'] : null,
PDO::PARAM_INT
);
if (in_array('config_write_timestamp', $columnNames)) {
$stmt->bindValue(
':config_write_timestamp',
$values['write_timestamp']['write_timestamp'],
PDO::PARAM_STR
);
}
if (in_array('config_write_thread_id', $columnNames)) {
$stmt->bindValue(
':config_write_thread_id',
$values['write_thread_id']['write_thread_id'],
PDO::PARAM_STR
);
}
if (in_array('stats_activate', $columnNames)) {
$stmt->bindValue(':stats_activate', $values['stats_activate']['stats_activate'], PDO::PARAM_STR);
}
if (in_array('log_max_size', $columnNames)) {
$stmt->bindValue(':log_max_size', $values['log_max_size'], PDO::PARAM_INT);
}
if (in_array('bbdo_version', $columnNames)) {
$stmt->bindValue(':bbdo_version', $values['bbdo_version'], PDO::PARAM_STR);
}
$stmt->execute();
} catch (PDOException $e) {
return false;
}
$iIdServer = $values['ns_nagios_server'];
$iId = $objMain->insertServerInCfgNagios(-1, $iIdServer, $values['name']);
if (! empty($iId)) {
$objMain->insertDefaultCfgNagiosLogger($iId);
}
// Get the ID
$query = 'SELECT config_id FROM cfg_centreonbroker WHERE config_name = :config_name';
try {
$statement = $this->db->prepare($query);
$statement->bindValue(':config_name', $values['name'], PDO::PARAM_STR);
$statement->execute();
} catch (PDOException $e) {
return false;
}
$row = $statement->fetch(PDO::FETCH_ASSOC);
$id = $row['config_id'];
// Log
$logs = $this->getLogsOption();
$queryLog = 'INSERT INTO cfg_centreonbroker_log (id_centreonbroker, id_log, id_level) VALUES ';
foreach (array_keys($logs) as $logId) {
$queryLog .= '(:id_centreonbroker, :log_' . $logId . ', :level_' . $logId . '), ';
}
$queryLog = rtrim($queryLog, ', ');
try {
$stmt = $this->db->prepare($queryLog);
$stmt->bindValue(':id_centreonbroker', (int) $id, PDO::PARAM_INT);
foreach ($logs as $logId => $logName) {
$stmt->bindValue(':log_' . $logId, (int) $logId, PDO::PARAM_INT);
$logValue = $values['log_' . $logName] ?? null;
$stmt->bindValue(':level_' . $logId, (int) $logValue, PDO::PARAM_INT);
}
$stmt->execute();
} catch (PDOException $e) {
return false;
}
try {
$this->updateCentreonBrokerInfosByAPI($id, $values);
} catch (Throwable $th) {
error_log((string) $th);
echo "<div class='msg' align='center'>" . _($th->getMessage()) . '</div>';
return false;
}
return true;
}
/**
* Update configuration
*
* @param int $id The configuration id
* @param array $values The post array
*
* @throws PDOException
* @return bool
*/
public function updateConfig(int $id, array $values)
{
// Insert the Centreon Broker configuration
$query = '';
try {
$stmt = $this->db->prepare(
<<<'SQL'
UPDATE cfg_centreonbroker SET
config_name = :config_name,
config_filename = :config_filename,
ns_nagios_server = :ns_nagios_server,
config_activate = :config_activate,
daemon = :daemon,
config_write_timestamp = :config_write_timestamp,
config_write_thread_id = :config_write_thread_id,
stats_activate = :stats_activate,
cache_directory = :cache_directory,
event_queue_max_size = :event_queue_max_size,
event_queues_total_size = :event_queues_total_size,
command_file = :command_file,
log_directory = :log_directory,
log_filename = :log_filename,
log_max_size = :log_max_size,
pool_size = :pool_size,
bbdo_version = :bbdo_version
WHERE config_id = :config_id
SQL
);
$stmt->bindValue(':config_id', $id, PDO::PARAM_INT);
$stmt->bindValue(':config_name', $values['name'], PDO::PARAM_STR);
$stmt->bindValue(':config_filename', $values['filename'], PDO::PARAM_STR);
$stmt->bindValue(':ns_nagios_server', $values['ns_nagios_server'], PDO::PARAM_STR);
$stmt->bindValue(':config_activate', $values['activate']['activate'], PDO::PARAM_STR);
$stmt->bindValue(':daemon', $values['activate_watchdog']['activate_watchdog'], PDO::PARAM_STR);
$stmt->bindValue(':config_write_timestamp', $values['write_timestamp']['write_timestamp'], PDO::PARAM_STR);
$stmt->bindValue(':config_write_thread_id', $values['write_thread_id']['write_thread_id'], PDO::PARAM_STR);
$stmt->bindValue(':stats_activate', $values['stats_activate']['stats_activate'], PDO::PARAM_STR);
$stmt->bindValue(':cache_directory', $values['cache_directory'], PDO::PARAM_STR);
$stmt->bindValue(':log_directory', $values['log_directory'], PDO::PARAM_STR);
$stmt->bindValue(':log_filename', $values['log_filename'], PDO::PARAM_STR);
$stmt->bindValue(':log_max_size', $values['log_max_size'], PDO::PARAM_INT);
$stmt->bindValue(':bbdo_version', $values['bbdo_version'], PDO::PARAM_STR);
$stmt->bindValue(
':event_queue_max_size',
(int) $this->checkEventMaxQueueSizeValue($values['event_queue_max_size']),
PDO::PARAM_INT
);
$stmt->bindValue(
':event_queues_total_size',
! empty($values['event_queues_total_size']) ? (int) $values['event_queues_total_size'] : null,
PDO::PARAM_INT
);
$stmt->bindValue(':command_file', $values['command_file'], PDO::PARAM_STR);
empty($values['pool_size'])
? $stmt->bindValue(':pool_size', null, PDO::PARAM_NULL)
: $stmt->bindValue(':pool_size', (int) $values['pool_size'], PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
return false;
}
// Log
$logs = $this->getLogsOption();
$deleteStmt = $this->db->prepare(
<<<'SQL'
DELETE FROM cfg_centreonbroker_log WHERE id_centreonbroker = :config_id
SQL
);
$deleteStmt->bindValue(':config_id', $id, PDO::PARAM_INT);
$deleteStmt->execute();
$queryLog = 'INSERT INTO cfg_centreonbroker_log (id_centreonbroker, id_log, id_level) VALUES ';
foreach (array_keys($logs) as $logId) {
$queryLog .= '(:id_centreonbroker, :log_' . $logId . ', :level_' . $logId . '), ';
}
$queryLog = rtrim($queryLog, ', ');
try {
$stmt = $this->db->prepare($queryLog);
$stmt->bindValue(':id_centreonbroker', (int) $id, PDO::PARAM_INT);
foreach ($logs as $logId => $logName) {
$stmt->bindValue(':log_' . $logId, (int) $logId, PDO::PARAM_INT);
$stmt->bindValue(':level_' . $logId, (int) $values['log_' . $logName], PDO::PARAM_INT);
}
$stmt->execute();
} catch (PDOException $e) {
return false;
}
try {
$this->updateCentreonBrokerInfosByAPI($id, $values);
} catch (Throwable $th) {
error_log((string) $th);
echo "<div class='msg' align='center'>" . _($th->getMessage()) . '</div>';
return false;
}
return true;
}
/**
* Get the list of forms for a config_id
*
* @param int $config_id The id of config
* @param string $tag The tag name
* @param int $page The page topology
* @param Smarty $tpl The template Smarty
* @throws HTML_QuickForm_Error
* @return array
*/
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonTopology.class.php | centreon/www/class/centreonTopology.class.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
*
*/
/**
* Class
*
* @class CentreonTopology
*/
class CentreonTopology
{
/** @var CentreonDB */
protected $db;
/**
* CentreonTopology constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* @param string $key
* @param $value
* @throws Exception
* @return mixed
*/
public function getTopology($key, $value)
{
$queryTopologyPage = 'SELECT * FROM topology WHERE topology_' . $key . ' = :keyTopo';
$stmt = $this->db->prepare($queryTopologyPage);
$stmt->bindParam(':keyTopo', $value);
$stmt->execute();
return $stmt->fetch();
}
/**
* @param $topologyPage
* @param string $topologyName
* @param string $breadCrumbDelimiter
*
* @throws Exception
* @return string
*/
public function getBreadCrumbFromTopology($topologyPage, $topologyName, $breadCrumbDelimiter = ' > ')
{
$breadCrumb = $topologyName;
$currentTopology = $this->getTopology('page', $topologyPage);
while (! empty($currentTopology['topology_parent'])) {
$parentTopology = $this->getTopology('page', $currentTopology['topology_parent']);
$breadCrumb = $parentTopology['topology_name'] . $breadCrumbDelimiter . $breadCrumb;
$currentTopology = $parentTopology;
}
return $breadCrumb;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonAclGroup.class.php | centreon/www/class/centreonAclGroup.class.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
*
*/
/**
* Class
*
* @class CentreonAclGroup
*/
class CentreonAclGroup
{
/** @var CentreonDB */
protected $db;
/**
* CentreonAclGroup constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':group' . $v . ',';
$queryValues['group' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected timeperiods
$query = 'SELECT acl_group_id, acl_group_name FROM acl_groups '
. 'WHERE acl_group_id IN (' . $listValues . ') '
. 'ORDER BY acl_group_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['acl_group_id'], 'text' => $row['acl_group_name']];
}
return $items;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonServicecategories.class.php | centreon/www/class/centreonServicecategories.class.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
*
*/
/**
* Class
*
* @class CentreonServicecategories
*/
class CentreonServicecategories
{
/** @var CentreonDB */
protected $db;
/**
* CentreonServicecategories constructor
*
* @param CentreonDB $pearDB
*/
public function __construct($pearDB)
{
$this->db = $pearDB;
}
/**
* @param int $field
*
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'service_categories';
$parameters['currentObject']['id'] = 'sc_id';
$parameters['currentObject']['name'] = 'sc_name';
$parameters['currentObject']['comparator'] = 'sc_id';
switch ($field) {
case 'sc_svcTpl':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonServicetemplates';
$parameters['relationObject']['table'] = 'service_categories_relation';
$parameters['relationObject']['field'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'sc_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
global $centreon;
$items = [];
// get list of authorized service categories
if (! $centreon->user->access->admin) {
$scAcl = $centreon->user->access->getServiceCategories();
}
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$multiValues = explode(',', $v);
foreach ($multiValues as $item) {
$queryValues[':sc_' . $item] = (int) $item;
}
}
}
// get list of selected service categories
$query = 'SELECT sc_id, sc_name FROM service_categories '
. 'WHERE sc_id IN ('
. (count($queryValues) ? implode(',', array_keys($queryValues)) : '""')
. ') ORDER BY sc_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue($key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
// hide unauthorized service categories
$hide = false;
if (! $centreon->user->access->admin && count($scAcl) && ! in_array($row['sc_id'], array_keys($scAcl))) {
$hide = true;
}
$items[] = ['id' => $row['sc_id'], 'text' => $row['sc_name'], 'hide' => $hide];
}
return $items;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonTraps.class.php | centreon/www/class/centreonTraps.class.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
*
*/
/**
* Class
*
* @class CentreonTraps
*/
class CentreonTraps
{
/** @var CentreonDB */
protected $db;
/** @var HTML_QuickFormCustom */
protected $form;
/** @var Centreon */
protected $centreon;
/**
* CentreonTraps constructor
*
* @param CentreonDB $db
* @param Centreon $centreon
* @param HTML_QuickFormCustom $form
*
* @throws Exception
*/
public function __construct($db, $centreon = null, $form = null)
{
if (! isset($db)) {
throw new Exception('Db connector object is required');
}
$this->db = $db;
$this->centreon = $centreon;
$this->form = $form;
}
/**
* Sets form if not passed to constructor beforehands
*
* @param $form
*/
public function setForm($form): void
{
$this->form = $form;
}
/**
* Check if the OID has the good Format
*
* @param null|string $oid
* @return bool
*/
public function testOidFormat($oid = null)
{
return (bool) (preg_match('/^(\.([0-2]))|([0-2])((\.0)|(\.([1-9][0-9]*)))*$/', $oid) == true);
}
/**
* Delete Traps
*
* @param array $traps
*
* @throws PDOException
*/
public function delete($traps = []): void
{
$querySelect = 'SELECT traps_name FROM `traps` WHERE `traps_id` = :trapsId LIMIT 1';
$queryDelete = 'DELETE FROM traps WHERE traps_id = :trapsId ';
$statementSelect = $this->db->prepare($querySelect);
$statementDelete = $this->db->prepare($queryDelete);
foreach (array_keys($traps) as $trapsId) {
if (is_int($trapsId)) {
$statementSelect->bindValue(':trapsId', $trapsId, PDO::PARAM_INT);
$statementSelect->execute();
$row = $statementSelect->fetch(PDO::FETCH_ASSOC);
$statementDelete->bindValue(':trapsId', $trapsId, PDO::PARAM_INT);
$statementDelete->execute();
if ($statementDelete->rowCount() > 0) {
$this->centreon->CentreonLogAction->insertLog('traps', $trapsId, $row['traps_name'], 'd');
}
}
}
}
/**
* Indicates if the trap name already exists
*
* @param string $trapName Trap name to find
*
* @throws PDOException
* @return bool
*/
public function trapNameExists(string $trapName)
{
if (! empty($trapName)) {
$statement = $this->db->prepare(
'SELECT COUNT(*) AS total FROM traps WHERE traps_name = :trap_name'
);
$statement->bindValue(':trap_name', $trapName, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
return ((int) $result['total']) > 0;
}
return false;
}
/**
* duplicate traps
*
* @param array $traps
* @param array $nbrDup
*
* @throws PDOException
*/
public function duplicate($traps = [], $nbrDup = []): void
{
$querySelectTrap = 'SELECT * FROM traps WHERE traps_id = :trapsId LIMIT 1';
$queryInsertTrapServiceRelation = '
INSERT INTO traps_service_relation (traps_id, service_id)
(SELECT :maxTrapsId, service_id
FROM traps_service_relation
WHERE traps_id = :trapsId)';
$queryInsertPreexec = '
INSERT INTO traps_preexec (trap_id, tpe_string, tpe_order)
(SELECT :maxTrapsId, tpe_string, tpe_order
FROM traps_preexec
WHERE trap_id = :trapsId)';
$querySelectMatching = 'SELECT * FROM traps_matching_properties WHERE trap_id = :trapsId';
$queryInsertMatching = '
INSERT INTO traps_matching_properties
(`trap_id`,`tmo_order`,`tmo_regexp`,`tmo_string`,`tmo_status`,`severity_id`)
VALUES (:trap_id, :tmo_order, :tmo_regexp, :tmo_string, :tmo_status, :severity_id)';
$stmtSelectTrap = $this->db->prepare($querySelectTrap);
$stmtInsertTrapServiceRelation = $this->db->prepare($queryInsertTrapServiceRelation);
$stmtInsertPreexec = $this->db->prepare($queryInsertPreexec);
$stmtSelectMatching = $this->db->prepare($querySelectMatching);
$stmtInsertMatching = $this->db->prepare($queryInsertMatching);
foreach (array_keys($traps) as $trapsId) {
if (is_int($trapsId)) {
$stmtSelectTrap->bindValue(':trapsId', $trapsId, PDO::PARAM_INT);
$stmtSelectTrap->execute();
$trapConfigurations = $stmtSelectTrap->fetch(PDO::FETCH_ASSOC);
$trapConfigurations['traps_id'] = '';
for ($newIndex = 1; $newIndex <= $nbrDup[$trapsId]; $newIndex++) {
$val = null;
$trapName = null;
$fields = [];
foreach ($trapConfigurations as $cfgName => $cfgValue) {
if ($cfgName == 'traps_name') {
$cfgValue .= '_' . $newIndex;
$trapName = $cfgValue;
$fields['traps_name'] = $trapName;
} elseif ($cfgName != 'traps_id') {
$fields[$cfgName] = $cfgValue;
}
if (is_null($val)) {
$val .= ($cfgValue == null)
? 'NULL'
: "'" . $this->db->escape($cfgValue) . "'";
} else {
$val .= ($cfgValue == null)
? ', NULL'
: ", '" . $this->db->escape($cfgValue) . "'";
}
}
if (! is_null($val)
&& ! empty($trapName)
&& ! $this->trapNameExists($trapName)
) {
$this->db->query("INSERT INTO traps VALUES ({$val})");
$res2 = $this->db->query('SELECT MAX(traps_id) FROM traps');
$maxId = $res2->fetch();
$stmtInsertTrapServiceRelation->bindValue(
':maxTrapsId',
$maxId['MAX(traps_id)'],
PDO::PARAM_INT
);
$stmtInsertTrapServiceRelation->bindValue(':trapsId', $trapsId, PDO::PARAM_INT);
$stmtInsertTrapServiceRelation->execute();
$stmtInsertPreexec->bindValue(':maxTrapsId', $maxId['MAX(traps_id)'], PDO::PARAM_INT);
$stmtInsertPreexec->bindValue(':trapsId', $trapsId, PDO::PARAM_INT);
$stmtInsertPreexec->execute();
$stmtSelectMatching->bindValue(':trapsId', $trapsId, PDO::PARAM_INT);
$stmtSelectMatching->execute();
while ($row = $stmtSelectMatching->fetch()) {
$severity = $row['severity_id'] ?? null;
$stmtInsertMatching->bindValue(':trap_id', $maxId['MAX(traps_id)'], PDO::PARAM_INT);
$stmtInsertMatching->bindValue(':tmo_order', $row['tmo_order'], PDO::PARAM_INT);
$stmtInsertMatching->bindValue(':tmo_regexp', $row['tmo_regexp'], PDO::PARAM_STR);
$stmtInsertMatching->bindValue(':tmo_string', $row['tmo_string'], PDO::PARAM_STR);
$stmtInsertMatching->bindValue(':tmo_status', $row['tmo_status'], PDO::PARAM_INT);
$stmtInsertMatching->bindValue(':severity_id', $severity, PDO::PARAM_INT);
$stmtInsertMatching->execute();
}
$this->centreon->CentreonLogAction->insertLog(
'traps',
$maxId['MAX(traps_id)'],
$trapName,
'a',
$fields
);
}
}
}
}
}
/**
* @param int|null $traps_id
*
* @throws InvalidArgumentException
* @throws PDOException
* @return null|void
*/
public function update($traps_id = null)
{
if (! $traps_id) {
return null;
}
$ret = $this->form->getSubmitValues();
$retValue = [];
$rq = 'UPDATE traps SET ';
$rq .= '`traps_name` = ';
if (isset($ret['traps_name']) && $ret['traps_name'] != null) {
$rq .= ':traps_name, ';
$retValue[':traps_name'] = $ret['traps_name'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_oid` = ';
if (isset($ret['traps_oid']) && $ret['traps_oid'] != null) {
$rq .= ':traps_oid, ';
$retValue[':traps_oid'] = $ret['traps_oid'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_args` = ';
if (isset($ret['traps_args']) && $ret['traps_args'] != null) {
$rq .= ':traps_args, ';
$retValue[':traps_args'] = $ret['traps_args'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_status` = ';
if (isset($ret['traps_status']) && $ret['traps_status'] != null) {
$rq .= ':traps_status, ';
$retValue[':traps_status'] = $ret['traps_status'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`severity_id` = ';
if (isset($ret['severity']) && $ret['severity'] != null) {
$rq .= ':severity, ';
$retValue[':severity'] = $ret['severity'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_submit_result_enable` = ';
if (isset($ret['traps_submit_result_enable']) && $ret['traps_submit_result_enable'] != null) {
$rq .= ':traps_submit_result_enable, ';
$retValue[':traps_submit_result_enable'] = $ret['traps_submit_result_enable'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_reschedule_svc_enable` = ';
if (isset($ret['traps_reschedule_svc_enable']) && $ret['traps_reschedule_svc_enable'] != null) {
$rq .= ':traps_reschedule_svc_enable, ';
$retValue[':traps_reschedule_svc_enable'] = $ret['traps_reschedule_svc_enable'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_execution_command` = ';
if (isset($ret['traps_execution_command']) && $ret['traps_execution_command'] != null) {
$rq .= ':traps_execution_command, ';
$retValue[':traps_execution_command'] = $ret['traps_execution_command'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_execution_command_enable` = ';
if (isset($ret['traps_execution_command_enable']) && $ret['traps_execution_command_enable'] != null) {
$rq .= ':traps_execution_command_enable, ';
$retValue[':traps_execution_command_enable'] = $ret['traps_execution_command_enable'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_advanced_treatment` = ';
if (isset($ret['traps_advanced_treatment']) && $ret['traps_advanced_treatment'] != null) {
$rq .= ':traps_advanced_treatment, ';
$retValue[':traps_advanced_treatment'] = $ret['traps_advanced_treatment'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_comments` = ';
if (isset($ret['traps_comments']) && $ret['traps_comments'] != null) {
$rq .= ':traps_comments, ';
$retValue[':traps_comments'] = $ret['traps_comments'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_routing_mode` = ';
if (isset($ret['traps_routing_mode']) && $ret['traps_routing_mode'] != null) {
$rq .= ':traps_routing_mode, ';
$retValue[':traps_routing_mode'] = $ret['traps_routing_mode'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_routing_value` = ';
if (isset($ret['traps_routing_value']) && $ret['traps_routing_value'] != null) {
$rq .= ':traps_routing_value, ';
$retValue[':traps_routing_value'] = $ret['traps_routing_value'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_routing_filter_services` = ';
if (isset($ret['traps_routing_filter_services']) && $ret['traps_routing_filter_services'] != null) {
$rq .= ':traps_routing_filter_services, ';
$retValue[':traps_routing_filter_services'] = $ret['traps_routing_filter_services'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`manufacturer_id` = ';
if (isset($ret['manufacturer_id']) && $ret['manufacturer_id'] != null) {
$rq .= ':manufacturer_id, ';
$retValue[':manufacturer_id'] = $ret['manufacturer_id'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_log` = ';
if (isset($ret['traps_log']) && $ret['traps_log'] != null) {
$rq .= ':traps_log, ';
$retValue[':traps_log'] = $ret['traps_log'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_exec_interval` = ';
if (isset($ret['traps_exec_interval']) && $ret['traps_exec_interval'] != null) {
$rq .= ':traps_exec_interval, ';
$retValue[':traps_exec_interval'] = $ret['traps_exec_interval'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_exec_interval_type` = ';
if (isset($ret['traps_exec_interval_type']['traps_exec_interval_type'])
&& $ret['traps_exec_interval_type']['traps_exec_interval_type'] != null) {
$rq .= ':traps_exec_interval_type, ';
$retValue[':traps_exec_interval_type'] = $ret['traps_exec_interval_type']['traps_exec_interval_type'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_exec_method` = ';
if (isset($ret['traps_exec_method']['traps_exec_method'])
&& $ret['traps_exec_method']['traps_exec_method'] != null) {
$rq .= ':traps_exec_method, ';
$retValue[':traps_exec_method'] = $ret['traps_exec_method']['traps_exec_method'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_downtime` = ';
if (isset($ret['traps_downtime']['traps_downtime'])
&& $ret['traps_downtime']['traps_downtime'] != null) {
$rq .= ':traps_downtime, ';
$retValue[':traps_downtime'] = $ret['traps_downtime']['traps_downtime'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_output_transform` = ';
if (isset($ret['traps_output_transform']) && $ret['traps_output_transform'] != null) {
$rq .= ':traps_output_transform, ';
$retValue[':traps_output_transform'] = $ret['traps_output_transform'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_advanced_treatment_default` = ';
if (isset($ret['traps_advanced_treatment_default']) && $ret['traps_advanced_treatment_default'] != null) {
$rq .= ':traps_advanced_treatment_default, ';
$retValue[':traps_advanced_treatment_default'] = $ret['traps_advanced_treatment_default'];
} else {
$rq .= "'0', ";
}
$rq .= '`traps_timeout` = ';
if (isset($ret['traps_timeout']) && $ret['traps_timeout'] != null) {
$rq .= ':traps_timeout, ';
$retValue[':traps_timeout'] = $ret['traps_timeout'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_customcode` = ';
if (isset($ret['traps_customcode']) && $ret['traps_customcode'] != null) {
$rq .= ':traps_customcode, ';
$retValue[':traps_customcode'] = $ret['traps_customcode'];
} else {
$rq .= 'NULL, ';
}
$rq .= '`traps_mode` = ';
if (isset($ret['traps_mode']['traps_mode']) && $ret['traps_mode']['traps_mode'] != null) {
$rq .= ':traps_mode ';
$retValue[':traps_mode'] = $ret['traps_mode']['traps_mode'];
} else {
$rq .= 'NULL ';
}
$rq .= 'WHERE `traps_id` = :traps_id ';
$retValue[':traps_id'] = (int) $traps_id;
$stmt = $this->db->prepare($rq);
foreach ($retValue as $key => $value) {
$stmt->bindValue($key, $value);
}
$stmt->execute();
$this->setMatchingOptions($traps_id);
$this->setServiceRelations($traps_id);
$this->setServiceTemplateRelations($traps_id);
$this->setPreexec($traps_id);
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$this->centreon->CentreonLogAction->insertLog('traps', $traps_id, $fields['traps_name'], 'c', $fields);
}
/**
* Insert Traps
*
* @param array $ret
*
* @throws InvalidArgumentException
* @throws PDOException
* @return mixed
*/
public function insert($ret = [])
{
if (! count($ret)) {
$ret = $this->form->getSubmitValues();
}
$sqlValue = '';
$retValue = [];
$rq = 'INSERT INTO traps (';
$rq .= '`traps_name`, ';
if (isset($ret['traps_name']) && $ret['traps_name'] != null) {
$sqlValue .= ':traps_name, ';
$retValue[':traps_name'] = $ret['traps_name'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_oid`, ';
if (isset($ret['traps_oid']) && $ret['traps_oid'] != null) {
$sqlValue .= ':traps_oid, ';
$retValue[':traps_oid'] = $ret['traps_oid'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_args`, ';
if (isset($ret['traps_args']) && $ret['traps_args'] != null) {
$sqlValue .= ':traps_args, ';
$retValue[':traps_args'] = $ret['traps_args'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_status`, ';
if (isset($ret['traps_status']) && $ret['traps_status'] != null) {
$sqlValue .= ':traps_status, ';
$retValue[':traps_status'] = $ret['traps_status'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`severity_id`, ';
if (isset($ret['severity']) && $ret['severity'] != null) {
$sqlValue .= ':severity, ';
$retValue[':severity'] = $ret['severity'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_submit_result_enable`, ';
if (isset($ret['traps_submit_result_enable']) && $ret['traps_submit_result_enable'] != null) {
$sqlValue .= ':traps_submit_result_enable, ';
$retValue[':traps_submit_result_enable'] = $ret['traps_submit_result_enable'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_reschedule_svc_enable`, ';
if (isset($ret['traps_reschedule_svc_enable']) && $ret['traps_reschedule_svc_enable'] != null) {
$sqlValue .= ':traps_reschedule_svc_enable, ';
$retValue[':traps_reschedule_svc_enable'] = $ret['traps_reschedule_svc_enable'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_execution_command`, ';
if (isset($ret['traps_execution_command']) && $ret['traps_execution_command'] != null) {
$sqlValue .= ':traps_execution_command, ';
$retValue[':traps_execution_command'] = $ret['traps_execution_command'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_execution_command_enable`, ';
if (isset($ret['traps_execution_command_enable']) && $ret['traps_execution_command_enable'] != null) {
$sqlValue .= ':traps_execution_command_enable, ';
$retValue[':traps_execution_command_enable'] = $ret['traps_execution_command_enable'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_advanced_treatment`, ';
if (isset($ret['traps_advanced_treatment']) && $ret['traps_advanced_treatment'] != null) {
$sqlValue .= ':traps_advanced_treatment, ';
$retValue[':traps_advanced_treatment'] = $ret['traps_advanced_treatment'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_comments`, ';
if (isset($ret['traps_comments']) && $ret['traps_comments'] != null) {
$sqlValue .= ':traps_comments, ';
$retValue[':traps_comments'] = $ret['traps_comments'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_routing_mode`, ';
if (isset($ret['traps_routing_mode']) && $ret['traps_routing_mode'] != null) {
$sqlValue .= ':traps_routing_mode, ';
$retValue[':traps_routing_mode'] = $ret['traps_routing_mode'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_routing_value`, ';
if (isset($ret['traps_routing_value']) && $ret['traps_routing_value'] != null) {
$sqlValue .= ':traps_routing_value, ';
$retValue[':traps_routing_value'] = $ret['traps_routing_value'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_routing_filter_services`, ';
if (isset($ret['traps_routing_filter_services']) && $ret['traps_routing_filter_services'] != null) {
$sqlValue .= ':traps_routing_filter_services, ';
$retValue[':traps_routing_filter_services'] = $ret['traps_routing_filter_services'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`manufacturer_id`, ';
if (isset($ret['manufacturer_id']) && $ret['manufacturer_id'] != null) {
$sqlValue .= ':manufacturer_id, ';
$retValue[':manufacturer_id'] = $ret['manufacturer_id'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_log`, ';
if (isset($ret['traps_log']) && $ret['traps_log'] != null) {
$sqlValue .= ':traps_log, ';
$retValue[':traps_log'] = $ret['traps_log'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_exec_interval`, ';
if (isset($ret['traps_exec_interval']) && $ret['traps_exec_interval'] != null) {
$sqlValue .= ':traps_exec_interval, ';
$retValue[':traps_exec_interval'] = $ret['traps_exec_interval'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_exec_interval_type`, ';
if (isset($ret['traps_exec_interval_type']['traps_exec_interval_type'])
&& $ret['traps_exec_interval_type']['traps_exec_interval_type'] != null) {
$sqlValue .= ':traps_exec_interval_type, ';
$retValue[':traps_exec_interval_type'] = $ret['traps_exec_interval_type']['traps_exec_interval_type'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_exec_method`, ';
if (isset($ret['traps_exec_method']['traps_exec_method'])
&& $ret['traps_exec_method']['traps_exec_method'] != null) {
$sqlValue .= ':traps_exec_method, ';
$retValue[':traps_exec_method'] = $ret['traps_exec_method']['traps_exec_method'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_mode`, ';
if (isset($ret['traps_mode']['traps_mode'])
&& $ret['traps_mode']['traps_mode'] != null) {
$sqlValue .= ':traps_mode, ';
$retValue[':traps_mode'] = $ret['traps_mode']['traps_mode'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_downtime`, ';
if (isset($ret['traps_downtime']['traps_downtime'])
&& $ret['traps_downtime']['traps_downtime'] != null) {
$sqlValue .= ':traps_downtime, ';
$retValue[':traps_downtime'] = $ret['traps_downtime']['traps_downtime'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_output_transform`, ';
if (isset($ret['traps_output_transform']) && $ret['traps_output_transform'] != null) {
$sqlValue .= ':traps_output_transform, ';
$retValue[':traps_output_transform'] = $ret['traps_output_transform'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_advanced_treatment_default`, ';
if (isset($ret['traps_advanced_treatment_default']) && $ret['traps_advanced_treatment_default'] != null) {
$sqlValue .= ':traps_advanced_treatment_default, ';
$retValue[':traps_advanced_treatment_default'] = $ret['traps_advanced_treatment_default'];
} else {
$sqlValue .= "'0', ";
}
$rq .= '`traps_timeout`, ';
if (isset($ret['traps_timeout']) && $ret['traps_timeout'] != null) {
$sqlValue .= ':traps_timeout, ';
$retValue[':traps_timeout'] = $ret['traps_timeout'];
} else {
$sqlValue .= 'NULL, ';
}
$rq .= '`traps_customcode` ';
if (isset($ret['traps_customcode']) && $ret['traps_customcode'] != null) {
$sqlValue .= ':traps_customcode ';
$retValue[':traps_customcode'] = $ret['traps_customcode'];
} else {
$sqlValue .= 'NULL ';
}
$rq .= ') VALUES (' . $sqlValue . ')';
$stmt = $this->db->prepare($rq);
foreach ($retValue as $key => $value) {
$stmt->bindValue($key, $value);
}
$stmt->execute();
$res = $this->db->query('SELECT MAX(traps_id) FROM traps');
$traps_id = $res->fetch();
$this->setMatchingOptions($traps_id['MAX(traps_id)']);
$this->setServiceRelations($traps_id['MAX(traps_id)']);
$this->setServiceTemplateRelations($traps_id['MAX(traps_id)']);
$this->setPreexec($traps_id['MAX(traps_id)']);
// Prepare value for changelog
$fields = CentreonLogAction::prepareChanges($ret);
$this->centreon->CentreonLogAction->insertLog(
'traps',
$traps_id['MAX(traps_id)'],
$fields['traps_name'],
'a',
$fields
);
return $traps_id['MAX(traps_id)'];
}
/**
* Get pre exec commands from trap_id
*
* @param int $trapId
*
* @throws PDOException
* @return array
*/
public function getPreexecFromTrapId(int $trapId)
{
if ($trapId > 0) {
$query = '
SELECT tpe_string
FROM traps_preexec
WHERE trap_id = :trapId
ORDER BY tpe_order';
$statement = $this->db->prepare($query);
$statement->bindValue(':trapId', $trapId, PDO::PARAM_INT);
$statement->execute();
$arr = [];
$i = 0;
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$arr[$i] = ['preexec_#index#' => $row['tpe_string']];
$i++;
}
return $arr;
}
return [];
}
/**
* Get matching rules from trap_id
*
* @param int $trapId
*
* @throws PDOException
* @return array
*/
public function getMatchingRulesFromTrapId(int $trapId)
{
if ($trapId > 0) {
$query = '
SELECT tmo_string, tmo_regexp, tmo_status, severity_id
FROM traps_matching_properties
WHERE trap_id = :trapId
ORDER BY tmo_order';
$statement = $this->db->prepare($query);
$statement->bindValue(':trapId', $trapId, PDO::PARAM_INT);
$statement->execute();
$arr = [];
$i = 0;
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$arr[$i] = ['rule_#index#' => $row['tmo_string'], 'regexp_#index#' => $row['tmo_regexp'], 'rulestatus_#index#' => $row['tmo_status'], 'ruleseverity_#index#' => $row['severity_id']];
$i++;
}
return $arr;
}
return [];
}
/**
* @param int $field
*
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'traps';
$parameters['currentObject']['id'] = 'traps_id';
$parameters['currentObject']['name'] = 'traps_name';
$parameters['currentObject']['comparator'] = 'traps_id';
switch ($field) {
case 'manufacturer_id':
$parameters['type'] = 'simple';
$parameters['externalObject']['table'] = 'traps_vendor';
$parameters['externalObject']['id'] = 'id';
$parameters['externalObject']['name'] = 'name';
$parameters['externalObject']['comparator'] = 'id';
break;
case 'groups':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'traps';
$parameters['externalObject']['id'] = 'traps_id';
$parameters['externalObject']['name'] = 'traps_name';
$parameters['externalObject']['comparator'] = 'traps_id';
$parameters['relationObject']['table'] = 'traps_group_relation';
$parameters['relationObject']['field'] = 'traps_id';
$parameters['relationObject']['comparator'] = 'traps_group_id';
break;
case 'services':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonService';
$parameters['relationObject']['table'] = 'traps_service_relation';
$parameters['relationObject']['field'] = 'service_id';
$parameters['relationObject']['comparator'] = 'traps_id';
break;
case 'service_templates':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonServicetemplates';
$parameters['relationObject']['table'] = 'traps_service_relation';
$parameters['relationObject']['field'] = 'service_id';
$parameters['relationObject']['comparator'] = 'traps_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':traps' . $v . ',';
$queryValues['traps' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected traps
$query = 'SELECT traps_id, traps_name FROM traps '
. 'WHERE traps_id IN (' . $listValues . ') ORDER BY traps_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['traps_id'], 'text' => $row['traps_name']];
}
return $items;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonAuth.LDAP.class.php | centreon/www/class/centreonAuth.LDAP.class.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 LDAP\Connection;
require_once __DIR__ . '/centreonAuth.class.php';
require_once __DIR__ . '/centreonLDAP.class.php';
/**
* Class
*
* @class CentreonAuthLDAP
* @description Class for Ldap authentication
*/
class CentreonAuthLDAP
{
/** @var Connection|resource */
public $ds;
/** @var CentreonDB */
protected $pearDB;
/** @var CentreonLDAP */
protected $ldap;
/** @var CentreonUserLog */
protected $CentreonLog;
/** @var mixed[] */
protected $contactInfos;
/** @var string */
protected $typePassword;
/** @var int */
protected $debug;
/** @var bool */
protected $firstCheck = true;
/** @var int */
protected $arId;
/**
* CentreonAuthLDAP constructor
*
* @param CentreonDB $pearDB Connection to centreon database
* @param CentreonUserLog $CentreonLog Log event
* @param string $login The username
* @param string $password The user password
* @param array $contactInfos
* @param int $arId | Auth Ressource ID
*
* @throws PDOException
*/
public function __construct($pearDB, $CentreonLog, $login, $password, $contactInfos, $arId)
{
$this->arId = $arId;
$this->pearDB = $pearDB;
$this->CentreonLog = $CentreonLog;
$this->ldap = new CentreonLDAP($pearDB, $CentreonLog, $arId);
$this->ldap->connect();
$this->ds = $this->ldap->getDs();
// Set contact Information
$this->contactInfos = $contactInfos;
if (! empty($this->contactInfos['contact_ldap_dn'])) {
$this->contactInfos['contact_ldap_dn'] = html_entity_decode($this->contactInfos['contact_ldap_dn']);
}
// Keep password
$this->typePassword = $password;
$this->debug = $this->getLogFlag();
}
/**
* Check the user pass
*/
public function checkPassword()
{
if (empty($this->contactInfos['contact_ldap_dn'])) {
$this->contactInfos['contact_ldap_dn'] = $this->ldap->findUserDn($this->contactInfos['contact_alias']);
} elseif (
($userDn = $this->ldap->findUserDn($this->contactInfos['contact_alias']))
&& mb_strtolower($userDn, 'UTF-8') !== mb_strtolower($this->contactInfos['contact_ldap_dn'], 'UTF-8') // Ignore case for LDAP and database contact info comparison
) { // validate if user exists in this resource
if (! $userDn) {
// User resource error
return CentreonAuth::PASSWORD_INVALID;
}
// User alias matches the contact alias but the user DN is different
// We have to update the user DN
$updateUserDnOK = $this->updateUserDn();
if ($updateUserDnOK === false) {
// LDAP fallback
return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED;
}
}
if (empty(trim($this->contactInfos['contact_ldap_dn']))) {
return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED;
}
if ($this->debug) {
$this->CentreonLog->insertLog(
3,
'LDAP AUTH : ' . $this->contactInfos['contact_ldap_dn'] . ' :: Authentication in progress'
);
}
@ldap_bind($this->ds, $this->contactInfos['contact_ldap_dn'], $this->typePassword);
if (empty($this->ds)) {
if ($this->debug) {
$this->CentreonLog->insertLog(3, 'DS empty');
}
return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED;
}
/*
* In some case, we fallback to local Auth
* 0 : Bind successful => Default case
* 2 : Protocol error
* -1 : Can't contact LDAP server (php4) => Fallback
* 51 : Server is busy => Fallback
* 52 : Server is unavailable => Fallback
* 81 : Can't contact LDAP server (php5) => Fallback
*/
switch (ldap_errno($this->ds)) {
case 0:
if ($this->debug) {
$this->CentreonLog->insertLog(3, 'LDAP AUTH : Success');
}
if ($this->updateUserDn() == false) {
return CentreonAuth::PASSWORD_INVALID;
}
return CentreonAuth::PASSWORD_VALID;
case -1:
case 2: // protocol error
case 51: // busy
case 52: // unavailable
case 81: // server down
if ($this->debug) {
$this->CentreonLog->insertLog(3, 'LDAP AUTH : ' . ldap_error($this->ds));
}
return CentreonAuth::PASSWORD_CANNOT_BE_VERIFIED;
default:
if ($this->debug) {
$this->CentreonLog->insertLog(3, 'LDAP AUTH : ' . ldap_error($this->ds));
}
return CentreonAuth::PASSWORD_INVALID;
}
}
/**
* Search and update the user dn at login
*
* @throws exception
* @return bool If the DN is modified
*/
public function updateUserDn(): bool
{
$contactAlias = html_entity_decode($this->contactInfos['contact_alias'], ENT_QUOTES, 'UTF-8');
if ($this->ldap->rebind()) {
$userDn = $this->ldap->findUserDn($contactAlias);
if ($userDn === false) {
$this->CentreonLog->insertLog(3, 'LDAP AUTH - Error : No DN for user ' . $contactAlias);
return false;
}
// Get ldap user information
$userInfos = $this->ldap->getEntry($userDn);
$userDisplay = $userInfos[$this->ldap->getAttrName('user', 'name')];
// Get the first if there are multiple entries
if (is_array($userDisplay)) {
$userDisplay = $userDisplay[0];
}
// Replace space by underscore
$userDisplay = str_replace([' ', ','], '_', $userDisplay);
// Delete parenthesis
$userDisplay = str_replace(['(', ')'], '', $userDisplay);
// getting user's email
$userEmail = $this->contactInfos['contact_email'];
$ldapEmailValue = $userInfos[$this->ldap->getAttrName('user', 'email')];
if (isset($ldapEmailValue)) {
$userEmail = (trim(is_array($ldapEmailValue) && $ldapEmailValue !== [] ? current($ldapEmailValue) : $ldapEmailValue));
}
if ($userEmail === '') {
// empty email is not an error, we replace it with a dash
$userEmail = '-';
}
// getting user's pager
$userPager = $this->contactInfos['contact_pager'];
$ldapUserPager = $userInfos[$this->ldap->getAttrName('user', 'pager')];
if (isset($ldapUserPager)) {
$userPager = (trim(is_array($ldapUserPager) && $ldapUserPager !== [] ? current($ldapUserPager) : $ldapUserPager));
}
/**
* Searching if the user already exist in the DB and updating OR adding him
*/
if (isset($this->contactInfos['contact_id'])) {
try {
// checking if the LDAP synchronization on login is enabled or needed
if (! $this->ldap->isSyncNeededAtLogin($this->arId, $this->contactInfos['contact_id'])) {
// skipping the update
return true;
}
$this->CentreonLog->insertLog(
3,
'LDAP AUTH : Updating user DN of ' . $userDisplay
);
$stmt = $this->pearDB->prepare(
<<<'SQL'
UPDATE contact SET
contact_ldap_dn = :userDn,
contact_name = :userDisplay,
contact_email = :userEmail,
contact_pager = :userPager,
reach_api_rt = :reachApiRt,
ar_id = :arId
WHERE contact_id = :contactId
SQL
);
$stmt->bindValue(':userDn', $userDn, PDO::PARAM_STR);
$stmt->bindValue(':userDisplay', $userDisplay, PDO::PARAM_STR);
$stmt->bindValue(':userEmail', $userEmail, PDO::PARAM_STR);
$stmt->bindValue(':userPager', $userPager, PDO::PARAM_STR);
$stmt->bindValue(
':reachApiRt',
$this->contactInfos['contact_oreon'] === '1' ? 1 : 0,
PDO::PARAM_INT
);
$stmt->bindValue(':arId', $this->arId, PDO::PARAM_INT);
$stmt->bindValue(':contactId', $this->contactInfos['contact_id'], PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
$this->CentreonLog->insertLog(
3,
'LDAP AUTH - Error : when trying to update user : ' . $userDisplay
);
return false;
}
$this->contactInfos['contact_ldap_dn'] = $userDn;
// Updating user's contactgroup relations from LDAP
try {
include_once realpath(__DIR__ . '/centreonContactgroup.class.php');
$cgs = new CentreonContactgroup($this->pearDB);
$cgs->syncWithLdap();
} catch (Exception $e) {
$this->CentreonLog->insertLog(
3,
'LDAP AUTH - Error : when updating ' . $userDisplay . '\'s ldap contactgroups'
);
}
$this->ldap->setUserCurrentSyncTime($this->contactInfos);
$this->CentreonLog->insertLog(
3,
'LDAP AUTH : User DN updated for ' . $userDisplay
);
return true;
}
/**
* The current user wasn't found. Adding him to the DB
* First, searching if a contact template has been specified in the LDAP parameters
*/
$res = $this->pearDB->prepare(
"SELECT ari_value FROM `auth_ressource_info` a, `contact` c
WHERE a.`ari_name` = 'ldap_contact_tmpl'
AND a.ar_id = :arId
AND a.ari_value = c.contact_id"
);
try {
$res->bindValue(':arId', $this->arId, PDO::PARAM_INT);
$res->execute();
$row = $res->fetch();
if (empty($row['ari_value'])) {
$this->CentreonLog->insertLog(3, 'LDAP AUTH - Error : No contact template defined.');
return false;
}
$tmplId = $row['ari_value'];
} catch (PDOException $e) {
$this->CentreonLog->insertLog(
3,
'LDAP AUTH - Error : when trying to get LDAP data for : ' . $userDisplay
);
return false;
}
// Inserting the new user in the database
$stmt = $this->pearDB->prepare(
<<<'SQL'
INSERT INTO contact
(contact_template_id, contact_alias, contact_name, contact_auth_type, contact_ldap_dn, ar_id,
contact_email, contact_pager, contact_oreon, reach_api_rt, contact_activate, contact_register,
contact_enable_notifications)
VALUES
(:templateId, :contactAlias, :userDisplay, 'ldap', :userDn, :arId, :userEmail, :userPager, '1',
1, '1', '1', '2')
SQL
);
try {
$stmt->bindValue(':templateId', $tmplId, PDO::PARAM_INT);
$stmt->bindValue(':contactAlias', $contactAlias, PDO::PARAM_STR);
$stmt->bindValue(':userDisplay', $userDisplay, PDO::PARAM_STR);
$stmt->bindValue(':userDn', $userDn, PDO::PARAM_STR);
$stmt->bindValue(':arId', $this->arId, PDO::PARAM_INT);
$stmt->bindValue(':userEmail', $userEmail, PDO::PARAM_STR);
$stmt->bindValue(':userPager', $userPager, PDO::PARAM_STR);
$stmt->execute();
// Retrieving the created contact_id
$res = $this->pearDB->prepare(
'SELECT contact_id FROM contact
WHERE contact_ldap_dn = :userDn'
);
$res->bindValue(':userDn', $userDn, PDO::PARAM_STR);
$res->execute();
$row = $res->fetch();
$this->contactInfos['contact_id'] = $row['contact_id'];
/**
* Searching the user's affiliated contactgroups in the LDAP
*/
$listGroup = $this->ldap->listGroupsForUser($userDn);
$listGroupStr = '';
foreach ($listGroup as $gName) {
if ($listGroupStr !== '') {
$listGroupStr .= ',';
}
$listGroupStr .= "'" . $gName . "'";
}
if ($listGroupStr === '') {
$listGroupStr = "''";
}
$res2 = $this->pearDB->query(
'SELECT cg_id FROM contactgroup
WHERE cg_name IN (' . $listGroupStr . ')'
);
// Inserting the relation between the LDAP's contactgroups and the user
$stmt = $this->pearDB->prepare(
'INSERT INTO contactgroup_contact_relation
(contactgroup_cg_id, contact_contact_id)
VALUES (:ldapCg, :contactId)'
);
while ($row2 = $res2->fetch()) {
$stmt->bindValue(':ldapCg', $row2['cg_id'], PDO::PARAM_INT);
$stmt->bindValue(':contactId', $this->contactInfos['contact_id'], PDO::PARAM_INT);
$stmt->execute();
}
$this->ldap->setUserCurrentSyncTime($this->contactInfos);
$this->CentreonLog->insertLog(3, 'LDAP AUTH - New user DN added : ' . $contactAlias);
// Inserting the relation between the LDAP's default contactgroup and the user
// @returns true if everything goes well
return $this->ldap->addUserToLdapDefaultCg(
$this->arId,
$this->contactInfos['contact_id']
);
} catch (PDOException $e) {
$this->CentreonLog->insertLog(
3,
'LDAP AUTH - Error : processing new user ' . $userDisplay . ' from ldap id : ' . $this->arId
);
}
}
return false;
}
/**
* Is loging enable ?
*
* @throws PDOException
* @return int 1 enable 0 disable
*/
private function getLogFlag()
{
$res = $this->pearDB->query("SELECT value FROM options WHERE `key` = 'debug_ldap_import'");
$data = $res->fetch();
return $data['value'] ?? 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonMeta.class.php | centreon/www/class/centreonMeta.class.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
*
*/
/**
* Class
*
* @class CentreonMeta
*/
class CentreonMeta
{
/** @var CentreonDB */
protected $db;
/**
* CentreonMeta constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Return host id
*
* @throws PDOException
* @return int
*/
public function getRealHostId()
{
static $hostId = null;
if (is_null($hostId)) {
$queryHost = 'SELECT host_id '
. 'FROM host '
. 'WHERE host_name = "_Module_Meta" '
. 'AND host_register = "2" '
. 'LIMIT 1 ';
$res = $this->db->query($queryHost);
if ($res->rowCount()) {
$row = $res->fetchRow();
$hostId = $row['host_id'];
} else {
$query = 'INSERT INTO host (host_name, host_register) '
. 'VALUES ("_Module_Meta", "2") ';
$this->db->query($query);
$res = $this->db->query($queryHost);
if ($res->rowCount()) {
$row = $res->fetchRow();
$hostId = $row['host_id'];
} else {
$hostId = 0;
}
}
}
return $hostId;
}
/**
* Return service id
*
* @param int $metaId
*
* @throws PDOException
* @return int
*/
public function getRealServiceId($metaId)
{
static $services = null;
if (isset($services[$metaId])) {
return $services[$metaId];
}
$sql = 'SELECT s.service_id '
. 'FROM service s '
. 'WHERE s.service_description = "meta_' . $metaId . '" ';
$res = $this->db->query($sql);
if ($res->rowCount()) {
while ($row = $res->fetchRow()) {
$services[$metaId] = $row['service_id'];
}
}
return $services[$metaId] ?? 0;
}
/**
* Return metaservice id
*
* @param string $serviceDisplayName
*
* @throws PDOException
* @return int
*/
public function getMetaIdFromServiceDisplayName($serviceDisplayName)
{
$metaId = null;
$query = 'SELECT service_description '
. 'FROM service '
. 'WHERE display_name = "' . $serviceDisplayName . '" ';
$res = $this->db->query($query);
if ($res->rowCount()) {
$row = $res->fetchRow();
if (preg_match('/meta_(\d+)/', $row['service_description'], $matches)) {
$metaId = $matches[1];
}
}
return $metaId;
}
/**
* @param int $field
*
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'meta_service';
$parameters['currentObject']['id'] = 'meta_id';
$parameters['currentObject']['name'] = 'meta_name';
$parameters['currentObject']['comparator'] = 'meta_id';
switch ($field) {
case 'check_period':
case 'notification_period':
$parameters['type'] = 'simple';
$parameters['externalObject']['table'] = 'timeperiod';
$parameters['externalObject']['id'] = 'tp_id';
$parameters['externalObject']['name'] = 'tp_name';
$parameters['externalObject']['comparator'] = 'tp_id';
break;
case 'ms_cs':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'contact';
$parameters['externalObject']['id'] = 'contact_id';
$parameters['externalObject']['name'] = 'contact_name';
$parameters['externalObject']['comparator'] = 'contact_id';
$parameters['relationObject']['table'] = 'meta_contact';
$parameters['relationObject']['field'] = 'contact_id';
$parameters['relationObject']['comparator'] = 'meta_id';
break;
case 'ms_cgs':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'contactgroup';
$parameters['externalObject']['id'] = 'cg_id';
$parameters['externalObject']['name'] = 'cg_name';
$parameters['externalObject']['comparator'] = 'cg_id';
$parameters['relationObject']['table'] = 'meta_contactgroup_relation';
$parameters['relationObject']['field'] = 'cg_cg_id';
$parameters['relationObject']['comparator'] = 'meta_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':meta' . $v . ',';
$queryValues['meta' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected meta
$query = 'SELECT meta_id, meta_name FROM meta_service '
. 'WHERE meta_id IN (' . $listValues . ') ORDER BY meta_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['meta_id'], 'text' => $row['meta_name']];
}
return $items;
}
/**
* Get the list of all meta-service
*
* @return array
*/
public function getList()
{
$queryList = 'SELECT `meta_id`, `meta_name`
FROM `meta_service`
ORDER BY `meta_name`';
try {
$res = $this->db->query($queryList);
} catch (PDOException $e) {
return [];
}
$listMeta = [];
while ($row = $res->fetchRow()) {
$listMeta[$row['meta_id']] = $row['meta_name'];
}
return $listMeta;
}
/**
* Returns service details
*
* @param int $id
* @param array $parameters
*
* @throws PDOException
* @return array
*/
public function getParameters($id, $parameters = [])
{
$sElement = '*';
$values = [];
if (empty($id) || empty($parameters)) {
return [];
}
if (count($parameters) > 0) {
$sElement = implode(',', $parameters);
}
$query = 'SELECT ' . $sElement . ' '
. 'FROM meta_service '
. 'WHERE meta_id = ' . $this->db->escape($id) . ' ';
$res = $this->db->query($query);
if ($res->rowCount()) {
$values = $res->fetchRow();
}
return $values;
}
/**
* Returns service id
*
* @param int $metaId
* @param string $metaName
*
* @throws PDOException
* @return int
*/
public function insertVirtualService($metaId, $metaName)
{
$hostId = $this->getRealHostId();
$serviceId = null;
$composedName = 'meta_' . $metaId;
$queryService = 'SELECT service_id, display_name FROM service '
. 'WHERE service_register = "2" AND service_description = "' . $composedName . '" ';
$res = $this->db->query($queryService);
if ($res->rowCount()) {
$row = $res->fetchRow();
$serviceId = $row['service_id'];
if ($row['display_name'] !== $metaName) {
$query = 'UPDATE service SET display_name = :display_name WHERE service_id = :service_id';
$statement = $this->db->prepare($query);
$statement->bindValue(':display_name', $metaName, PDO::PARAM_STR);
$statement->bindValue(':service_id', (int) $serviceId, PDO::PARAM_INT);
$statement->execute();
}
} else {
$query = 'INSERT INTO service (service_description, display_name, service_register) '
. 'VALUES '
. '("' . $composedName . '", "' . $metaName . '", "2")';
$this->db->query($query);
$query = 'INSERT INTO host_service_relation(host_host_id, service_service_id) '
. 'VALUES (:host_id,'
. '(SELECT service_id
FROM service
WHERE service_description = :service_description AND service_register = "2" LIMIT 1)'
. ')';
$statement = $this->db->prepare($query);
$statement->bindValue(':host_id', (int) $hostId, PDO::PARAM_INT);
$statement->bindValue(':service_description', $composedName, PDO::PARAM_STR);
$statement->execute();
$res = $this->db->query($queryService);
if ($res->rowCount()) {
$row = $res->fetchRow();
$serviceId = $row['service_id'];
}
}
return $serviceId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWizard.php | centreon/www/class/centreonWizard.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
*
*/
/**
* Class
*
* @class Centreon_Wizard
*/
class Centreon_Wizard
{
/** @var string */
private $_uuid = null;
/** @var string */
private $_name = null;
/** @var array */
private $_values = [];
/** @var int */
private $_lastUpdate = 0;
/**
* Centreon_Wizard constructor
*
* @param string $name The wizard name
* @param string $uuid The wizard unique id
*/
public function __construct($name, $uuid)
{
$this->_uuid = $uuid;
$this->_name = $name;
$this->_lastUpdate = time();
}
/**
* Magic method __sleep
*
* @return string[]
*/
public function __sleep()
{
$this->_lastUpdate = time();
return ['_uuid', '_lastUpdate', '_name', '_values'];
}
/**
* Magic method __wakeup
*
* @return void
*/
public function __wakeup()
{
$this->_lastUpdate = time();
}
/**
* Get values for a step
*
* @param int $step The step position
*
* @return array
*/
public function getValues($step)
{
if (isset($this->_values[$step]) === false) {
return [];
}
return $this->_values[$step];
}
/**
* Get a value
*
* @param int $step The step position
* @param string $name The variable name
* @param string $default The default value
*
* @return string
*/
public function getValue($step, $name, $default = '')
{
if (isset($this->_values[$step]) === false || isset($this->_values[$step][$name]) === false) {
return $default;
}
return $this->_values[$step][$name];
}
/**
* Add values for a step
*
* @param int $step The step position
* @param array $post The post with values
*
* @return void
*/
public function addValues($step, $post): void
{
// Reinit
$this->_values[$step] = [];
foreach ($post as $key => $value) {
if (strncmp($key, 'step' . $step . '_', 6) === 0) {
$this->_values[$step][str_replace('step' . $step . '_', '', $key)] = $value;
}
}
$this->_lastUpdate = time();
}
/**
* Test if the uuid of wizard
*
* @param string $uuid The unique id
*
* @return bool
*/
public function testUuid($uuid)
{
return (bool) ($uuid == $this->_uuid);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonLocale.class.php | centreon/www/class/centreonLocale.class.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
*
*/
/**
* Class
*
* @class CentreonLocale
*/
class CentreonLocale
{
/** @var CentreonDB */
protected $db;
/**
* CentreonLocale constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* GetLocaleList
*
* @throws PDOException
* @return array
*/
public function getLocaleList()
{
$res = $this->db->query(
'SELECT locale_id, locale_short_name, locale_long_name, locale_img '
. "FROM locale ORDER BY locale_short_name <> 'en', locale_short_name"
);
$list = [];
while ($row = $res->fetchRow()) {
$list[$row['locale_id']] = ['locale_short_name' => _($row['locale_short_name']), 'locale_long_name' => _($row['locale_long_name']), 'locale_img' => _($row['locale_img'])];
}
return $list;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonDependency.class.php | centreon/www/class/centreonDependency.class.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
*
*/
/**
* Class
*
* @class CentreonDependency
*/
class CentreonDependency
{
/** @var CentreonDB|null */
protected $db = null;
/**
* Constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Get the service service dependency
*
* @param bool $withSg If use servicegroup relation
* @return array
*/
public function getServiceService($withSg = false)
{
$query = 'SELECT dsp.host_host_id as parent_host_id, dsp.service_service_id as parent_service_id,
dsc.host_host_id as child_host_id, dsc.service_service_id as child_service_id
FROM dependency_serviceParent_relation dsp, dependency_serviceChild_relation dsc
WHERE dsp.dependency_dep_id = dsc.dependency_dep_id';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$listServices = [];
while ($row = $res->fetchRow()) {
$listServices[$row['parent_host_id'] . ';' . $row['parent_service_id'] . ';' . $row['child_host_id'] . ';' . $row['child_service_id']] = $row;
}
if ($withSg) {
$querySg = 'SELECT dsgp.servicegroup_sg_id as parent_sg, dsgc.servicegroup_sg_id as child_sg
FROM dependency_servicegroupParent_relation dsgp, dependency_servicegroupChild_relation dsgc
WHERE dsgp.dependency_dep_id = dsgc.dependency_dep_id';
try {
$res = $this->db->query($querySg);
} catch (PDOException $e) {
return $listServices;
}
$sgObj = new CentreonServicegroups($this->db);
while ($row = $res->fetchRow()) {
$sgps = $sgObj->getServiceGroupServices($row['parent_sg']);
$sgcs = $sgObj->getServiceGroupServices($row['child_sg']);
foreach ($sgps as $sgp) {
foreach ($sgcs as $sgc) {
$listServices[$sgp[0] . ';' . $sgp[1] . ';' . $sgc[0] . ';' . $sgc[1]] = ['parent_host_id' => $sgp[0], 'parent_service_id' => $sgp[1], 'child_host_id' => $sgc[0], 'child_service_id' => $sgc[1]];
}
}
}
}
return $listServices;
}
/**
* Get the host host dependency
*
* @param bool $withHg If use hostgroup relation
* @return array
*/
public function getHostHost($withHg = false)
{
$query = 'SELECT dhp.host_host_id as parent_host_id, dhc.host_host_id as child_host_id
FROM dependency_hostParent_relation dhp, dependency_hostChild_relation dhc
WHERE dhp.dependency_dep_id = dhc.dependency_dep_id';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$listHosts = [];
while ($row = $res->fetchRow()) {
$listHosts[$row['parent_host_id'] . ';' . $row['child_host_id']] = $row;
}
if ($withHg) {
$queryHg = 'SELECT dhgp.hostgroup_hg_id as parent_hg, dhgc.hostgroup_hg_id as child_hg
FROM dependency_hostgroupParent_relation dhgp, dependency_hostgroupChild_relation dhgc
WHERE dhgp.dependency_dep_id = dhgc.dependency_dep_id';
try {
$res = $this->db->query($queryHg);
} catch (PDOException $e) {
return $listHosts;
}
$hgObj = new CentreonHostgroups($this->db);
while ($row = $res->fetchRow()) {
$hgps = $hgObj->getHostGroupHosts($row['parent_hg']);
$hgcs = $hgObj->getHostGroupHosts($row['child_hg']);
foreach ($hgps as $hgp) {
foreach ($hgcs as $hgc) {
$listHosts[$hgp . ';' . $hgc] = ['parent_host_id' => $hgp, 'child_host_id' => $hgc];
}
}
}
}
return $listHosts;
}
/**
* Parent Host
* Dependent Service
*
* @return array
*/
public function getHostService()
{
$query = 'SELECT dhp.host_host_id as parent_host_id, dsc.host_host_id as child_host_id,
dsc.service_service_id as child_service_id
FROM dependency_hostParent_relation dhp, dependency_serviceChild_relation dsc
WHERE dhp.dependency_dep_id = dsc.dependency_dep_id';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$listHostService = [];
while ($row = $res->fetchRow()) {
$listHostService[] = $row;
}
return $listHostService;
}
/**
* Parent Service
* Dependent Host
*
* @return array
*/
public function getServiceHost()
{
$query = 'SELECT dsp.host_host_id as parent_host_id, dsp.service_service_id as parent_service_id,
dhc.host_host_id as child_host_id
FROM dependency_serviceParent_relation dsp, dependency_hostChild_relation dhc
WHERE dsp.dependency_dep_id = dhc.dependency_dep_id';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$listServiceHost = [];
while ($row = $res->fetchRow()) {
$listServiceHost[] = $row;
}
return $listServiceHost;
}
/**
* Purge obsolete dependencies that are no longer used
*
* @param CentreonDB $db
*
* @throws PDOException
*/
public static function purgeObsoleteDependencies($db): void
{
$sql = 'DELETE FROM dependency WHERE dep_id NOT IN (
SELECT DISTINCT dep.dependency_dep_id from (
SELECT dependency_dep_id FROM dependency_hostChild_relation
UNION
SELECT dependency_dep_id FROM dependency_hostParent_relation
UNION
SELECT dependency_dep_id FROM dependency_hostgroupChild_relation
UNION
SELECT dependency_dep_id FROM dependency_hostgroupParent_relation
UNION
SELECT dependency_dep_id FROM dependency_metaserviceChild_relation
union
SELECT dependency_dep_id FROM dependency_metaserviceParent_relation
union
SELECT dependency_dep_id FROM dependency_serviceChild_relation
union
SELECT dependency_dep_id FROM dependency_serviceParent_relation
union
SELECT dependency_dep_id FROM dependency_servicegroupChild_relation
union
SELECT dependency_dep_id FROM dependency_servicegroupParent_relation
) dep
)';
$db->query($sql);
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'host';
$parameters['currentObject']['id'] = 'host_id';
$parameters['currentObject']['name'] = 'host_name';
$parameters['currentObject']['comparator'] = 'host_id';
switch ($field) {
case 'dep_hostParents':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHost';
$parameters['externalObject']['table'] = 'host';
$parameters['externalObject']['id'] = 'host_id';
$parameters['externalObject']['name'] = 'host_name';
$parameters['externalObject']['comparator'] = 'host_id';
$parameters['relationObject']['table'] = 'dependency_hostParent_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_hostChilds':
case 'dep_hHostChi':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHost';
$parameters['externalObject']['table'] = 'host';
$parameters['externalObject']['id'] = 'host_id';
$parameters['externalObject']['name'] = 'host_name';
$parameters['externalObject']['comparator'] = 'host_id';
$parameters['relationObject']['table'] = 'dependency_hostChild_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_hSvPar':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonService';
$parameters['relationObject']['table'] = 'dependency_serviceParent_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['additionalField'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_hSvChi':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonService';
$parameters['relationObject']['table'] = 'dependency_serviceChild_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['additionalField'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_hgParents':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHostgroups';
$parameters['externalObject']['table'] = 'hostgroup';
$parameters['externalObject']['id'] = 'hg_id';
$parameters['externalObject']['name'] = 'hg_name';
$parameters['externalObject']['comparator'] = 'hg_id';
$parameters['relationObject']['table'] = 'dependency_hostgroupParent_relation';
$parameters['relationObject']['field'] = 'hostgroup_hg_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_hgChilds':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHostgroups';
$parameters['externalObject']['table'] = 'hostgroup';
$parameters['externalObject']['id'] = 'hg_id';
$parameters['externalObject']['name'] = 'hg_name';
$parameters['externalObject']['comparator'] = 'hg_id';
$parameters['relationObject']['table'] = 'dependency_hostgroupChild_relation';
$parameters['relationObject']['field'] = 'hostgroup_hg_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_sgParents':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonServicegroups';
$parameters['externalObject']['table'] = 'servicegroup';
$parameters['externalObject']['id'] = 'sg_id';
$parameters['externalObject']['name'] = 'sg_name';
$parameters['externalObject']['comparator'] = 'sg_id';
$parameters['relationObject']['table'] = 'dependency_servicegroupParent_relation';
$parameters['relationObject']['field'] = 'servicegroup_sg_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_sgChilds':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonServicegroups';
$parameters['externalObject']['table'] = 'servicegroup';
$parameters['externalObject']['id'] = 'sg_id';
$parameters['externalObject']['name'] = 'sg_name';
$parameters['externalObject']['comparator'] = 'sg_id';
$parameters['relationObject']['table'] = 'dependency_servicegroupChild_relation';
$parameters['relationObject']['field'] = 'servicegroup_sg_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_msParents':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonMeta';
$parameters['externalObject']['table'] = 'meta_service';
$parameters['externalObject']['id'] = 'meta_id';
$parameters['externalObject']['name'] = 'meta_name';
$parameters['externalObject']['comparator'] = 'meta_id';
$parameters['relationObject']['table'] = 'dependency_metaserviceParent_relation';
$parameters['relationObject']['field'] = 'meta_service_meta_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
case 'dep_msChilds':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonMeta';
$parameters['externalObject']['table'] = 'meta_service';
$parameters['externalObject']['id'] = 'meta_id';
$parameters['externalObject']['name'] = 'meta_name';
$parameters['externalObject']['comparator'] = 'meta_id';
$parameters['relationObject']['table'] = 'dependency_metaserviceChild_relation';
$parameters['relationObject']['field'] = 'meta_service_meta_id';
$parameters['relationObject']['comparator'] = 'dependency_dep_id';
break;
}
return $parameters;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonObjects.class.php | centreon/www/class/centreonObjects.class.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
*
*/
/**
* Class
*
* @class CentreonObjects
* @description Class that contains various methods for managing hosts
*/
class CentreonObjects
{
/** @var array */
public $hosts;
/** @var array */
public $services;
/** @var array */
public $hostgoups;
/** @var array */
public $servicegroups;
/** @var array */
public $commandes;
/** @var CentreonDB */
private $DB;
/**
* CentreonObjects constructor
*
* @param CentreonDB $pearDB
*/
public function __construct($pearDB)
{
$this->DB = $pearDB;
// $this->hostgroups = new CentreonHostGroups($pearDB);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraphPoller.class.php | centreon/www/class/centreonGraphPoller.class.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
*
*/
/**
* Class
*
* @class centreonGraphPoller
* @description Class tp get metrics for a poller and return this on JSON
*/
class centreonGraphPoller
{
/** @var */
public $rrdOptions;
/** @var */
public $arguments;
/** @var */
public $metrics;
/** @var */
public $graphData;
/** @var */
protected $generalOpt;
/** @var */
protected $extraDatas;
/** @var string Rrdtool command line */
private $commandLine;
/** @var int Poller id */
private $pollerId;
/** @var array Graph titles */
private $title;
/** @var array */
private $options;
/** @var array */
private $differentStats;
/** @var array */
private $colors;
/** @var CentreonDB */
private $db;
/** @var CentreonDB */
private $dbMonitoring;
/** @var string */
private $graphName;
/** @var string */
private $nagiosStatsPath;
/** @var array */
private $metricsInfos = [];
/**
* centreonGraphPoller constructor
*
* @param CentreonDB $db
* @param CentreonDB $dbMonitoring
*/
public function __construct($db, $dbMonitoring)
{
$this->db = $db;
$this->dbMonitoring = $dbMonitoring;
$this->initGraphOptions();
$this->initRrd();
}
/**
* Set poller graph
*
* @param int $pollerId
* @param string $graphName
*
* @return void
*/
public function setPoller($pollerId, $graphName): void
{
$this->graphName = $graphName;
$this->pollerId = $pollerId;
$this->extraDatas = ['title' => $this->title[$graphName], 'base' => 1000];
$this->rrdOptions = [];
$this->arguments = [];
$this->setRRDOption('imgformat', 'JSONTIME');
}
/**
* @return string
*/
public function getGraphName()
{
return $this->graphName;
}
/**
* @param string $graphName
*/
public function setGraphName($graphName = ''): void
{
$this->graphName = $graphName;
}
/**
* Add argument rrdtool
*
* @param string $arg
*
* @return void
*/
public function addArgument($arg): void
{
$this->arguments[] = $arg;
}
/**
* Add argument rrdtool
*
* @param string $name the key
* @param string $value
*
* @return void
*/
public function setRRDOption($name, $value = null): void
{
if (str_contains($value, ' ')) {
$value = "'" . $value . "'";
}
$this->rrdOptions[$name] = $value;
}
/**
* Add arguments for rrdtool command line
*
* @param int $start
* @param int $end
*
* @throws RuntimeException
* @return void
*/
public function buildCommandLine($start, $end): void
{
$this->extraDatas['start'] = $start;
$this->extraDatas['end'] = $end;
$this->setRRDOption('start', $start);
$this->setRRDOption('end', $end);
$this->metrics = [];
$metrics = $this->differentStats[$this->options[$this->graphName]];
$i = 0;
foreach ($metrics as $metric) {
$path = $this->nagiosStatsPath . '/perfmon-' . $this->pollerId . '/' . $this->options[$this->graphName];
if (file_exists($path) === false) {
throw new RuntimeException();
}
$displayformat = '%7.2lf';
$this->addArgument('DEF:v' . $i . '=' . $path . ':' . $metric . ':AVERAGE');
$this->addArgument('VDEF:v' . $i . $metric . '=v' . $i . ',AVERAGE');
$this->addArgument('LINE1:v' . $i . '#0000ff:v' . $i);
$this->addArgument('GPRINT:v' . $i . $metric . ':"' . $metric . "\:" . $displayformat . '" ');
$this->metrics[] = ['metric_id' => $i, 'metric' => $metric, 'metric_legend' => $metric, 'legend' => $metric, 'ds_data' => ['ds_filled' => 0, 'ds_color_line' => $this->colors[$metric]]];
$i++;
}
}
/**
* Get graph result
*
* @param int $start
* @param int $end
*
* @throws RuntimeException
* @return array
*/
public function getGraph($start, $end)
{
$this->buildCommandLine($start, $end);
return $this->getJsonStream();
}
/**
* Init graph titles
*
* @return void
*/
private function initGraphOptions(): void
{
$this->title = ['active_host_check' => _('Host Check Execution Time'), 'active_host_last' => _('Hosts Actively Checked'), 'host_latency' => _('Host check latency'), 'active_service_check' => _('Service Check Execution Time'), 'active_service_last' => _('Services Actively Checked'), 'service_latency' => _('Service check latency'), 'cmd_buffer' => _('Commands in buffer'), 'host_states' => _('Host status'), 'service_states' => _('Service status')];
$this->colors = ['Min' => '#88b917', 'Max' => '#e00b3d', 'Average' => '#00bfb3', 'Last_Min' => '#00bfb3', 'Last_5_Min' => '#88b917', 'Last_15_Min' => '#ff9a13', 'Last_Hour' => '#F91D05', 'Up' => '#88b917', 'Down' => '#e00b3d', 'Unreach' => '#818285', 'Ok' => '#88b917', 'Warn' => '#ff9a13', 'Crit' => '#F91D05', 'Unk' => '#bcbdc0', 'In_Use' => '#88b917', 'Max_Used' => '#F91D05', 'Total_Available' => '#00bfb3'];
$this->options = ['active_host_check' => 'nagios_active_host_execution.rrd', 'active_host_last' => 'nagios_active_host_last.rrd', 'host_latency' => 'nagios_active_host_latency.rrd', 'active_service_check' => 'nagios_active_service_execution.rrd', 'active_service_last' => 'nagios_active_service_last.rrd', 'service_latency' => 'nagios_active_service_latency.rrd', 'cmd_buffer' => 'nagios_cmd_buffer.rrd', 'host_states' => 'nagios_hosts_states.rrd', 'service_states' => 'nagios_services_states.rrd'];
$this->differentStats = ['nagios_active_host_execution.rrd' => ['Min', 'Max', 'Average'], 'nagios_active_host_last.rrd' => ['Last_Min', 'Last_5_Min', 'Last_15_Min', 'Last_Hour'], 'nagios_active_host_latency.rrd' => ['Min', 'Max', 'Average'], 'nagios_active_service_execution.rrd' => ['Min', 'Max', 'Average'], 'nagios_active_service_last.rrd' => ['Last_Min', 'Last_5_Min', 'Last_15_Min', 'Last_Hour'], 'nagios_active_service_latency.rrd' => ['Min', 'Max', 'Average'], 'nagios_cmd_buffer.rrd' => ['In_Use', 'Max_Used', 'Total_Available'], 'nagios_hosts_states.rrd' => ['Up', 'Down', 'Unreach'], 'nagios_services_states.rrd' => ['Ok', 'Warn', 'Crit', 'Unk']];
}
/**
* Get rrdtool options
*
* @throws PDOException
* @return void
*/
private function initRrd(): void
{
$DBRESULT = $this->db->query('SELECT * FROM `options`');
$this->generalOpt = [];
while ($option = $DBRESULT->fetch()) {
$this->generalOpt[$option['key']] = $option['value'];
}
$DBRESULT->closeCursor();
$DBRESULT2 = $this->dbMonitoring->query('SELECT RRDdatabase_nagios_stats_path FROM config');
$nagiosStats = $DBRESULT2->fetch();
$this->nagiosStatsPath = $nagiosStats['RRDdatabase_nagios_stats_path'];
$DBRESULT2->closeCursor();
}
/**
* Log message
*
* @param string $message
*
* @return void
*/
private function log($message): void
{
if ($this->generalOpt['debug_rrdtool']
&& is_writable($this->generalOpt['debug_path'])) {
error_log(
'[' . date('d/m/Y H:i') . '] RDDTOOL : ' . $message . " \n",
3,
$this->generalOpt['debug_path'] . 'rrdtool.log'
);
}
}
/**
* Get rrdtool result
*
* @return mixed
*/
private function getJsonStream()
{
$commandLine = '';
$commandLine = ' graph - ';
foreach ($this->rrdOptions as $key => $value) {
$commandLine .= '--' . $key;
if (isset($value)) {
if (preg_match('/\'/', $value)) {
$value = "'" . preg_replace('/\'/', ' ', $value) . "'";
}
$commandLine .= '=' . $value;
}
$commandLine .= ' ';
}
foreach ($this->arguments as $arg) {
$commandLine .= ' ' . $arg . ' ';
}
$commandLine = preg_replace('/(\\$|`)/', '', $commandLine);
$this->log($commandLine);
if (is_writable($this->generalOpt['debug_path'])) {
$stderr = ['file', $this->generalOpt['debug_path'] . '/rrdtool.log', 'a'];
} else {
$stderr = ['pipe', 'a'];
}
$descriptorspec = [
0 => ['pipe', 'r'],
// stdin is pipe for reading
1 => ['pipe', 'w'],
// stdout is pipe for writing
2 => $stderr,
];
$process = proc_open($this->generalOpt['rrdtool_path_bin'] . ' - ', $descriptorspec, $pipes, null, null);
$this->graphData = ['global' => $this->extraDatas, 'metrics' => []];
foreach ($this->metrics as $metric) {
$this->graphData['metrics'][] = $metric;
}
if (is_resource($process)) {
fwrite($pipes[0], $commandLine);
fclose($pipes[0]);
$str = stream_get_contents($pipes[1]);
$returnValue = proc_close($process);
$str = preg_replace('/OK u:.*$/', '', $str);
$rrdData = json_decode($str, true);
}
$this->formatByMetrics($rrdData);
return $this->graphData;
}
/**
* Parse rrdtool result
*
* @param mixed $rrdData
*
* @return void
*/
private function formatByMetrics($rrdData): void
{
$this->graphData['times'] = [];
$size = count($rrdData['data']);
$gprintsSize = count($rrdData['meta']['gprints']);
for ($i = 0; $i < $size; $i++) {
$this->graphData['times'][] = $rrdData['data'][$i][0];
}
$i = 1;
$gprintsPos = 0;
foreach ($this->graphData['metrics'] as &$metric) {
$metric['data'] = [];
$metric['prints'] = [];
$insert = 0;
$metricFullname = 'v' . $metric['metric_id'];
for (; $gprintsPos < $gprintsSize; $gprintsPos++) {
if (isset($rrdData['meta']['gprints'][$gprintsPos]['line'])) {
if ($rrdData['meta']['gprints'][$gprintsPos]['line'] == $metricFullname) {
$insert = 1;
} else {
break;
}
} elseif ($insert == 1) {
$metric['prints'][] = array_values($rrdData['meta']['gprints'][$gprintsPos]);
}
}
for ($j = 0; $j < $size; $j++) {
$metric['data'][] = $rrdData['data'][$j][$i];
}
$i++;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonStatsModules.class.php | centreon/www/class/centreonStatsModules.class.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__ . '/../../bootstrap.php';
require_once __DIR__ . '/centreonDB.class.php';
use Psr\Log\LoggerInterface;
/**
* Class
*
* @class CentreonStatsModules
*/
class CentreonStatsModules
{
/** @var CentreonDB */
private $db;
/** @var LoggerInterface */
private $logger;
/**
* CentreonStatsModules constructor
*
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->db = new centreonDB();
$this->logger = $logger;
}
/**
* Get statistics from module
*
* @throws PDOException
* @return array The statistics of each module
*/
public function getModulesStatistics()
{
$data = [];
$moduleObjects = $this->getModuleObjects(
$this->getInstalledModules()
);
if (is_array($moduleObjects)) {
foreach ($moduleObjects as $moduleObject) {
try {
$oModuleObject = new $moduleObject();
$data[] = $oModuleObject->getStats();
} catch (Throwable $e) {
$this->logger->error($e->getMessage(), ['context' => $e]);
}
}
}
return $data;
}
/**
* Get list of installed modules
*
* @throws PDOException
* @return array Return the names of installed modules [['name' => string], ...]
*/
private function getInstalledModules()
{
$installedModules = [];
$stmt = $this->db->prepare('SELECT name FROM modules_informations');
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $value) {
$installedModules[] = $value['name'];
}
return $installedModules;
}
/**
* Get statistics module objects
*
* @param array $installedModules Names of installed modules for which you want
* to retrieve statistics module [['name' => string], ...]
*
* @return array Return a list of statistics module found
* @see CentreonStatsModules::getInstalledModules()
*/
private function getModuleObjects(array $installedModules)
{
$moduleObjects = [];
foreach ($installedModules as $module) {
if ($files = glob(_CENTREON_PATH_ . 'www/modules/' . $module . '/statistics/*.class.php')) {
foreach ($files as $fullFile) {
try {
include_once $fullFile;
$fileName = str_replace('.class.php', '', basename($fullFile));
if (class_exists(ucfirst($fileName))) {
$moduleObjects[] = ucfirst($fileName);
}
} catch (Throwable $e) {
$this->logger->error('Cannot get stats of module ' . $module);
}
}
}
}
return $moduleObjects;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/iFileManager.php | centreon/www/class/iFileManager.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
*
*/
/**
* Interface
*
* @class iFileManager
*/
interface iFileManager
{
/**
* @return mixed
*/
public function upload();
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonHosttemplates.class.php | centreon/www/class/centreonHosttemplates.class.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 _CENTREON_PATH_ . 'www/class/centreonInstance.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php';
/**
* Class
*
* @class CentreonHosttemplates
* @description Class that contains various methods for managing hosts
*/
class CentreonHosttemplates extends CentreonHost
{
/**
* @param array $values
* @param array $options
* @param string $register
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [], $register = '1')
{
return parent::getObjectForSelect2($values, $options, '0');
}
/**
* Returns array of host linked to the template
*
* @param string $hostTemplateName
* @param bool $checkTemplates
*
* @throws Exception
* @return array
*/
public function getLinkedHostsByName($hostTemplateName, $checkTemplates = true)
{
$register = $checkTemplates ? 0 : 1;
$linkedHosts = [];
$query = 'SELECT DISTINCT h.host_name
FROM host_template_relation htr, host h, host ht
WHERE htr.host_tpl_id = ht.host_id
AND htr.host_host_id = h.host_id
AND ht.host_register = "0"
AND h.host_register = :register
AND ht.host_name = :hostTplName';
try {
$result = $this->db->prepare($query);
$result->bindValue(':register', $register, PDO::PARAM_STR);
$result->bindValue(':hostTplName', $this->db->escape($hostTemplateName), PDO::PARAM_STR);
$result->execute();
} catch (PDOException $e) {
throw new Exception('Error while getting linked hosts of ' . $hostTemplateName);
}
while ($row = $result->fetch()) {
$linkedHosts[] = $row['host_name'];
}
return $linkedHosts;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonConnector.class.php | centreon/www/class/centreonConnector.class.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
*
*/
/*
* Class that contains various methods for managing connectors
*
* Usage example:
*
* <?php
* require_once realpath(dirname(__FILE__) . "/../../config/centreon.config.php");
* require_once _CENTREON_PATH_ . 'www/class/centreonConnector.class.php';
* require_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php';
*
* $connector = new CentreonConnector(new CentreonDB);
*
* //$connector->create(array(
* // 'name' => 'jackyse',
* // 'description' => 'some jacky',
* // 'command_line' => 'ls -la',
* // 'enabled' => true
* // ), true);
*
* //$connector->update(10, array(
* // 'name' => 'soapy',
* // 'description' => 'Lorem ipsum',
* // 'enabled' => true,
* // 'command_line' => 'ls -laph --color'
* //));
*
* //$connector->getList(false, 20, false);
*
* //$connector->delete(10);
*
* //$connector->read(7);
*
* //$connector->copy(1, 5, true);
*
* //$connector->count(false);
*
* //$connector->isNameAvailable('norExists');
*/
/**
* Class
*
* @class CentreonConnector
*/
class CentreonConnector
{
/** @var CentreonDB */
protected $dbConnection;
/**
* CentreonConnector constructor
*
* @param CentreonDB $dbConnection
*/
public function __construct($dbConnection)
{
$this->dbConnection = $dbConnection;
}
/**
* Adds a connector to the database
*
* @param array $connector
* @param bool $returnId
* @throws InvalidArgumentException
* @throws RuntimeException
* @return CentreonConnector|int
*/
public function create(array $connector, $returnId = false)
{
// Checking data
if (! isset($connector['name'])) {
throw new InvalidArgumentException('No name for the connector set');
}
if (empty($connector['name'])) {
throw new InvalidArgumentException('Empty name for the connector');
}
if (! array_key_exists('description', $connector)) {
$connector['description'] = null;
}
if (! array_key_exists('command_line', $connector)) {
$connector['command_line'] = null;
}
if (! array_key_exists('enabled', $connector)) {
$connector['enabled'] = true;
}
// Inserting into database
try {
$success = $this->dbConnection->prepare(
<<<'SQL'
INSERT INTO `connector` (
`name`,
`description`,
`command_line`,
`enabled`,
`created`,
`modified`
) VALUES (?, ?, ?, ?, ?, ?)
SQL
);
$success->execute([
$connector['name'],
$connector['description'],
$connector['command_line'],
$connector['enabled'],
$now = time(),
$now,
]);
} catch (PDOException $e) {
throw new RuntimeException('Cannot insert connector; Check the database schema');
}
// in case last inserted id needed
if ($returnId) {
try {
$lastIdQueryResult = $this->dbConnection->prepare(
'SELECT `id` FROM `connector` WHERE `name` = ? LIMIT 1'
);
$lastIdQueryResult->execute([$connector['name']]);
} catch (PDOException $e) {
throw new RuntimeException('Cannot get last insert ID');
}
$lastId = $lastIdQueryResult->fetchRow();
if (! isset($lastId['id'])) {
throw new RuntimeException('Field id for connector not selected in query or connector not inserted');
}
if (isset($connector['command_id'])) {
$statement = $this->dbConnection->prepare('UPDATE `command` '
. 'SET connector_id = :conId WHERE `command_id` = :value');
foreach ($connector['command_id'] as $key => $value) {
try {
$statement->bindValue(':conId', (int) $lastId['id'], PDO::PARAM_INT);
$statement->bindValue(':value', (int) $value, PDO::PARAM_INT);
$statement->execute();
} catch (PDOException $e) {
throw new RuntimeException('Cannot update connector');
}
}
}
return $lastId['id'];
}
return $this;
}
/**
* Reads the connector
*
* @param int $id
*
* @throws InvalidArgumentException
* @throws PDOException
* @throws RuntimeException
* @return array
*/
public function read($id)
{
if (! is_numeric($id)) {
throw new InvalidArgumentException('Id is not integer');
}
try {
$result = $this->dbConnection->prepare(
<<<'SQL'
SELECT
`id`,
`name`,
`description`,
`command_line`,
`enabled`,
`created`,
`modified`
FROM
`connector`
WHERE
`id` = ?
LIMIT
1
SQL
);
$result->execute([$id]);
} catch (PDOException $e) {
throw new RuntimeException('Cannot select connector');
}
$connector = $result->fetchRow();
$connector['id'] = (int) $connector['id'];
$connector['enabled'] = (bool) $connector['enabled'];
$connector['created'] = (int) $connector['created'];
$connector['modified'] = (int) $connector['modified'];
$connector['command_id'] = [];
$DBRESULT = $this->dbConnection->query("SELECT command_id FROM command WHERE connector_id = '{$id}'");
while ($row = $DBRESULT->fetchRow()) {
$connector['command_id'][] = $row['command_id'];
}
unset($row);
$DBRESULT->closeCursor();
return $connector;
}
/**
* Updates connector
*
* @param int $connectorId
* @param array $connector
*
* @throws RuntimeException
*
* @return CentreonConnector
*/
public function update(int $connectorId, array $connector = []): self
{
if ($connector === []) {
return $this;
}
try {
$this->dbConnection->beginTransaction();
$bindValues = [];
$subRequest = '';
if (isset($connector['name'])) {
$bindValues[':name'] = $connector['name'];
$subRequest = ', `name` = :name';
}
if (isset($connector['description'])) {
$bindValues[':description'] = $connector['description'];
$subRequest .= ', `description` = :description';
}
if (isset($connector['command_line'])) {
$bindValues[':command_line'] = $connector['command_line'];
$subRequest .= ', `command_line` = :command_line';
}
if (isset($connector['enabled'])) {
$bindValues[':enabled'] = $connector['enabled'];
$subRequest .= ', `enabled` = :enabled';
}
if ($bindValues !== []) {
$bindValues[':date_now'] = time();
$subRequest = '`modified` = :date_now' . $subRequest;
$statement = $this->dbConnection->prepare(
<<<SQL
UPDATE `connector`
SET {$subRequest}
WHERE `connector`.`id` = :id
LIMIT 1
SQL
);
$statement->bindValue(':id', (int) $connectorId, PDO::PARAM_INT);
foreach ($bindValues as $fieldName => $fieldValue) {
$statement->bindValue($fieldName, $fieldValue);
}
$statement->execute();
}
$statement = $this->dbConnection->prepare(
'UPDATE `command` SET connector_id = NULL WHERE `connector_id` = :id'
);
$statement->bindValue(':id', (int) $connectorId, PDO::PARAM_INT);
$statement->execute();
$commandIds = $connector['command_id'] ?? [];
foreach ($commandIds as $commandId) {
$statement = $this->dbConnection->prepare(
'UPDATE `command` SET `connector_id` = :id WHERE `command_id` = :command_id'
);
$statement->bindValue(':id', (int) $connectorId, PDO::PARAM_INT);
$statement->bindValue(':command_id', (int) $commandId, PDO::PARAM_INT);
$statement->execute();
}
$this->dbConnection->commit();
} catch (Throwable) {
$this->dbConnection->rollBack();
throw new RuntimeException('Cannot update connector');
}
return $this;
}
/**
* Deletes connector
*
* @param int $id
*
* @throws InvalidArgumentException
* @throws RuntimeException
* @return CentreonConnector
*/
public function delete($id)
{
if (! is_numeric($id)) {
throw new InvalidArgumentException('Id should be integer');
}
try {
$result = $this->dbConnection->prepare('DELETE FROM `connector` WHERE `id` = ? LIMIT 1');
$result->execute([$id]);
} catch (PDOException $e) {
throw new RuntimeException('Cannot delete connector');
}
return $this;
}
/**
* Gets list of connectors
*
* @param bool $onlyEnabled
* @param int|bool $page When false all connectors are returned
* @param int $perPage Ignored if $page == false
* @param bool $usedByCommand
* @throws InvalidArgumentException
* @throws RuntimeException
*/
public function getList($onlyEnabled = true, $page = false, $perPage = 30, $usedByCommand = false)
{
/**
* Checking parameters
*/
if (! is_numeric($page) && $page !== false) {
throw new InvalidArgumentException('Page number should be integer');
}
if (! is_numeric($perPage)) {
throw new InvalidArgumentException('Per page parameter should be integer');
}
if ($page === false) {
$restrictSql = '';
} else {
/**
* Calculating offset
*/
$offset = $page * $perPage;
$restrictSql = " LIMIT {$perPage} OFFSET {$offset}";
}
$sql = 'SELECT
`id`,
`name`,
`description`,
`command_line`,
`enabled`,
`created`,
`modified`
FROM
`connector`';
$whereClauses = [];
if ($onlyEnabled) {
$whereClauses[] = ' `enabled` = 1 ';
}
if ($usedByCommand) {
$whereClauses[] = ' `id` IN (SELECT DISTINCT `connector_id` FROM `command`) ';
}
foreach ($whereClauses as $i => $clause) {
if (! $i) {
$sql .= ' WHERE ';
} else {
$sql .= ' AND ';
}
$sql .= $clause;
}
$sql .= $restrictSql;
try {
$connectorsResult = $this->dbConnection->query($sql);
} catch (PDOException $e) {
throw new RuntimeException('Cannot select connectors');
}
$connectors = [];
while ($connector = $connectorsResult->fetchRow()) {
$connector['id'] = (int) $connector['id'];
$connector['enabled'] = (bool) $connector['enabled'];
$connector['created'] = (int) $connector['created'];
$connector['modified'] = (int) $connector['modified'];
$connectors[] = $connector;
}
return $connectors;
}
/**
* Copies existing connector
*
* @param int $id
* @param int $numberOfcopies
* @param bool $returnIds
*
* @throws InvalidArgumentException
* @throws PDOException
* @throws RuntimeException
* @return CentreonConnector|array
*/
public function copy($id, $numberOfcopies = 1, $returnIds = false)
{
try {
$connector = $this->read($id);
} catch (Exception $e) {
throw new RuntimeException('Cannot read connector', 404);
}
$ids = [];
$originalName = $connector['name'];
$suffix = 1;
for ($i = 0; $i < $numberOfcopies; $i++) {
$available = 0;
while (! $available) {
$newName = $originalName . '_' . $suffix;
$available = $this->isNameAvailable($newName);
++$suffix;
}
try {
$connector['name'] = $newName;
if ($returnIds) {
$ids[] = $this->create($connector, true);
} else {
$this->create($connector, false);
}
} catch (Exception $e) {
throw new RuntimeException('Cannot write one duplicated connector', 500);
}
}
if ($returnIds) {
return $ids;
}
return $this;
}
/**
* Counts total number of connectors
*
* @param bool $onlyEnabled
* @throws InvalidArgumentException
* @throws RuntimeException
* @return int
*/
public function count($onlyEnabled = true)
{
if (! is_bool($onlyEnabled)) {
throw new InvalidArgumentException('Parameter "onlyEnabled" should be boolean');
}
$error = false;
try {
if ($onlyEnabled) {
$countResult = $this->dbConnection->query(
'SELECT COUNT(*) AS \'count\' FROM `connector` WHERE `enabled` = 1'
);
} else {
$countResult = $this->dbConnection->query('SELECT COUNT(*) \'count\' FROM `connector`');
}
} catch (PDOException $e) {
$error = true;
}
if ($error || ! ($count = $countResult->fetchRow())) {
throw new RuntimeException('Cannot count connectors');
}
return $count['count'];
}
/**
* Verifies if connector exists by name
*
* @param string $name
* @param null $connectorId
*
* @throws InvalidArgumentException
* @throws PDOException
* @throws RuntimeException
* @return bool
*/
public function isNameAvailable($name, $connectorId = null)
{
if (! is_string($name)) {
throw new InvalidArgumentException('Name is not intrger');
}
if ($connectorId) {
if (! is_numeric($connectorId)) {
throw new InvalidArgumentException('Id is not an integer');
}
$existsResult = $this->dbConnection->prepare(
'SELECT `id` FROM `connector` WHERE `id` = ? AND `name` = ? LIMIT 1'
);
$existsResult->execute([$connectorId, $name]);
if ((bool) $existsResult->fetchRow()) {
return true;
}
}
try {
$existsResult = $this->dbConnection->prepare(
'SELECT `id` FROM `connector` WHERE `name` = ? LIMIT 1'
);
$existsResult->execute([$name]);
} catch (PDOException $e) {
throw new RuntimeException(
'Cannot verify if connector name already in use; Query not valid; Check the database schema'
);
}
return ! ((bool) $existsResult->fetchRow());
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'connector';
$parameters['currentObject']['id'] = 'connector_id';
$parameters['currentObject']['name'] = 'connector_name';
$parameters['currentObject']['comparator'] = 'connector_id';
switch ($field) {
case 'command_id':
$parameters['type'] = 'simple';
$parameters['reverse'] = true;
$parameters['externalObject']['table'] = 'command';
$parameters['externalObject']['id'] = 'command_id';
$parameters['externalObject']['name'] = 'command_name';
$parameters['externalObject']['comparator'] = 'command_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':id' . $v . ',';
$queryValues['id' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected connectors
$query = 'SELECT id, name FROM connector '
. 'WHERE id IN (' . $listValues . ') ORDER BY name ';
$stmt = $this->dbConnection->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['id'], 'text' => $row['name']];
}
return $items;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonRestHttp.class.php | centreon/www/class/centreonRestHttp.class.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 _CENTREON_PATH_ . '/www/class/centreonDB.class.php';
require_once _CENTREON_PATH_ . '/www/class/centreonLog.class.php';
/**
* Class
*
* @class CentreonRestHttp
* @description Utils class for call HTTP JSON REST
*/
class CentreonRestHttp
{
/** @var string The content type : default application/json */
private $contentType = 'application/json';
/** @var string|null using a proxy */
private $proxy = null;
/** @var string proxy authentication information */
private $proxyAuthentication = null;
/** @var CentreonLog|null logFileThe The log file for call errors */
private $logObj = null;
/**
* CentreonRestHttp constructor
*
* @param string $contentType The content type
* @param string|null $logFile
*
* @throws PDOException
*/
public function __construct($contentType = 'application/json', $logFile = null)
{
$this->getProxy();
$this->contentType = $contentType;
if (! is_null($logFile)) {
$this->logObj = new CentreonLog([4 => $logFile]);
}
}
/**
* Call the http rest endpoint
*
* @param string $url The endpoint url
* @param string $method The HTTP method
* @param array|null $data The data to send on the request
* @param array $headers The extra headers without Content-Type
* @param bool $throwContent
* @param bool $noCheckCertificate To disable CURLOPT_SSL_VERIFYPEER
* @param bool $noProxy To disable CURLOPT_PROXY
*
* @throws RestBadRequestException
* @throws RestConflictException
* @throws RestForbiddenException
* @throws RestInternalServerErrorException
* @throws RestMethodNotAllowedException
* @throws RestNotFoundException
* @throws RestUnauthorizedException
* @return array The result content
*/
public function call($url, $method = 'GET', $data = null, $headers = [], $throwContent = false, $noCheckCertificate = false, $noProxy = false)
{
// Add content type to headers
$headers[] = 'Content-type: ' . $this->contentType;
$headers[] = 'Connection: close';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($noCheckCertificate) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
if (! $noProxy && ! is_null($this->proxy)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
if (! is_null($this->proxyAuthentication)) {
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->proxyAuthentication);
}
}
switch ($method) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
break;
case 'GET':
curl_setopt($ch, CURLOPT_HTTPGET, true);
break;
default:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
break;
}
if (! is_null($data)) {
if (isset($this->contentType) && $this->contentType == 'application/json') {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
}
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (! $http_code) {
$http_code = 404;
}
curl_close($ch);
$decodedContent = '';
if ($result) {
$decodedContent = json_decode($result, true);
// if it is not possible to parse json, then result is probably a string
if (! is_array($decodedContent) && is_string($result)) {
$decodedContent = [
'message' => $result,
];
}
}
// Manage HTTP status code
$exceptionClass = null;
$logMessage = 'Unknown HTTP error';
switch ($http_code) {
case 200:
case 201:
case 204:
break;
case 400:
$exceptionClass = 'RestBadRequestException';
break;
case 401:
$exceptionClass = 'RestUnauthorizedException';
break;
case 403:
$exceptionClass = 'RestForbiddenException';
break;
case 404:
$exceptionClass = 'RestNotFoundException';
$logMessage = 'Page not found';
break;
case 405:
$exceptionClass = 'RestMethodNotAllowedException';
break;
case 409:
$exceptionClass = 'RestConflictException';
break;
case 500:
default:
$exceptionClass = 'RestInternalServerErrorException';
break;
}
if (! is_null($exceptionClass)) {
if ($throwContent && is_array($decodedContent)) {
$message = json_encode($decodedContent);
} elseif (isset($decodedContent['message'])) {
$message = $decodedContent['message'];
} else {
$message = $logMessage;
}
$this->insertLog($message, $url, $exceptionClass);
throw new $exceptionClass($message);
}
// Return the content
return $decodedContent;
}
/**
* @param string $url
* @param string|int $port
*
* @return void
*/
public function setProxy($url, $port): void
{
if (isset($url) && ! empty($url)) {
$this->proxy = $url;
if ($port) {
$this->proxy .= ':' . $port;
}
}
}
/**
* @param $output
* @param $url
* @param $type
*
* @return void
*/
private function insertLog($output, $url, $type = 'RestInternalServerErrorException'): void
{
if (is_null($this->logObj)) {
return;
}
$logOutput = '[' . $type . '] ' . $url . ' : ' . $output;
$this->logObj->insertLog(4, $logOutput);
}
/**
* @throws PDOException
* @return void
*/
private function getProxy(): void
{
$db = new CentreonDB();
$query = 'SELECT `key`, `value` '
. 'FROM `options` '
. 'WHERE `key` IN ( '
. '"proxy_url", "proxy_port", "proxy_user", "proxy_password" '
. ') ';
$res = $db->query($query);
while ($row = $res->fetchRow()) {
$dataProxy[$row['key']] = $row['value'];
}
if (isset($dataProxy['proxy_url']) && ! empty($dataProxy['proxy_url'])) {
$this->proxy = $dataProxy['proxy_url'];
if ($dataProxy['proxy_port']) {
$this->proxy .= ':' . $dataProxy['proxy_port'];
}
// Proxy basic authentication
if (isset($dataProxy['proxy_user']) && ! empty($dataProxy['proxy_user'])
&& isset($dataProxy['proxy_password']) && ! empty($dataProxy['proxy_password'])) {
$this->proxyAuthentication = $dataProxy['proxy_user'] . ':' . $dataProxy['proxy_password'];
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonPurgeEngine.class.php | centreon/www/class/centreonPurgeEngine.class.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 realpath(__DIR__ . '/centreonDB.class.php');
/**
* Class
*
* @class CentreonPurgeEngine
* @description Class that handles MySQL table partitions
*/
class CentreonPurgeEngine
{
/** @var string */
public $purgeAuditLogQuery = 'DELETE FROM log_action WHERE action_log_date < __RETENTION__';
/** @var CentreonDB */
private $dbCentstorage;
/** @var string */
private $purgeCommentsQuery;
/** @var string */
private $purgeDowntimesQuery;
/** @var array[] */
private $tablesToPurge;
/**
* CentreonPurgeEngine constructor
*
* @throws Exception
*/
public function __construct()
{
$this->purgeCommentsQuery = 'DELETE FROM comments WHERE (deletion_time is not null and deletion_time '
. '< __RETENTION__) OR (expire_time < __RETENTION__ AND expire_time <> 0)';
$this->purgeDowntimesQuery = 'DELETE FROM downtimes WHERE (actual_end_time is not null and actual_end_time '
. '< __RETENTION__) OR (deletion_time is not null and deletion_time < __RETENTION__)';
$this->tablesToPurge = ['data_bin' => ['retention_field' => 'len_storage_mysql', 'retention' => 0, 'is_partitioned' => false, 'ctime_field' => 'ctime'], 'logs' => ['retention_field' => 'archive_retention', 'retention' => 0, 'is_partitioned' => false, 'ctime_field' => 'ctime'], 'log_archive_host' => ['retention_field' => 'reporting_retention', 'retention' => 0, 'is_partitioned' => false, 'ctime_field' => 'date_end'], 'log_archive_service' => ['retention_field' => 'reporting_retention', 'retention' => 0, 'is_partitioned' => false, 'ctime_field' => 'date_end'], 'comments' => ['retention_field' => 'len_storage_comments', 'retention' => 0, 'is_partitioned' => false, 'custom_query' => $this->purgeCommentsQuery], 'downtimes' => ['retention_field' => 'len_storage_downtimes', 'retention' => 0, 'is_partitioned' => false, 'custom_query' => $this->purgeDowntimesQuery], 'log_action' => ['retention_field' => 'audit_log_retention', 'retention' => 0, 'is_partitioned' => false, 'custom_query' => $this->purgeAuditLogQuery]];
$this->dbCentstorage = new CentreonDB('centstorage');
$this->readConfig();
$this->checkTablesPartitioned();
}
/**
* @throws Exception
* @return void
*/
public function purge(): void
{
foreach ($this->tablesToPurge as $table => $parameters) {
if ($parameters['retention'] > 0) {
echo '[' . date(DATE_RFC822) . '] Purging table ' . $table . "...\n";
if ($parameters['is_partitioned']) {
$this->purgeParts($table);
} else {
$this->purgeOldData($table);
}
echo '[' . date(DATE_RFC822) . '] Table ' . $table . " purged\n";
}
}
echo '[' . date(DATE_RFC822) . "] Purging index_data...\n";
$this->purgeIndexData();
echo '[' . date(DATE_RFC822) . "] index_data purged\n";
echo '[' . date(DATE_RFC822) . "] Purging log_action_modification...\n";
$this->purgeLogActionModification();
echo '[' . date(DATE_RFC822) . "] log_action_modification purged\n";
}
/**
* @throws Exception
* @return void
*/
private function readConfig(): void
{
$query = 'SELECT len_storage_mysql,archive_retention,reporting_retention, '
. 'len_storage_downtimes, len_storage_comments, audit_log_retention FROM config';
try {
$DBRESULT = $this->dbCentstorage->query($query);
} catch (PDOException $e) {
throw new Exception('Cannot get retention information');
}
$ltime = localtime();
$row = $DBRESULT->fetchRow();
foreach ($this->tablesToPurge as &$table) {
if (isset($row[$table['retention_field']])
&& ! is_null($row[$table['retention_field']])
&& $row[$table['retention_field']] > 0
) {
$table['retention'] = mktime(
0,
0,
0,
$ltime[4] + 1,
$ltime[3] - $row[$table['retention_field']],
$ltime[5] + 1900
);
}
}
}
/**
* @throws Exception
* @return void
*/
private function checkTablesPartitioned(): void
{
foreach ($this->tablesToPurge as $name => $value) {
try {
$DBRESULT = $this->dbCentstorage->query('SHOW CREATE TABLE `' . dbcstg . '`.`' . $name . '`');
} catch (PDOException $e) {
throw new Exception('Cannot get partition information');
}
$row = $DBRESULT->fetchRow();
$matches = [];
// dont care of MAXVALUE
if (preg_match_all('/PARTITION `{0,1}(.*?)`{0,1} VALUES LESS THAN \((.*?)\)/', $row['Create Table'], $matches)) {
$this->tablesToPurge[$name]['is_partitioned'] = true;
$this->tablesToPurge[$name]['partitions'] = [];
for ($i = 0; isset($matches[1][$i]); $i++) {
$this->tablesToPurge[$name]['partitions'][$matches[1][$i]] = $matches[2][$i];
}
}
}
}
/**
* Drop partitions that are older than the retention duration
* @param MysqlTable $table
*/
private function purgeParts($table): int
{
$dropPartitions = [];
foreach ($this->tablesToPurge[$table]['partitions'] as $partName => $partTimestamp) {
if ($partTimestamp < $this->tablesToPurge[$table]['retention']) {
$dropPartitions[] = '`' . $partName . '`';
echo '[' . date(DATE_RFC822) . '] Partition will be delete ' . $partName . "\n";
}
}
if (count($dropPartitions) <= 0) {
return 0;
}
$request = 'ALTER TABLE `' . $table . '` DROP PARTITION ' . implode(', ', $dropPartitions);
try {
$DBRESULT = $this->dbCentstorage->query($request);
} catch (PDOException $e) {
throw new Exception('Error : Cannot drop partitions of table '
. $table . ', ' . $e->getMessage() . "\n");
return 1;
}
echo '[' . date(DATE_RFC822) . "] Partitions deleted\n";
return 0;
}
/**
* @param $table
*
* @throws Exception
* @return void
*/
private function purgeOldData($table): void
{
if (isset($this->tablesToPurge[$table]['custom_query'])) {
$request = str_replace(
'__RETENTION__',
$this->tablesToPurge[$table]['retention'],
$this->tablesToPurge[$table]['custom_query']
);
} else {
$request = 'DELETE FROM ' . $table . ' ';
$request .= 'WHERE ' . $this->tablesToPurge[$table]['ctime_field'] . ' < '
. $this->tablesToPurge[$table]['retention'];
}
try {
$DBRESULT = $this->dbCentstorage->query($request);
} catch (PDOException $e) {
throw new Exception('Error : Cannot purge ' . $table . ', ' . $e->getMessage() . "\n");
}
}
/**
* @throws Exception
* @return void
*/
private function purgeIndexData(): void
{
$request = "UPDATE index_data SET to_delete = '1' WHERE ";
$request .= 'NOT EXISTS(SELECT 1 FROM ' . db . '.service WHERE service.service_id = index_data.service_id)';
try {
$DBRESULT = $this->dbCentstorage->query($request);
} catch (PDOException $e) {
throw new Exception('Error : Cannot purge index_data, ' . $e->getMessage() . "\n");
}
}
/**
* @throws Exception
* @return void
*/
private function purgeLogActionModification(): void
{
$request = 'DELETE FROM log_action_modification WHERE action_log_id '
. 'NOT IN (SELECT action_log_id FROM log_action)';
try {
$DBRESULT = $this->dbCentstorage->query($request);
} catch (PDOException $e) {
throw new Exception('Error : Cannot purge log_action_modification, ' . $e->getMessage() . "\n");
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonHook.class.php | centreon/www/class/centreonHook.class.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
*
*/
/**
* Class
*
* @class CentreonHook
*/
class CentreonHook
{
/**
* @param $category
* @param $method
* @param $parameters
*
* @return array
*/
public static function execute($category, $method, $parameters = null)
{
global $centreon;
$result = [];
if (isset($centreon->hooks[$category][$method])) {
foreach ($centreon->hooks[$category][$method] as $hook) {
$hookPath = $hook['path'];
$hookClass = $hook['class'];
require_once $hookPath;
$object = new $hookClass();
$result[] = $object->{$method}($parameters);
}
}
return $result;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonTag.class.php | centreon/www/class/centreonTag.class.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
*
*/
/**
* Class
*
* @class CentreonTag
*/
class CentreonTag
{
/** @var CentreonDB */
protected $db;
/**
* CentreonTag constructor
*
* @param CentreonDB $pearDB
*/
public function __construct($pearDB)
{
$this->db = $pearDB;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':tags' . $v . ',';
$queryValues['tags' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected service categories
$query = 'SELECT tags_id, tags_name FROM mod_export_tags '
. 'WHERE tags_id IN (' . $listValues . ') ORDER BY tags_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['tags_id'], 'text' => $row['tags_name']];
}
return $items;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonWidget.class.php | centreon/www/class/centreonWidget.class.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 _CENTREON_PATH_ . 'www/class/centreonUtils.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonCustomView.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;
/**
* Class
*
* @class CentreonWidgetException
*/
class CentreonWidgetException extends Exception
{
}
/**
* Class
*
* @class CentreonWidget
*/
class CentreonWidget
{
/** @var CentreonCustomView */
public $customView;
/** @var int */
protected $userId;
/** @var CentreonDB */
protected $db;
/** @var array */
protected $widgets = [];
/** @var array */
protected $userGroups = [];
/**
* CentreonWidget constructor
*
* @param Centreon $centreon
* @param CentreonDB $db
*
* @throws Exception
*/
public function __construct($centreon, $db)
{
$this->userId = (int) $centreon->user->user_id;
$this->db = $db;
$query = 'SELECT contactgroup_cg_id '
. 'FROM contactgroup_contact_relation '
. 'WHERE contact_contact_id = :id';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $this->userId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$this->userGroups[$row['contactgroup_cg_id']] = $row['contactgroup_cg_id'];
}
$this->customView = new CentreonCustomView($centreon, $db);
}
/**
* @param int $widgetId
* @throws Exception
* @return null
*/
public function getWidgetType($widgetId)
{
$query = 'SELECT widget_model_id, widget_id FROM widgets WHERE widget_id = :widgetId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':widgetId', $widgetId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
return $row['widget_model_id'];
}
return null;
}
/**
* @param int $widgetId
* @throws Exception
* @return null
*/
public function getWidgetTitle($widgetId)
{
$query = 'SELECT title, widget_id FROM widgets WHERE widget_id = :id';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $widgetId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
return htmlentities($row['title'], ENT_QUOTES);
}
return null;
}
/**
* @param int $widgetModelId
* @throws Exception
* @return mixed
*/
public function getWidgetDirectory($widgetModelId)
{
$query = 'SELECT directory FROM widget_models WHERE widget_model_id = :id';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $widgetModelId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
return $row['directory'];
}
}
/**
* @param string|int $widgetModelId
* @param string $name
* @throws Exception
* @return int
*/
public function getParameterIdByName($widgetModelId, $name)
{
$tab = [];
if (! isset($tab[$widgetModelId])) {
$query = 'SELECT parameter_id, parameter_code_name '
. 'FROM widget_parameters '
. 'WHERE widget_model_id = :id';
$tab[$widgetModelId] = [];
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $widgetModelId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$tab[$widgetModelId][$row['parameter_code_name']] = $row['parameter_id'];
}
}
if (isset($tab[$widgetModelId][$name]) && $tab[$widgetModelId][$name]) {
return $tab[$widgetModelId][$name];
}
return 0;
}
/**
* @param string $type
* @param string $param
*
* @throws PDOException
* @return mixed|null
*/
public function getWidgetInfo($type = 'id', $param = '')
{
static $tabDir;
static $tabId;
if (! isset($tabId) || ! isset($tabDir)) {
$query = 'SELECT description, directory, title, widget_model_id, url, version, is_internal, author, '
. 'email, website, keywords, screenshot, thumbnail, autoRefresh '
. 'FROM widget_models';
$res = $this->db->query($query);
while ($row = $res->fetch()) {
$widgetInformation = [
'description' => $row['description'],
'directory' => $row['directory'],
'title' => $row['title'],
'widget_model_id' => $row['widget_model_id'],
'url' => $row['url'],
'version' => $row['is_internal'] === 0 ? $row['version'] : null,
'is_internal' => $row['is_internal'] === 1,
'author' => $row['author'],
'email' => $row['email'],
'website' => $row['website'],
'keywords' => $row['keywords'],
'screenshot' => $row['screenshot'],
'thumbnail' => $row['thumbnail'],
'autoRefresh' => $row['autoRefresh'],
];
$tabDir[$row['directory']] = $widgetInformation;
$tabId[$row['widget_model_id']] = $widgetInformation;
}
}
if ($type == 'directory' && isset($tabDir[$param])) {
return $tabDir[$param];
}
if ($type == 'id' && isset($tabId[$param])) {
return $tabId[$param];
}
return null;
}
/**
* @param int $customViewId
* @param int $widgetModelId
* @param string $widgetTitle
* @param bool $permission
* @param bool $authorized
*
* @throws CentreonWidgetException
* @throws Exception
*/
public function addWidget(
int $customViewId,
int $widgetModelId,
string $widgetTitle,
bool $permission,
bool $authorized,
): void {
if (! $authorized || ! $permission) {
throw new CentreonWidgetException('You are not allowed to add a widget.');
}
if (empty($customViewId) || empty($widgetModelId)) {
throw new CentreonWidgetException('No custom view or no widget selected');
}
$query = 'INSERT INTO widgets (title, widget_model_id) VALUES (:title, :id)';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':title', $widgetTitle, PDO::PARAM_STR);
$stmt->bindParam(':id', $widgetModelId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
// Get view layout
$query = 'SELECT layout '
. 'FROM custom_views '
. 'WHERE custom_view_id = :id';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new CentreonWidgetException('No view found');
}
$row = $stmt->fetch();
if (is_null($row)) {
throw new CentreonWidgetException('No view found');
}
$layout = str_replace('column_', '', $row['layout']);
// Default position
$newPosition = null;
// Prepare first position
$matrix = [];
$query = 'SELECT widget_order '
. 'FROM widget_views '
. 'WHERE custom_view_id = :id';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new CentreonWidgetException('No view found');
}
while ($position = $stmt->fetch()) {
[$col, $row] = explode('_', $position['widget_order']);
if (isset($matrix[$row]) == false) {
$matrix[$row] = [];
}
$matrix[$row][] = $col;
}
ksort($matrix);
$rowNb = 0; // current row in the foreach
foreach ($matrix as $row => $cols) {
if ($rowNb != $row) {
break;
}
if (count($cols) < $layout) {
sort($cols); // number of used columns in this row
for ($i = 0; $i < $layout; $i++) {
if (! isset($cols[$i]) || $cols[$i] != $i) {
$newPosition = $i . '_' . $rowNb;
break;
}
}
break;
}
$rowNb++;
}
if (is_null($newPosition)) {
$newPosition = '0_' . $rowNb;
}
$lastId = $this->getLastInsertedWidgetId($widgetTitle);
$query = 'INSERT INTO widget_views (custom_view_id, widget_id, widget_order) VALUES (:id, :lastId, :neworder)';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $customViewId, PDO::PARAM_INT);
$stmt->bindParam(':lastId', $lastId, PDO::PARAM_INT);
$stmt->bindParam(':neworder', $newPosition, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
}
/**
* Get Wiget Info By Id
*
* @param int $widgetModelId
*
* @throws PDOException
* @return mixed
*/
public function getWidgetInfoById($widgetModelId)
{
return $this->getWidgetInfo('id', $widgetModelId);
}
/**
* Get Widget Info By Directory
*
* @param string $directory
*
* @throws PDOException
* @return mixed
*/
public function getWidgetInfoByDirectory($directory)
{
return $this->getWidgetInfo('directory', $directory);
}
/**
* @param string|int $widgetId
* @throws CentreonWidgetException
* @throws Exception
* @return mixed
*/
public function getUrl($widgetId)
{
$query = 'SELECT url FROM widget_models wm, widgets w '
. 'WHERE wm.widget_model_id = w.widget_model_id '
. 'AND w.widget_id = :id';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $widgetId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$row = $stmt->fetch();
return $row['url'];
}
throw new CentreonWidgetException('No URL found for Widget #' . $widgetId);
}
/**
* @param string|int $widgetId
*
* @throws CentreonWidgetException
* @throws Exception
* @return mixed
*/
public function getRefreshInterval($widgetId)
{
$query = 'SELECT autoRefresh FROM widget_models wm, widgets w '
. 'WHERE wm.widget_model_id = w.widget_model_id '
. 'AND w.widget_id = :id';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $widgetId, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$row = $stmt->fetch();
return $row['autoRefresh'];
}
throw new CentreonWidgetException('No autoRefresh found for Widget #' . $widgetId);
}
/**
* @param int $viewId
*
* @throws Exception
* @return array
*/
public function getWidgetsFromViewId(int $viewId): array
{
if (! isset($this->widgets[$viewId])) {
$this->widgets[$viewId] = [];
$query = "SELECT w.widget_id, w.title, wm.url, widget_order
FROM widget_views wv, widgets w, widget_models wm
WHERE w.widget_id = wv.widget_id
AND wv.custom_view_id = :id
AND w.widget_model_id = wm.widget_model_id
ORDER BY
CAST(SUBSTRING_INDEX(widget_order, '_', 1) AS SIGNED INTEGER),
CAST(SUBSTRING_INDEX(widget_order, '_', -1) AS SIGNED INTEGER)";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $viewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$this->widgets[$viewId][$row['widget_id']]['title'] = htmlentities($row['title'], ENT_QUOTES);
$this->widgets[$viewId][$row['widget_id']]['url'] = $row['url'];
$this->widgets[$viewId][$row['widget_id']]['widget_order'] = $row['widget_order'];
$this->widgets[$viewId][$row['widget_id']]['widget_id'] = $row['widget_id'];
}
}
return $this->widgets[$viewId];
}
/**
* @param string $search
* @param array $range
*
* @throws Exception
* @return array
*/
public function getWidgetModels($search = '', $range = [])
{
$queryValues = [];
$query = 'SELECT SQL_CALC_FOUND_ROWS widget_model_id, title FROM widget_models ';
if ($search != '') {
$query .= 'WHERE title like :search ';
$queryValues['search'] = '%' . $search . '%';
}
$query .= 'ORDER BY title ';
if (! empty($range)) {
$query .= 'LIMIT :offset, :limit ';
$queryValues['offset'] = (int) $range[0];
$queryValues['limit'] = (int) $range[1];
}
$stmt = $this->db->prepare($query);
if (isset($queryValues['search'])) {
$stmt->bindParam(':search', $queryValues['search'], PDO::PARAM_STR);
}
if (isset($queryValues['offset'])) {
$stmt->bindParam(':offset', $queryValues['offset'], PDO::PARAM_INT);
$stmt->bindParam(':limit', $queryValues['limit'], PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$widgets = [];
while ($data = $stmt->fetch()) {
$widgets[] = ['id' => $data['widget_model_id'], 'text' => $data['title']];
}
return ['items' => $widgets, 'total' => (int) $this->db->numberRows()];
}
/**
* @param int $viewId
* @param array $widgetList
*
* @throws Exception
*/
public function updateViewWidgetRelations($viewId, array $widgetList = []): void
{
$query = 'DELETE FROM widget_views WHERE custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $viewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$str = '';
$queryValues = [];
foreach ($widgetList as $widgetId) {
if ($str != '') {
$str .= ',';
}
$str .= '(:viewId, :widgetId' . $widgetId . ')';
$queryValues['widgetId' . $widgetId] = (int) $widgetId;
}
if ($str != '') {
$query = 'INSERT INTO widget_views (custom_view_id, widget_id) VALUES ' . $str;
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $viewId, PDO::PARAM_INT);
foreach ($queryValues as $widgetId) {
$stmt->bindValue(':widgetId' . $widgetId, $widgetId, PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
}
}
/**
* @param string|int $widgetId
* @param bool $hasPermission
*
* @throws Exception
* @return array
*/
public function getParamsFromWidgetId($widgetId, $hasPermission = false)
{
static $params;
if (! isset($params)) {
$params = [];
$query = 'SELECT ft.is_connector, ft.ft_typename, p.parameter_id, p.parameter_name, p.default_value, '
. 'p.header_title, p.require_permission '
. 'FROM widget_parameters_field_type ft, widget_parameters p, widgets w '
. 'WHERE ft.field_type_id = p.field_type_id '
. 'AND p.widget_model_id = w.widget_model_id '
. 'AND w.widget_id = :widgetId '
. 'ORDER BY parameter_order ASC';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':widgetId', $widgetId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
if ($row['require_permission'] && $hasPermission == false) {
continue;
}
$params[$row['parameter_id']]['parameter_id'] = $row['parameter_id'];
$params[$row['parameter_id']]['ft_typename'] = $row['ft_typename'];
$params[$row['parameter_id']]['parameter_name'] = $row['parameter_name'];
$params[$row['parameter_id']]['default_value'] = $row['default_value'];
$params[$row['parameter_id']]['is_connector'] = $row['is_connector'];
$params[$row['parameter_id']]['header_title'] = $row['header_title'];
}
}
return $params;
}
/**
* @param array $params
* @param bool $permission
* @param bool $authorized
*
* @throws CentreonWidgetException
* @throws PDOException
*/
public function updateUserWidgetPreferences(array $params, bool $permission, bool $authorized): void
{
if (! $authorized || ! $permission) {
throw new CentreonWidgetException('You are not allowed to set preferences on the widget');
}
$queryValues = [];
$query = 'SELECT wv.widget_view_id '
. 'FROM widget_views wv, custom_view_user_relation cvur '
. 'WHERE cvur.custom_view_id = wv.custom_view_id '
. 'AND wv.widget_id = :widgetId '
. 'AND (cvur.user_id = :userId';
$explodedValues = '';
if (count($this->userGroups)) {
foreach ($this->userGroups as $k => $v) {
$explodedValues .= ':userGroupId' . $v . ',';
$queryValues['userGroupId' . $v] = $v;
}
$explodedValues = rtrim($explodedValues, ',');
$query .= " OR cvur.usergroup_id IN ({$explodedValues}) ";
}
$query .= ') AND wv.custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':widgetId', $params['widget_id'], PDO::PARAM_INT);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$stmt->bindParam(':viewId', $params['custom_view_id'], PDO::PARAM_INT);
if (count($this->userGroups)) {
foreach ($queryValues as $key => $userGroupId) {
$stmt->bindValue(':' . $key, $userGroupId, PDO::PARAM_INT);
}
}
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$row = $stmt->fetch();
$widgetViewId = $row['widget_view_id'];
} else {
throw new CentreonWidgetException('No widget_view_id found for user');
}
if ($permission == false) {
$query = 'DELETE FROM widget_preferences '
. 'WHERE widget_view_id = :widgetViewId '
. 'AND user_id = :userId '
. 'AND parameter_id NOT IN ('
. 'SELECT parameter_id FROM widget_parameters WHERE require_permission = "1")';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':widgetViewId', $widgetViewId, PDO::PARAM_INT);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
} else {
$query = 'DELETE FROM widget_preferences '
. 'WHERE widget_view_id = :widgetViewId '
. 'AND user_id = :userId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':widgetViewId', $widgetViewId, PDO::PARAM_INT);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
}
$queryValues = [];
$str = '';
foreach ($params as $key => $val) {
if (preg_match("/param_(\d+)/", $key, $matches)) {
if (is_array($val)) {
if (isset($val['op_' . $matches[1]], $val['cmp_' . $matches[1]])) {
$val = $val['op_' . $matches[1]] . ' ' . $val['cmp_' . $matches[1]];
} elseif (isset($val['order_' . $matches[1]], $val['column_' . $matches[1]])) {
$val = $val['column_' . $matches[1]] . ' ' . $val['order_' . $matches[1]];
} elseif (isset($val['from_' . $matches[1]], $val['to_' . $matches[1]])) {
$val = $val['from_' . $matches[1]] . ',' . $val['to_' . $matches[1]];
} else {
$val = implode(',', $val);
}
$val = trim($val);
}
if ($str != '') {
$str .= ', ';
}
$str .= '(:widgetViewId, :parameter' . $matches[1] . ', :preference' . $matches[1] . ', :userId)';
$queryValues['parameter'][':parameter' . $matches[1]] = $matches[1];
$queryValues['preference'][':preference' . $matches[1]] = $val;
}
}
if ($str != '') {
$query = 'INSERT INTO widget_preferences (widget_view_id, parameter_id, preference_value, user_id) '
. 'VALUES ' . $str;
$stmt = $this->db->prepare($query);
$stmt->bindValue(':widgetViewId', $widgetViewId, PDO::PARAM_INT);
$stmt->bindValue(':userId', $this->userId, PDO::PARAM_INT);
if (isset($queryValues['parameter'])) {
foreach ($queryValues['parameter'] as $k => $v) {
$stmt->bindValue($k, $v, PDO::PARAM_INT);
}
}
if (isset($queryValues['preference'])) {
foreach ($queryValues['preference'] as $k => $v) {
$stmt->bindValue($k, $v, PDO::PARAM_STR);
}
}
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
}
$this->customView->syncCustomView($params['custom_view_id']);
}
/**
* @param int $customViewId
* @param int $widgetId
* @param bool $authorized
* @param bool $permission
*
* @throws Exception
*/
public function deleteWidgetFromView(int $customViewId, int $widgetId, bool $authorized, bool $permission): void
{
if (! $authorized || ! $permission) {
throw new CentreonWidgetException('You are not allowed to delete the widget');
}
$query = 'DELETE FROM widget_views '
. 'WHERE custom_view_id = :viewId '
. 'AND widget_id = :widgetId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$stmt->bindParam(':widgetId', $widgetId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
}
/**
* Updates a widget position on a customview
*
* @param int $customViewId
* @param bool $permission
* @param array $positions
*
* @throws CentreonWidgetException
* @throws PDOException
*/
public function updateWidgetPositions(int $customViewId, bool $permission, array $positions = []): void
{
if (! $permission) {
throw new CentreonWidgetException('You are not allowed to change widget position');
}
if (empty($customViewId)) {
throw new CentreonWidgetException('No custom view id provided');
}
if ($positions !== [] && is_array($positions)) {
foreach ($positions as $rawData) {
if (preg_match('/([0-9]+)_([0-9]+)_([0-9]+)/', $rawData, $matches)) {
$widgetOrder = "{$matches[1]}_{$matches[2]}";
$widgetId = $matches[3];
$query = 'UPDATE widget_views SET widget_order = :widgetOrder '
. 'WHERE custom_view_id = :viewId '
. 'AND widget_id = :widgetId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':widgetOrder', $widgetOrder, PDO::PARAM_STR);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$stmt->bindParam(':widgetId', $widgetId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
}
}
}
}
/**
* Read Configuration File
*
* @param string $filename
*
* @return array
*/
public function readConfigFile($filename)
{
$xmlString = file_get_contents($filename);
$xmlObj = simplexml_load_string($xmlString);
return (new CentreonUtils())->objectIntoArray($xmlObj);
}
/**
* @param string $widgetPath
* @param string $directory
*
* @throws Exception
*/
public function install($widgetPath, $directory): void
{
$config = $this->readConfigFile($widgetPath . '/' . $directory . '/configs.xml');
if (! $config['autoRefresh']) {
$config['autoRefresh'] = 0;
}
$queryValues = [];
$query = 'INSERT INTO widget_models (title, description, url, version, directory, author, email, '
. 'website, keywords, screenshot, thumbnail, autoRefresh) '
. 'VALUES (:title, :description, :url, :version, :directory, :author, :email, '
. ':website, :keywords, :screenshot, :thumbnail, :autoRefresh)';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':title', $config['title'], PDO::PARAM_STR);
$stmt->bindParam(':description', $config['description'], PDO::PARAM_STR);
$stmt->bindParam(':url', $config['url'], PDO::PARAM_STR);
$stmt->bindParam(':version', $config['version'], PDO::PARAM_STR);
$stmt->bindParam(':directory', $directory, PDO::PARAM_STR);
$stmt->bindParam(':author', $config['author'], PDO::PARAM_STR);
$stmt->bindParam(':email', $config['email'], PDO::PARAM_STR);
$stmt->bindParam(':website', $config['website'], PDO::PARAM_STR);
$stmt->bindParam(':keywords', $config['keywords'], PDO::PARAM_STR);
$stmt->bindParam(':screenshot', $config['screenshot'], PDO::PARAM_STR);
$stmt->bindParam(':thumbnail', $config['thumbnail'], PDO::PARAM_STR);
$stmt->bindParam(':autoRefresh', $config['autoRefresh'], PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$lastId = $this->getLastInsertedWidgetModelId($directory);
$this->insertWidgetPreferences($lastId, $config);
}
/**
* @param string $widgetPath
* @param string $directory
*
* @throws Exception
*/
public function upgrade($widgetPath, $directory): void
{
$config = $this->readConfigFile($widgetPath . '/' . $directory . '/configs.xml');
if (! $config['autoRefresh']) {
$config['autoRefresh'] = 0;
}
$queryValues = [];
$query = 'UPDATE widget_models SET '
. 'title = ?, '
. 'description = ?, '
. 'url = ?, '
. 'version = ?, '
. 'author = ?, '
. 'email = ?, '
. 'website = ?, '
. 'keywords = ?, '
. 'screenshot = ?, '
. 'thumbnail = ?, '
. 'autoRefresh = ? '
. 'WHERE directory = ?';
$queryValues[] = (string) $config['title'];
$queryValues[] = (string) $config['description'];
$queryValues[] = (string) $config['url'];
$queryValues[] = (string) $config['version'];
$queryValues[] = (string) $config['author'];
$queryValues[] = (string) $config['email'];
$queryValues[] = (string) $config['website'];
$queryValues[] = (string) $config['keywords'];
$queryValues[] = (string) $config['screenshot'];
$queryValues[] = (string) $config['thumbnail'];
$queryValues[] = (int) $config['autoRefresh'];
$queryValues[] = (string) $directory;
$stmt = $this->db->prepare($query);
$dbResult = $stmt->execute($queryValues);
if (! $dbResult) {
throw new Exception('An error occured');
}
$info = $this->getWidgetInfoByDirectory($directory);
$this->upgradePreferences($info['widget_model_id'], $config);
}
/**
* @param string $directory
*
* @throws Exception
*/
public function uninstall($directory): void
{
$query = 'DELETE FROM widget_models WHERE directory = :directory';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':directory', $directory, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
}
/**
* @param int $widgetId
*
* @throws Exception
* @return array
*/
public function getWidgetPreferences($widgetId)
{
$query = 'SELECT default_value, parameter_code_name '
. 'FROM widget_parameters param, widgets w '
. 'WHERE w.widget_model_id = param.widget_model_id '
. 'AND w.widget_id = :widgetId';
// Prevent SQL injection with widget id
$stmt = $this->db->prepare($query);
$stmt->bindParam(':widgetId', $widgetId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$tab = [];
while ($row = $stmt->fetch()) {
$tab[$row['parameter_code_name']] = $row['default_value'];
}
try {
$query = 'SELECT pref.preference_value, param.parameter_code_name '
. 'FROM widget_preferences pref, widget_parameters param, widget_views wv '
. 'WHERE param.parameter_id = pref.parameter_id '
. 'AND pref.widget_view_id = wv.widget_view_id '
. 'AND wv.widget_id = :widgetId '
. 'AND pref.user_id = :userId';
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraphService.class.php | centreon/www/class/centreonGraphService.class.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 'centreonGraph.class.php';
/**
* Class
*
* @class CentreonGraphService
* @description Class for get metrics for a service and return this on JSON
*/
class CentreonGraphService extends CentreonGraph
{
public $listMetricsId;
protected $legends = [];
/**
* CentreonGraphService Constructor
*
* @param int $index The index data id
* @param string $userId The session id
*
* @throws PDOException
*/
public function __construct($index, $userId)
{
parent::__construct($userId, $index, 0, 1);
}
/**
* Get the metrics
*
* @param int $rows The number of points returned (Default: 200)
*
* @throws RuntimeException
* @return array
*/
public function getData($rows = 200)
{
$legendDataInfo = ['last' => 'LAST', 'min' => 'MINIMUM', 'max' => 'MAXIMUM', 'average' => 'AVERAGE', 'total' => 'TOTAL'];
// Flush RRDCached for have the last values
$this->flushRrdCached($this->listMetricsId);
$commandLine = '';
$defType = [0 => 'CDEF', 1 => 'VDEF'];
// Build command line
$commandLine .= ' xport ';
$commandLine .= ' --showtime';
$commandLine .= ' --start ' . $this->RRDoptions['start'];
$commandLine .= ' --end ' . $this->RRDoptions['end'];
$commandLine .= ' --maxrows ' . $rows;
// Build legend command line
$extraLegend = false;
$commandLegendLine = ' graph x';
$commandLegendLine .= ' --start ' . $this->RRDoptions['start'];
$commandLegendLine .= ' --end ' . $this->RRDoptions['end'];
$metrics = [];
$vname = [];
$virtuals = [];
$i = 0;
// Parse metrics
foreach ($this->metrics as $metric) {
if (isset($metric['virtual']) && $metric['virtual'] == 1) {
$virtuals[] = $metric;
$vname[$metric['metric']] = 'vv' . $i;
} else {
$path = $this->dbPath . '/' . $metric['metric_id'] . '.rrd';
if (file_exists($path) === false) {
throw new RuntimeException();
}
$commandLine .= ' DEF:v' . $i . '=' . $path . ':value:AVERAGE';
$commandLegendLine .= ' DEF:v' . $i . '=' . $path . ':value:AVERAGE';
$commandLine .= ' XPORT:v' . $i . ':v' . $i;
$vname[$metric['metric']] = 'v' . $i;
$info = ['data' => [], 'graph_type' => 'line', 'unit' => $metric['unit'], 'color' => $metric['ds_color_line'], 'negative' => false, 'stack' => false, 'crit' => null, 'warn' => null];
$info['legend'] = str_replace('\\\\', '\\', $metric['metric_legend']);
$info['metric_name'] = ! empty($metric['ds_name']) ? $metric['ds_name'] : $info['legend'];
// Add legend getting data
foreach ($legendDataInfo as $name => $key) {
if ($metric['ds_' . $name] !== '') {
$extraLegend = true;
if (($name == 'min' || $name == 'max')
&& (isset($metric['ds_minmax_int'])
&& $metric['ds_minmax_int'])
) {
$displayformat = '%7.0lf';
} else {
$displayformat = '%7.2lf';
}
$commandLegendLine .= ' VDEF:l' . $i . $key . '=v' . $i . ',' . $key;
$commandLegendLine .= ' PRINT:l' . $i . $key . ':"'
. str_replace(':', '\:', $metric['metric_legend'])
. '|' . ucfirst($name) . '|' . $displayformat . '"';
}
}
if (isset($metric['ds_color_area'], $metric['ds_filled'])
&& $metric['ds_filled'] === '1'
) {
$info['graph_type'] = 'area';
}
if (isset($metric['ds_invert']) && $metric['ds_invert'] == 1) {
$info['negative'] = true;
}
if (isset($metric['stack'])) {
$info['stack'] = $metric['stack'] == 1;
}
if (isset($metric['crit'])) {
$info['crit'] = $metric['crit'];
}
if (isset($metric['warn'])) {
$info['warn'] = $metric['warn'];
}
$metrics[] = $info;
}
$i++;
}
// Append virtual metrics
foreach ($virtuals as $metric) {
$commandLine .= ' ' . $defType[$metric['def_type']] . ':'
. $vname[$metric['metric']] . '='
. $this->subsRPN($metric['rpn_function'], $vname);
if ($metric['def_type'] == 0) {
$commandLine .= ' XPORT:' . $vname[$metric['metric']] . ':' . $vname[$metric['metric']];
$info = ['data' => [], 'legend' => $metric['metric_legend'], 'graph_type' => 'line', 'unit' => $metric['unit'], 'color' => $metric['ds_color_line'], 'negative' => false];
if (isset($metric['ds_color_area'], $metric['ds_filled'])
&& $metric['ds_filled'] === '1'
) {
$info['graph_type'] = 'area';
}
if (isset($metric['ds_invert']) && $metric['ds_invert'] == 1) {
$info['negative'] = true;
}
$metrics[] = $info;
}
}
$descriptorspec = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'a']];
$process = proc_open($this->generalOpt['rrdtool_path_bin'] . ' - ', $descriptorspec, $pipes, null, null);
if (is_resource($process) === false) {
throw new RuntimeException();
}
fwrite($pipes[0], $commandLine);
fclose($pipes[0]);
$str = '';
stream_set_blocking($pipes[1], 0);
do {
$status = proc_get_status($process);
$str .= stream_get_contents($pipes[1]);
} while ($status['running']);
$str .= stream_get_contents($pipes[1]);
// Remove text of the end of the stream
$str = preg_replace("/<\/xport>(.*)$/s", '</xport>', $str);
$exitCode = $status['exitcode'];
proc_close($process);
if ($exitCode != 0) {
throw new RuntimeException();
}
// Transform XML to values
$useXmlErrors = libxml_use_internal_errors(true);
$xml = simplexml_load_string($str);
if ($xml === false) {
throw new RuntimeException();
}
libxml_clear_errors();
libxml_use_internal_errors($useXmlErrors);
$rows = $xml->xpath('//xport/data/row');
foreach ($rows as $row) {
$time = null;
$i = 0;
foreach ($row->children() as $info) {
if (is_null($time)) {
$time = (string) $info;
} elseif (strtolower($info) === 'nan' || is_null($info)) {
$metrics[$i++]['data'][$time] = $info;
} elseif ($metrics[$i]['negative']) {
$metrics[$i++]['data'][$time] = floatval((string) $info) * -1;
} else {
$metrics[$i++]['data'][$time] = floatval((string) $info);
}
}
}
// Get legends
$descriptorspec = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'a']];
$process = proc_open($this->generalOpt['rrdtool_path_bin'] . ' - ', $descriptorspec, $pipes, null, null);
if (is_resource($process) === false) {
throw new RuntimeException();
}
fwrite($pipes[0], $commandLegendLine);
fclose($pipes[0]);
$str = '';
stream_set_blocking($pipes[1], 0);
do {
$status = proc_get_status($process);
$str .= stream_get_contents($pipes[1]);
} while ($status['running']);
$str .= stream_get_contents($pipes[1]);
$exitCode = $status['exitcode'];
proc_close($process);
if ($exitCode != 0) {
throw new RuntimeException();
}
// Parsing
$retLines = explode("\n", $str);
foreach ($retLines as $retLine) {
if (str_contains($retLine, '|')) {
$infos = explode('|', $retLine);
if (! isset($this->legends[$infos[0]])) {
$this->legends[$infos[0]] = ['extras' => []];
}
$this->legends[$infos[0]]['extras'][] = ['name' => $infos[1], 'value' => $infos[2]];
}
}
return $metrics;
}
/**
* Get limits lower and upper for a chart
*
* These values are defined on chart template
*
* @return array
*/
public function getLimits()
{
$limits = ['min' => null, 'max' => null];
if ($this->templateInformations['lower_limit'] !== '') {
$limits['min'] = $this->templateInformations['lower_limit'];
}
if ($this->templateInformations['upper_limit'] !== '') {
$limits['max'] = $this->templateInformations['upper_limit'];
}
return $limits;
}
/**
* Get the base for this chart
*
* @return int
*/
public function getBase()
{
return $this->templateInformations['base'] ?? 1000;
}
public function getLegends()
{
return $this->legends;
}
/**
* @param $hostId
* @param $serviceId
* @param $dbc
* @throws Exception
* @return mixed
*/
public static function getIndexId($hostId, $serviceId, $dbc)
{
$query = 'SELECT id FROM index_data '
. 'WHERE host_id = :host '
. 'AND service_id = :service';
$stmt = $dbc->prepare($query);
$stmt->bindParam(':host', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':service', $serviceId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$row = $stmt->fetch();
if ($row == false) {
throw new OutOfRangeException();
}
return $row['id'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonMedia.class.php | centreon/www/class/centreonMedia.class.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
*
*/
/**
* Class
*
* @class CentreonMedia
* @description Class used for managing images
*/
class CentreonMedia
{
public const CENTREON_MEDIA_PATH = __DIR__ . '/../img/media/';
/** @var CentreonDB */
protected $db;
/** @var array */
protected $filenames = [];
/** @var string */
protected $mediadirectoryname = '';
/**
* CentreonMedia constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Get media directory path
*
* @throws Exception
* @return string
*/
public function getMediaDirectory()
{
if (empty($this->mediadirectoryname)) {
return self::CENTREON_MEDIA_PATH;
}
return $this->mediadirectoryname;
}
/**
* Get media directory path
*
* @param mixed $dirname
* @throws Exception
* @return void
*/
public function setMediaDirectory($dirname): void
{
$this->mediadirectoryname = $dirname;
}
/**
* Returns ID of target directory
*
* @param string $dirName
*
* @throws PDOException
* @return int|null
*/
public function getDirectoryId($dirName): ?int
{
$dirName = $this->sanitizePath($dirName);
$statement = $this->db->prepare(
'SELECT dir_id FROM view_img_dir WHERE dir_name = :dirName LIMIT 1'
);
$statement->bindValue(':dirName', $dirName, PDO::PARAM_STR);
$statement->execute();
$dirId = null;
if ($row = $statement->fetch()) {
$dirId = (int) $row['dir_id'];
}
return $dirId;
}
/**
* Returns name of target directory
*
* @param int $directoryId
*
* @throws PDOException
* @return string
*/
public function getDirectoryName($directoryId)
{
$query = 'SELECT dir_name FROM view_img_dir WHERE dir_id = ' . $directoryId . ' LIMIT 1';
$result = $this->db->query($query);
$directoryName = null;
if ($result->rowCount()) {
$row = $result->fetchRow();
$directoryName = $row['dir_name'];
}
return $directoryName;
}
/**
* Add media directory
*
* @param string $dirName
* @param string $dirAlias
*
* @throws Exception
* @return int
*/
public function addDirectory($dirName, $dirAlias = null)
{
$dirName = $this->sanitizePath($dirName);
if (is_null($dirAlias)) {
$dirAlias = $dirName;
}
try {
$statement = $this->db->prepare(
'INSERT INTO `view_img_dir` (dir_name, dir_alias)
SELECT :dirName, :dirAlias FROM DUAL
WHERE NOT EXISTS (
SELECT dir_id FROM `view_img_dir`
WHERE `dir_name` = :dirName
AND `dir_alias` = :dirAlias
LIMIT 1
)'
);
$statement->bindValue(':dirName', $dirName, PDO::PARAM_STR);
$statement->bindValue(':dirAlias', $dirAlias, PDO::PARAM_STR);
$statement->execute();
} catch (PDOException $e) {
throw new Exception('Error while creating directory ' . $dirName, (int) $e->getCode(), $e);
}
$this->createDirectory($dirName);
return $this->getDirectoryId($dirName);
}
/**
* Returns ID of target Image
*
* @param string $imagename
* @param string|null $dirname
*
* @throws PDOException
* @return mixed
*/
public function getImageId($imagename, $dirname = null)
{
if (! isset($dirname)) {
$tab = preg_split("/\//", $imagename);
$dirname = $tab[0] ?? null;
$imagename = $tab[1] ?? null;
}
if (! isset($imagename) || ! isset($dirname)) {
return null;
}
$query = 'SELECT img.img_id '
. 'FROM view_img_dir dir, view_img_dir_relation rel, view_img img '
. 'WHERE dir.dir_id = rel.dir_dir_parent_id '
. 'AND rel.img_img_id = img.img_id '
. "AND img.img_path = '" . $imagename . "' "
. "AND dir.dir_name = '" . $dirname . "' "
. 'LIMIT 1';
$RES = $this->db->query($query);
$img_id = null;
if ($RES->rowCount()) {
$row = $RES->fetchRow();
$img_id = $row['img_id'];
}
return $img_id;
}
/**
* Returns the filename from a given id
*
* @param int|null $imgId
*
* @throws PDOException
* @return string
*/
public function getFilename($imgId = null)
{
if (! isset($imgId)) {
return '';
}
if (count($this->filenames)) {
return $this->filenames[$imgId] ?? '';
}
$query = 'SELECT img_id, img_path, dir_alias
FROM view_img vi, view_img_dir vid, view_img_dir_relation vidr
WHERE vidr.img_img_id = vi.img_id
AND vid.dir_id = vidr.dir_dir_parent_id';
$res = $this->db->query($query);
$this->filenames[0] = 0;
while ($row = $res->fetchRow()) {
$this->filenames[$row['img_id']] = $row['dir_alias'] . '/' . $row['img_path'];
}
return $this->filenames[$imgId] ?? '';
}
/**
* Extract files from archive file and returns filenames
*
* @param string $archiveFile
*
* @throws Exception
* @return array
*/
public static function getFilesFromArchive($archiveFile)
{
$fileName = basename($archiveFile);
$position = strrpos($fileName, '.');
if ($position === false) {
throw new Exception('Missing extension');
}
$extension = substr($fileName, ($position + 1));
$files = [];
$allowedExt = ['zip', 'tar', 'gz', 'tgzip', 'tgz', 'bz', 'tbzip', 'tbz', 'bzip', 'bz2', 'tbzip2', 'tbz2', 'bzip2'];
if (! in_array(strtolower($extension), $allowedExt)) {
throw new Exception('Unknown extension');
}
if (strtolower($extension) == 'zip') {
$archiveObj = new ZipArchive();
$res = $archiveObj->open($archiveFile);
if ($res !== true) {
throw new Exception('Could not read archive');
}
for ($i = 0; $i < $archiveObj->numFiles; $i++) {
$files[] = $archiveObj->statIndex($i)['name'];
}
} else {
$archiveObj = new PharData($archiveFile, Phar::KEY_AS_FILENAME);
foreach ($archiveObj as $file) {
$files[] = $file->getFilename();
}
}
if ($files === []) {
throw new Exception('Archive file is empty');
}
if (strtolower($extension) == 'zip') {
$archiveObj->extractTo(dirname($archiveFile), $files);
$archiveObj->close();
} elseif ($archiveObj->extractTo(dirname($archiveFile), $files) === false) {
throw new Exception('Could not extract files');
}
return $files;
}
/**
* @param array $parameters
* @param string|null $binary
*
* @throws Exception
* @return mixed
*/
public function addImage($parameters, $binary = null)
{
$imageId = null;
if (! isset($parameters['img_name']) || ! isset($parameters['img_path']) || ! isset($parameters['dir_name'])) {
throw new Exception('Cannot add media : missing parameters');
}
if (! isset($parameters['img_comment'])) {
$parameters['img_comment'] = '';
}
$directoryName = $this->sanitizePath($parameters['dir_name']);
$directoryId = $this->addDirectory($directoryName);
$imageName = htmlentities($parameters['img_name'], ENT_QUOTES, 'UTF-8');
$imagePath = htmlentities($parameters['img_path'], ENT_QUOTES, 'UTF-8');
$imageComment = htmlentities($parameters['img_comment'], ENT_QUOTES, 'UTF-8');
// Check if image already exists
$query = 'SELECT vidr.vidr_id '
. 'FROM view_img vi, view_img_dir vid, view_img_dir_relation vidr '
. 'WHERE vi.img_id = vidr.img_img_id '
. 'AND vid.dir_id = vidr.dir_dir_parent_id '
. 'AND vi.img_name = "' . $imageName . '" '
. 'AND vid.dir_name = "' . $directoryName . '" ';
$result = $this->db->query($query);
if (! $result->rowCount()) {
// Insert image in database
$query = 'INSERT INTO view_img '
. '(img_name, img_path, img_comment) '
. 'VALUES ( '
. '"' . $imageName . '", '
. '"' . $imagePath . '", '
. '"' . $imageComment . '" '
. ') ';
try {
$result = $this->db->query($query);
} catch (PDOException $e) {
throw new Exception('Error while creating image ' . $imageName);
}
// Get image id
$query = 'SELECT MAX(img_id) AS img_id '
. 'FROM view_img '
. 'WHERE img_name = "' . $imageName . '" '
. 'AND img_path = "' . $imagePath . '" ';
$error = false;
try {
$result = $this->db->query($query);
} catch (PDOException $e) {
$error = true;
}
if ($error || ! $result->rowCount()) {
throw new Exception('Error while creating image ' . $imageName);
}
$row = $result->fetchRow();
$imageId = $row['img_id'];
// Insert relation between directory and image
$statement = $this->db->prepare('INSERT INTO view_img_dir_relation (dir_dir_parent_id, img_img_id) '
. 'VALUES (:dirId, :imgId) ');
$statement->bindValue(':dirId', (int) $directoryId, PDO::PARAM_INT);
$statement->bindValue(':imgId', (int) $imageId, PDO::PARAM_INT);
try {
$statement->execute();
} catch (PDOException $e) {
throw new Exception('Error while inserting relation between' . $imageName . ' and ' . $directoryName);
}
} else {
$imageId = $this->getImageId($imageName, $directoryName);
}
// Create binary file if specified
if (! is_null($binary)) {
$directoryPath = $this->getMediaDirectory() . '/' . $directoryName . '/';
$this->createImage($directoryPath, $imagePath, $binary);
}
return $imageId;
}
/**
* Add directory
*
* @param string $dirname
*
* @throws Exception
*/
private function createDirectory($dirname): void
{
$mediaDirectory = $this->getMediaDirectory();
$fullPath = $mediaDirectory . '/' . basename($dirname);
// Create directory and nested folder structure
if (! is_dir($fullPath)) {
@mkdir($fullPath, 0755, true);
if (! is_dir($fullPath)) {
error_log('Impossible to create directory ' . $fullPath);
}
} elseif (fileperms($fullPath) !== 0755) {
chmod($fullPath, 0755);
}
}
/**
* @param string $path
*
* @return string
*/
private function sanitizePath($path)
{
$cleanstr = htmlentities($path, ENT_QUOTES, 'UTF-8');
$cleanstr = str_replace('/', '_', $cleanstr);
return str_replace('\\', '_', $cleanstr);
}
/**
* @param string $directoryPath
* @param string $imagePath
* @param string $binary
*/
private function createImage($directoryPath, $imagePath, $binary): void
{
$fullPath = $directoryPath . '/' . $imagePath;
$decodedBinary = base64_decode($binary);
if (! file_exists($fullPath)) {
file_put_contents($fullPath, $decodedBinary);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/HtmlAnalyzer.php | centreon/www/class/HtmlAnalyzer.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);
/**
* Class
*
* @class HtmlAnalyzer
*
* @deprecated Instead used {@see HtmlSanitizer}
*/
class HtmlAnalyzer
{
/** @var int */
private int $index = -1;
/** @var mixed|string */
private mixed $stringToSanitize;
/** @var int */
private int $deepTag = 0;
/**
* @param string $stringToSanitize
*/
public function __construct(string $stringToSanitize)
{
$this->stringToSanitize = $stringToSanitize;
}
/**
* Sanitize and remove html tags
*
* @param mixed $stringToSanitize
*
* @return string
*/
public static function sanitizeAndRemoveTags($stringToSanitize): string
{
$stringToSanitize = (string) $stringToSanitize;
$html = new self($stringToSanitize);
$newString = $html->removeHtmlTag();
return str_replace(["'", '"'], [''', '"'], $newString);
}
/**
* Remove html tag
*
* @return string
*/
public function removeHtmlTag(): string
{
$newString = '';
while (($token = $this->getNextToken()) !== null) {
if ($token === '<') {
$this->deepTag++;
} elseif ($token === '>') {
if ($this->deepTag > 0) {
$this->deepTag--;
} else {
$newString .= $token;
}
} elseif ($this->deepTag === 0) {
$newString .= $token;
}
}
return $newString;
}
/**
* Get next token
*
* @return string|null
*/
private function getNextToken(): ?string
{
$this->index++;
if (mb_strlen($this->stringToSanitize) > $this->index) {
return mb_substr($this->stringToSanitize, $this->index, 1);
}
return null;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonBase.class.php | centreon/www/class/centreonBase.class.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
*
*/
/**
* Class
*
* @class CentreonBase
* @description Class for request
*/
class CentreonBase
{
/** @var string */
public $index;
// Objects
/** @var CentreonDB */
protected $DB;
/** @var CentreonDB */
protected $DBC;
/** @var CentreonGMT */
protected $GMT;
/** @var CentreonHost */
protected $hostObj;
/** @var CentreonService */
protected $serviceObj;
/** @var string */
protected $sessionId;
// Variables
/** @var int */
protected $debug;
/** @var int|mixed */
protected $compress;
/** @var */
protected $userId;
/** @var */
protected $general_opt;
/**
* CentreonBase constructor
*
* <code>
* $obj = new CentreonBGRequest($_GET["session_id"], 1, 1, 0, 1);
* </code>
*
* @param string $sessionId
* @param bool $index
* @param bool $debug
* @param bool $compress
*
* @throws PDOException
*/
public function __construct($sessionId, $index, $debug, $compress = null)
{
if (! isset($debug)) {
$this->debug = 0;
}
(! isset($compress)) ? $this->compress = 1 : $this->compress = $compress;
if (! isset($sessionId)) {
echo 'Your must check your session id';
exit(1);
}
$this->sessionId = htmlentities($sessionId, ENT_QUOTES, 'UTF-8');
$this->index = htmlentities($index, ENT_QUOTES, 'UTF-8');
// Enable Database Connexions
$this->DB = new CentreonDB();
$this->DBC = new CentreonDB('centstorage');
// Init Objects
$this->hostObj = new CentreonHost($this->DB);
$this->serviceObj = new CentreonService($this->DB);
// Timezone management
$this->GMT = new CentreonGMT();
$this->GMT->getMyGMTFromSession($this->sessionId);
}
/**
* @param $options
*
* @return void
*/
public function setGeneralOption($options): void
{
$this->general_opt = $options;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonCommand.class.php | centreon/www/class/centreonCommand.class.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;
/**
* Class
*
* @class CentreonCommand
*/
class CentreonCommand
{
/** @var string[] */
public $aTypeMacro = ['1' => 'HOST', '2' => 'SERVICE'];
/** @var array[] */
public $aTypeCommand = ['host' => ['key' => '$_HOST', 'preg' => '/\$_HOST([\w_-]+)\$/'], 'service' => ['key' => '$_SERVICE', 'preg' => '/\$_SERVICE([\w_-]+)\$/']];
/** @var CentreonDB */
protected $db;
/**
* CentreonCommand constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Get list of check commands
*
* @throws Exception
* @return array
*/
public function getCheckCommands()
{
return $this->getCommandList(2);
}
/**
* Get list of notification commands
*
* @throws Exception
* @return array
*/
public function getNotificationCommands()
{
return $this->getCommandList(1);
}
/**
* Get list of misc commands
*
* @throws Exception
* @return array
*/
public function getMiscCommands()
{
return $this->getCommandList(3);
}
/**
* Returns array of locked commands
*
* @throws PDOException
* @return array
*/
public function getLockedCommands()
{
static $arr = null;
if (is_null($arr)) {
$arr = [];
$res = $this->db->query('SELECT command_id FROM command WHERE command_locked = 1');
while ($row = $res->fetch()) {
$arr[$row['command_id']] = true;
}
}
return $arr;
}
/**
* @param $iIdCommand
* @param $sType
* @param int $iWithFormatData
* @throws Exception
* @return array
*/
public function getMacroByIdAndType($iIdCommand, $sType, $iWithFormatData = 1)
{
$macroToFilter = ['SNMPVERSION', 'SNMPCOMMUNITY'];
if (empty($iIdCommand) || ! array_key_exists($sType, $this->aTypeCommand)) {
return [];
}
$aDescription = $this->getMacroDescription($iIdCommand);
$query = 'SELECT command_id, command_name, command_line '
. 'FROM command '
. 'WHERE command_type = 2 '
. 'AND command_id = :id '
. 'AND command_line like :command '
. 'ORDER BY command_name';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $iIdCommand, PDO::PARAM_INT);
$commandLine = '%' . $this->aTypeCommand[$sType]['key'] . '%';
$stmt->bindParam(':command', $commandLine, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$arr = [];
$i = 0;
if ($iWithFormatData == 1) {
while ($row = $stmt->fetch()) {
preg_match_all($this->aTypeCommand[$sType]['preg'], $row['command_line'], $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (! in_array($match[1], $macroToFilter)) {
$sName = $match[1];
$sDesc = $aDescription[$sName]['description'] ?? '';
$arr[$i]['macroInput_#index#'] = $sName;
$arr[$i]['macroValue_#index#'] = '';
$arr[$i]['macroPassword_#index#'] = null;
$arr[$i]['macroDescription_#index#'] = $sDesc;
$arr[$i]['macroDescription'] = $sDesc;
$arr[$i]['macroCommandFrom'] = $row['command_name'];
$i++;
}
}
}
} else {
while ($row = $stmt->fetch()) {
$arr[$row['command_id']] = $row['command_name'];
}
}
return $arr;
}
/**
* @param $iIdCmd
* @throws Exception
* @return array
*/
public function getMacroDescription($iIdCmd)
{
$aReturn = [];
$query = 'SELECT * FROM `on_demand_macro_command` WHERE `command_command_id` = :command';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':command', $iIdCmd, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$arr['id'] = $row['command_macro_id'];
$arr['name'] = $row['command_macro_name'];
$arr['description'] = $row['command_macro_desciption'];
$arr['type'] = $row['command_macro_type'];
$aReturn[$row['command_macro_name']] = $arr;
}
$stmt->closeCursor();
return $aReturn;
}
/**
* @param $iCommandId
* @param $aMacro
* @param $sType
* @throws Exception
* @return array
*/
public function getMacrosCommand($iCommandId, $aMacro, $sType)
{
$aReturn = [];
if (count($aMacro) > 0 && array_key_exists($sType, $this->aTypeMacro)) {
$queryValues = [];
$explodedValues = '';
$query = 'SELECT * FROM `on_demand_macro_command` '
. 'WHERE command_command_id = ? '
. 'AND command_macro_type = ? '
. 'AND command_macro_name IN (';
$queryValues[] = (int) $iCommandId;
$queryValues[] = (string) $sType;
if (! empty($aMacro)) {
foreach ($aMacro as $k => $v) {
$explodedValues .= '?,';
$queryValues[] = (string) $v;
}
$explodedValues = rtrim($explodedValues, ',');
} else {
$explodedValues .= '""';
}
$query .= $explodedValues . ')';
$stmt = $this->db->prepare($query);
$dbResult = $stmt->execute($queryValues);
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$arr['id'] = $row['command_macro_id'];
$arr['name'] = $row['command_macro_name'];
$arr['description'] = htmlentities($row['command_macro_desciption']);
$arr['type'] = $sType;
$aReturn[] = $arr;
}
$stmt->closeCursor();
}
return $aReturn;
}
/**
* @param $iCommandId
* @param $sStr
* @param $sType
*
* @throws Exception
* @return array
*/
public function matchObject($iCommandId, $sStr, $sType)
{
$macros = [];
$macrosDesc = [];
if (array_key_exists($sType, $this->aTypeMacro)) {
preg_match_all(
$this->aTypeCommand[strtolower($this->aTypeMacro[$sType])]['preg'],
$sStr,
$matches1,
PREG_SET_ORDER
);
foreach ($matches1 as $match) {
$macros[] = $match[1];
}
if ($macros !== []) {
$macrosDesc = $this->getMacrosCommand($iCommandId, $macros, $sType);
$aNames = array_column($macrosDesc, 'name');
foreach ($macros as $detail) {
if (! in_array($detail, $aNames) && ! empty($detail)) {
$arr['id'] = '';
$arr['name'] = $detail;
$arr['description'] = '';
$arr['type'] = $sType;
$macrosDesc[] = $arr;
}
}
}
}
return $macrosDesc;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':command' . $v . ',';
$queryValues['command' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected connectors
$query = 'SELECT command_id, command_name FROM command '
. 'WHERE command_id IN (' . $listValues . ') '
. 'ORDER BY command_name ';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetch()) {
$items[] = ['id' => $row['command_id'], 'text' => $row['command_name']];
}
return $items;
}
/**
* @param $id
* @param array $parameters
* @throws Exception
* @return array|mixed
*/
public function getParameters($id, $parameters = [])
{
$queryValues = [];
$explodedValues = '';
$arr = [];
if (empty($id)) {
return [];
}
if (count($parameters) > 0) {
foreach ($parameters as $k => $v) {
$explodedValues .= "`{$v}`,";
}
$explodedValues = rtrim($explodedValues, ',');
} else {
$explodedValues = '*';
}
$query = 'SELECT ' . $explodedValues . ' FROM command WHERE command_id = ?';
$queryValues[] = (int) $id;
$stmt = $this->db->prepare($query);
$dbResult = $stmt->execute($queryValues);
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$arr = $stmt->fetch();
}
return $arr;
}
/**
* @param $name
* @throws Exception
* @return array|mixed
*/
public function getCommandByName($name)
{
$arr = [];
$query = 'SELECT * FROM command WHERE command_name = :commandName';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':commandName', $name, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$arr = $stmt->fetch();
}
return $arr;
}
/**
* @param $name
* @throws Exception
* @return int|null
*/
public function getCommandIdByName($name)
{
$query = 'SELECT command_id FROM command WHERE command_name = :commandName';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':commandName', $name, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if (! $stmt->rowCount()) {
return null;
}
$row = $stmt->fetch();
return $row['command_id'];
}
/**
* @param $parameters
* @param bool $locked
* @throws Exception
*/
public function insert($parameters, $locked = false): void
{
try {
$cmaConnectorId = null;
if (
str_contains($parameters['command_name'] ?? '', '-CMA-')
|| str_contains($parameters['command_name'] ?? '', 'Centreon-Monitoring-Agent')
) {
$cmaConnectorId = $this->db->fetchOne(
'SELECT id FROM connector WHERE name = :name',
QueryParameters::create([
QueryParameter::string('name', 'Centreon Monitoring Agent'),
])
);
if ($cmaConnectorId === false) {
CentreonLog::create()->warning(
logTypeId: CentreonLog::TYPE_PLUGIN_PACK_MANAGER,
message: 'CMA Connector not found while inserting command '
. ($parameters['command_name'] ?? '') . 'command will be inserted without connector',
customContext: [
'command_name' => $parameters['command_name'] ?? '',
'command_line' => $parameters['command_line'] ?? '',
],
);
$cmaConnectorId = null;
}
}
$query = <<<'SQL'
INSERT INTO command (command_name, command_line, command_type, command_locked, connector_id)
VALUES (:command_name, :command_line, :command_type, :command_locked, :connector_id)
SQL;
$queryParameters = QueryParameters::create([
QueryParameter::string('command_name', $parameters['command_name'] ?? ''),
QueryParameter::string('command_line', $parameters['command_line'] ?? ''),
QueryParameter::int('command_type', $parameters['command_type'] ?? 2),
QueryParameter::int('command_locked', $locked ? 1 : 0),
QueryParameter::int('connector_id', $cmaConnectorId),
]);
$this->db->executeStatement($query, $queryParameters);
} catch (Exception $e) {
CentreonLog::create()->error(
logTypeId: CentreonLog::TYPE_PLUGIN_PACK_MANAGER,
message: 'Error while inserting command ' . ($parameters['command_name'] ?? ''),
customContext: [
'command_name' => $parameters['command_name'] ?? '',
'command_line' => $parameters['command_line'] ?? '',
],
exception: $e
);
throw new Exception('Error while inserting command ' . $parameters['command_name']);
}
}
/**
* @param $commandId
* @param $command
* @throws Exception
*/
public function update($commandId, $command): void
{
$sQuery = 'UPDATE `command` SET `command_line` = :line, `command_type` = :cType WHERE `command_id` = :id';
$stmt = $this->db->prepare($sQuery);
$stmt->bindParam(':line', $command['command_line'], PDO::PARAM_STR);
$stmt->bindParam(':cType', $command['command_type'], PDO::PARAM_INT);
$stmt->bindParam(':id', $commandId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('Error while update command ' . $command['command_name']);
}
}
/**
* @param $commandName
* @throws Exception
*/
public function deleteCommandByName($commandName): void
{
$sQuery = 'DELETE FROM command WHERE command_name = :commandName';
$stmt = $this->db->prepare($sQuery);
$stmt->bindParam(':commandName', $commandName, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('Error while delete command ' . $commandName);
}
}
/**
* @param $commandName
* @param bool $checkTemplates
* @throws Exception
* @return array
*/
public function getLinkedServicesByName($commandName, $checkTemplates = true)
{
$register = $checkTemplates ? 0 : 1;
$linkedCommands = [];
$query = 'SELECT DISTINCT s.service_description '
. 'FROM service s, command c '
. 'WHERE s.command_command_id = c.command_id '
. 'AND s.service_register = :register '
. 'AND c.command_name = :commandName ';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':register', $register, PDO::PARAM_STR);
$stmt->bindParam(':commandName', $commandName, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('Error while getting linked services of ' . $commandName);
}
while ($row = $stmt->fetch()) {
$linkedCommands[] = $row['service_description'];
}
return $linkedCommands;
}
/**
* @param $commandName
* @param bool $checkTemplates
* @throws Exception
* @return array
*/
public function getLinkedHostsByName($commandName, $checkTemplates = true)
{
$register = $checkTemplates ? 0 : 1;
$linkedCommands = [];
$query = 'SELECT DISTINCT h.host_name '
. 'FROM host h, command c '
. 'WHERE h.command_command_id = c.command_id '
. 'AND h.host_register = :register '
. 'AND c.command_name = :commandName ';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':register', $register, PDO::PARAM_STR);
$stmt->bindParam(':commandName', $commandName, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('Error while getting linked hosts of ' . $commandName);
}
while ($row = $stmt->fetch()) {
$linkedCommands[] = $row['host_name'];
}
return $linkedCommands;
}
/**
* @param $commandType
* @throws Exception
* @return array
*/
protected function getCommandList($commandType)
{
$query = 'SELECT command_id, command_name '
. 'FROM command '
. 'WHERE command_type = :type '
. 'ORDER BY command_name';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':type', $commandType, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$arr = [];
while ($row = $stmt->fetch()) {
$arr[$row['command_id']] = $row['command_name'];
}
return $arr;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonImageManager.php | centreon/www/class/centreonImageManager.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 Pimple\Container;
/**
* Class
*
* @class CentreonImageManager
*/
class CentreonImageManager extends centreonFileManager
{
/** @var string[] */
protected $legalExtensions = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
/** @var int */
protected $legalSize = 2000000;
/** @var mixed */
protected $dbConfig;
/**
* CentreonImageManager constructor
*
* @param Container $dependencyInjector
* @param $rawFile
* @param $basePath
* @param $destinationDir
* @param string $comment
*/
public function __construct(
Container $dependencyInjector,
$rawFile,
$basePath,
$destinationDir,
$comment = '',
) {
parent::__construct($dependencyInjector, $rawFile, $basePath, $destinationDir, $comment);
$this->dbConfig = $this->dependencyInjector['configuration_db'];
}
/**
* @param bool $insert
* @return array|bool
*/
public function upload($insert = true)
{
$parentUpload = parent::upload();
if ($parentUpload) {
if ($insert) {
$img_ids[] = $this->insertImg();
return $img_ids;
}
} else {
return false;
}
}
/**
* Upload file from Temp Directory
*
* @param string $tempDirectory
* @param bool $insert
*
* @return array|bool
*/
public function uploadFromDirectory(string $tempDirectory, $insert = true)
{
$tempFullPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempDirectory;
if (! parent::fileExist()) {
$this->moveImage(
$tempFullPath . DIRECTORY_SEPARATOR . $this->rawFile['tmp_name'],
$this->destinationPath . DIRECTORY_SEPARATOR . $this->rawFile['name']
);
if ($insert) {
$img_ids[] = $this->insertImg();
return $img_ids;
}
} else {
return false;
}
}
/**
* @param string|int $imgId
* @param string $imgName
*
* @return bool
*/
public function update($imgId, $imgName)
{
if (! $imgId || empty($imgName)) {
return false;
}
$stmt = $this->dbConfig->prepare(
'SELECT dir_id, dir_alias, img_path, img_comment '
. 'FROM view_img, view_img_dir, view_img_dir_relation '
. 'WHERE img_id = :imgId AND img_id = img_img_id '
. 'AND dir_dir_parent_id = dir_id'
);
$stmt->bindParam(':imgId', $imgId);
$stmt->execute();
$img_info = $stmt->fetch();
// update if new file
if (! empty($this->originalFile) && ! empty($this->tmpFile)) {
$this->deleteImg($this->mediaPath . $img_info['dir_alias'] . '/' . $img_info['img_path']);
$this->upload(false);
$stmt = $this->dbConfig->prepare(
'UPDATE view_img SET img_path = :path WHERE img_id = :imgId'
);
$stmt->bindParam(':path', $this->newFile);
$stmt->bindParam(':imgId', $imgId);
$stmt->execute();
}
// update image info
$stmt = $this->dbConfig->prepare(
'UPDATE view_img SET img_name = :imgName, '
. 'img_comment = :imgComment WHERE img_id = :imgId'
);
$stmt->bindParam(':imgName', $this->secureName($imgName));
$stmt->bindParam(':imgComment', $this->comment);
$stmt->bindParam(':imgId', $imgId);
$stmt->execute();
// check directory
if (! ($dirId = $this->checkDirectoryExistence())) {
$dirId = $this->insertDirectory();
}
// Create directory if not exist
if ($img_info['dir_alias'] != $this->destinationDir) {
$img_info['img_path'] = basename($img_info['img_path']);
$img_info['dir_alias'] = basename($img_info['dir_alias']);
$old = $this->mediaPath . $img_info['dir_alias'] . '/' . $img_info['img_path'];
$new = $this->mediaPath . $this->destinationDir . '/' . $img_info['img_path'];
$this->moveImage($old, $new);
}
// update relation
$stmt = $this->dbConfig->prepare(
'UPDATE view_img_dir_relation SET dir_dir_parent_id = :dirId '
. 'WHERE img_img_id = :imgId'
);
$stmt->bindParam(':dirId', $dirId);
$stmt->bindParam(':imgId', $imgId);
$stmt->execute();
return true;
}
/**
* @param string $fullPath
*
* @return void
*/
protected function deleteImg($fullPath)
{
unlink($fullPath);
}
/**
* @return int
*/
protected function checkDirectoryExistence()
{
$dirId = 0;
$query = 'SELECT dir_name, dir_id FROM view_img_dir WHERE dir_name = :dirName';
$stmt = $this->dbConfig->prepare($query);
$stmt->bindParam(':dirName', $this->destinationDir);
$stmt->execute();
if ($stmt->rowCount() >= 1) {
$dir = $stmt->fetch();
$dirId = $dir['dir_id'];
}
return $dirId;
}
/**
* @return mixed
*/
protected function insertDirectory()
{
touch($this->destinationPath . '/index.html');
$stmt = $this->dbConfig->prepare(
'INSERT INTO view_img_dir (dir_name, dir_alias) '
. 'VALUES (:dirName, :dirAlias)'
);
$stmt->bindParam(':dirName', $this->destinationDir, PDO::PARAM_STR);
$stmt->bindParam(':dirAlias', $this->destinationDir, PDO::PARAM_STR);
if ($stmt->execute()) {
return $this->dbConfig->lastInsertId();
}
return null;
}
/**
* @param $dirId
*
* @return void
*/
protected function updateDirectory($dirId)
{
$query = 'UPDATE view_img_dir SET dir_name = :dirName, dir_alias = :dirAlias WHERE dir_id = :dirId';
$stmt = $this->dbConfig->prepare($query);
$stmt->bindParam(':dirName', $this->destinationDir, PDO::PARAM_STR);
$stmt->bindParam(':dirAlias', $this->destinationDir, PDO::PARAM_STR);
$stmt->bindParam(':dirId', $dirId, PDO::PARAM_INT);
$stmt->execute();
}
/**
* @return mixed
*/
protected function insertImg()
{
if (! ($dirId = $this->checkDirectoryExistence())) {
$dirId = $this->insertDirectory();
}
$stmt = $this->dbConfig->prepare(
'INSERT INTO view_img (img_name, img_path, img_comment) '
. 'VALUES (:imgName, :imgPath, :dirComment)'
);
$stmt->bindParam(':imgName', $this->fileName, PDO::PARAM_STR);
$stmt->bindParam(':imgPath', $this->newFile, PDO::PARAM_STR);
$stmt->bindParam(':dirComment', $this->comment, PDO::PARAM_STR);
$stmt->execute();
$imgId = $this->dbConfig->lastInsertId();
$stmt = $this->dbConfig->prepare(
'INSERT INTO view_img_dir_relation (dir_dir_parent_id, img_img_id) '
. 'VALUES (:dirId, :imgId)'
);
$stmt->bindParam(':dirId', $dirId, PDO::PARAM_INT);
$stmt->bindParam(':imgId', $imgId, PDO::PARAM_INT);
$stmt->execute();
$stmt->closeCursor();
return $imgId;
}
/**
* @param string $old
* @param string $new
*/
protected function moveImage($old, $new)
{
copy($old, $new);
$this->deleteImg($old);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonDowntime.Broker.class.php | centreon/www/class/centreonDowntime.Broker.class.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 _CENTREON_PATH_ . 'www/class/centreonDowntime.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php';
/**
* Class
*
* @class CentreonDowntimeBroker
* @description Class for management downtime with ndo broker
* @extends CentreonDowntime
*/
class CentreonDowntimeBroker extends CentreonDowntime
{
/** @var CentreonDB */
private $dbb;
/** @var null */
private $scheduledDowntimes = null;
/**
* CentreonDowntimeBroker constructor
*
* @param CentreonDb $pearDB
* @param string $varlib
*/
public function __construct($pearDB, $varlib = null)
{
parent::__construct($pearDB, $varlib);
$this->dbb = new CentreonDB('centstorage');
$this->initPeriods();
}
/**
* Get the list of reccurrent downtime after now
*
* Return array
* array(
* 'services' => array(
* 0 => array('Host 1', 'Service 1')
* ),
* 'hosts' => array(
* 0 => array('Host 1')
* )
* )
*
* @return array An array with host and services for downtime, or false if in error
*/
public function getSchedDowntime()
{
$list = ['hosts' => [], 'services' => []];
$query = "SELECT d.internal_id as internal_downtime_id,
h.name as name1,
s.description as name2
FROM downtimes d, hosts h
LEFT JOIN services s ON s.host_id = h.host_id
WHERE d.host_id = h.host_id AND d.start_time > NOW() AND d.comment_data LIKE '[Downtime cycle%'";
try {
$res = $this->dbb->query($query);
} catch (PDOException $e) {
return false;
}
while ($row = $res->fetch()) {
if (isset($row['name2']) && $row['name2'] != '') {
$list['services'] = ['host_name' => $row['name1'], 'service_name' => $row['name2']];
} elseif (isset($row['name1']) && $row['name1'] != '') {
$list['hosts'] = ['host_name' => $row['name1']];
}
}
return $list;
}
/**
* Get the NDO internal ID
*
* @param string $oname1 The first object name (host_name)
* @param int $start_time The timestamp for starting downtime
* @param int $dt_id The downtime id
* @param string $oname2 The second object name (service_name), is null if search a host
* @return int
*/
public function getDowntimeInternalId($oname1, $start_time, $dt_id, $oname2 = null)
{
$query = 'SELECT d.internal_id as internal_downtime_id
FROM downtimes d, hosts h ';
if (isset($oname2) && $oname2 != '') {
$query .= ', services s ';
}
$query .= 'WHERE d.host_id = h.host_id
AND d.start_time = ' . $this->dbb->escape($start_time) . "
AND d.comment_data = '[Downtime cycle #" . $dt_id . "]'
AND h.name = '" . $this->dbb->escape($oname1) . "' ";
if (isset($oname2) && $oname2 != '') {
$query .= ' AND h.host_id = s.host_id ';
$query .= " AND s.description = '" . $this->dbb->escape($oname2) . "' ";
}
try {
$res = $this->dbb->query($query);
} catch (PDOException $e) {
return false;
}
$row = $res->fetch();
return $row['internal_downtime_id'];
}
/**
* @param $startDelay
* @param $endDelay
* @param $daysOfWeek
* @param $tomorrow
*
* @return bool
*/
public function isWeeklyApproachingDowntime($startDelay, $endDelay, $daysOfWeek, $tomorrow)
{
$isApproaching = false;
$currentDayOfWeek = $tomorrow ? $endDelay->format('w') : $startDelay->format('w');
$daysOfWeek = explode(',', $daysOfWeek);
foreach ($daysOfWeek as $dayOfWeek) {
if ($dayOfWeek == 7) {
$dayOfWeek = 0;
}
if ($currentDayOfWeek == $dayOfWeek) {
$isApproaching = true;
}
}
return $isApproaching;
}
/**
* @param $startDelay
* @param $endDelay
* @param $daysOfMonth
* @param $tomorrow
*
* @return bool
*/
public function isMonthlyApproachingDowntime($startDelay, $endDelay, $daysOfMonth, $tomorrow)
{
$isApproaching = false;
$currentDayOfMonth = $tomorrow ? $endDelay->format('d') : $startDelay->format('d');
if (preg_match('/^0(\d)$/', $currentDayOfMonth, $matches)) {
$currentDayOfMonth = $matches[1];
}
$daysOfMonth = explode(',', $daysOfMonth);
foreach ($daysOfMonth as $dayOfMonth) {
if ($currentDayOfMonth == $dayOfMonth) {
$isApproaching = true;
}
}
return $isApproaching;
}
/**
* @param $startDelay
* @param $endDelay
* @param $dayOfWeek
* @param $cycle
* @param $tomorrow
*
* @throws Exception
* @return bool
*/
public function isSpecificDateDowntime($startDelay, $endDelay, $dayOfWeek, $cycle, $tomorrow)
{
$isApproaching = false;
if ($dayOfWeek == 7) {
$dayOfWeek = 0;
}
$daysOfWeekAssociation = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday', 7 => 'sunday'];
$dayOfWeek = $daysOfWeekAssociation[$dayOfWeek];
if ($tomorrow) {
$currentMonth = $endDelay->format('M');
$currentYear = $endDelay->format('Y');
$currentDay = $endDelay->format('Y-m-d');
} else {
$currentMonth = $startDelay->format('M');
$currentYear = $startDelay->format('Y');
$currentDay = $startDelay->format('Y-m-d');
}
$cycleDay = new DateTime($cycle . ' ' . $dayOfWeek . ' of ' . $currentMonth . ' ' . $currentYear);
$cycleDay = $cycleDay->format('Y-m-d');
if ($currentDay == $cycleDay) {
$isApproaching = true;
}
return $isApproaching;
}
/**
* @param $delay
*
* @throws Exception
* @return array
*/
public function getApproachingDowntimes($delay)
{
$approachingDowntimes = [];
$downtimes = $this->getForEnabledResources();
$gmtObj = new CentreonGMT();
foreach ($downtimes as $downtime) {
// Convert HH::mm::ss to HH:mm
$downtime['dtp_start_time'] = substr(
$downtime['dtp_start_time'],
0,
strrpos($downtime['dtp_start_time'], ':')
);
$downtime['dtp_end_time'] = substr($downtime['dtp_end_time'], 0, strrpos($downtime['dtp_end_time'], ':'));
$currentHostDate = $gmtObj->getHostCurrentDatetime($downtime['host_id']);
$timezone = $currentHostDate->getTimezone();
$startDelay = new DateTime('now', $timezone);
$endDelay = new DateTime('now +' . $delay . 'seconds', $timezone);
$tomorrow = $this->isTomorrow($downtime['dtp_start_time'], $startDelay, $delay);
$downtimeStartDate = new DateTime($downtime['dtp_start_time'], $timezone);
$downtimeEndDate = new DateTime($downtime['dtp_end_time'], $timezone);
if ($tomorrow) {
$downtimeStartDate->add(new DateInterval('P1D'));
$downtimeEndDate->add(new DateInterval('P1D'));
}
// Check if we jump an hour
$startTimestamp = $this->manageWinterToSummerTimestamp($downtimeStartDate, $downtime['dtp_start_time']);
$endTimestamp = $this->manageWinterToSummerTimestamp($downtimeEndDate, $downtime['dtp_end_time']);
if ($startTimestamp == $endTimestamp) {
continue;
}
// Check if HH:mm time is approaching
if (! $this->isApproachingTime($startTimestamp, $startDelay->getTimestamp(), $endDelay->getTimestamp())) {
continue;
}
// check backward of one hour
$startTimestamp = $this->manageSummerToWinterTimestamp($downtimeStartDate);
$approaching = false;
if (
preg_match('/^\d(,\d)*$/', $downtime['dtp_day_of_week'])
&& preg_match('/^(none)|(all)$/', $downtime['dtp_month_cycle'])
) {
$approaching = $this->isWeeklyApproachingDowntime(
$startDelay,
$endDelay,
$downtime['dtp_day_of_week'],
$tomorrow
);
} elseif (preg_match('/^\d+(,\d+)*$/', $downtime['dtp_day_of_month'])) {
$approaching = $this->isMonthlyApproachingDowntime(
$startDelay,
$endDelay,
$downtime['dtp_day_of_month'],
$tomorrow
);
} elseif (
preg_match('/^\d(,\d)*$/', $downtime['dtp_day_of_week'])
&& $downtime['dtp_month_cycle'] != 'none'
) {
$approaching = $this->isSpecificDateDowntime(
$startDelay,
$endDelay,
$downtime['dtp_day_of_week'],
$downtime['dtp_month_cycle'],
$tomorrow
);
}
if ($approaching) {
$approachingDowntimes[] = ['dt_id' => $downtime['dt_id'], 'dt_activate' => $downtime['dt_activate'], 'start_hour' => $downtime['dtp_start_time'], 'end_hour' => $downtime['dtp_end_time'], 'start_timestamp' => $startTimestamp, 'end_timestamp' => $endTimestamp, 'host_id' => $downtime['host_id'], 'host_name' => $downtime['host_name'], 'service_id' => $downtime['service_id'], 'service_description' => $downtime['service_description'], 'fixed' => $downtime['dtp_fixed'], 'duration' => $downtime['dtp_duration'], 'tomorrow' => $tomorrow];
}
}
return $approachingDowntimes;
}
/**
* @param $downtime
*
* @throws PDOException
* @return void
*/
public function insertCache($downtime): void
{
$query = 'INSERT INTO downtime_cache '
. '(downtime_id, start_timestamp, end_timestamp, '
. 'start_hour, end_hour, host_id, service_id) '
. 'VALUES ( '
. $downtime['dt_id'] . ', '
. $downtime['start_timestamp'] . ', '
. $downtime['end_timestamp'] . ', '
. '"' . $downtime['start_hour'] . '", '
. '"' . $downtime['end_hour'] . '", '
. $downtime['host_id'] . ', ';
$query .= ($downtime['service_id'] != '') ? $downtime['service_id'] . ' ' : 'NULL ';
$query .= ') ';
$res = $this->db->query($query);
}
/**
* @throws PDOException
* @return void
*/
public function purgeCache(): void
{
$query = 'DELETE FROM downtime_cache WHERE start_timestamp < ' . time();
$this->db->query($query);
}
/**
* @param $downtime
*
* @throws PDOException
* @return bool
*/
public function isScheduled($downtime)
{
$isScheduled = false;
$query = 'SELECT downtime_cache_id '
. 'FROM downtime_cache '
. 'WHERE downtime_id = ' . $downtime['dt_id'] . ' '
. 'AND start_timestamp = ' . $downtime['start_timestamp'] . ' '
. 'AND end_timestamp = ' . $downtime['end_timestamp'] . ' '
. 'AND host_id = ' . $downtime['host_id'] . ' ';
$query .= ($downtime['service_id'] != '')
? 'AND service_id = ' . $downtime['service_id'] . ' '
: 'AND service_id IS NULL';
$res = $this->db->query($query);
if ($res->rowCount()) {
$isScheduled = true;
}
return $isScheduled;
}
/**
* Send external command to nagios or centcore
*
* @param int $host_id The host id for command
* @param string $cmd The command to send
*
* @throws PDOException
* @return void The command return code
*/
public function setCommand($host_id, $cmd): void
{
static $cmdData = null;
static $remoteCommands = [];
if (is_null($cmdData)) {
$cmdData = [];
$query = "SELECT ns.id, host_host_id
FROM cfg_nagios cn, nagios_server ns, ns_host_relation nsh
WHERE cn.nagios_server_id = ns.id
AND nsh.nagios_server_id = ns.id
AND cn.nagios_activate = '1'
AND ns.ns_activate = '1'";
$res = $this->db->query($query);
while ($row = $res->fetch()) {
$cmdData[$row['host_host_id']] = $row['id'];
}
}
if (! isset($cmdData[$host_id])) {
return;
}
$this->remoteCommands[] = 'EXTERNALCMD:' . $cmdData[$host_id] . ':' . $cmd;
}
/**
* Send all commands
*
* @return void
*/
public function sendCommands(): void
{
$remoteCommands = implode(PHP_EOL, $this->remoteCommands);
if ($remoteCommands) {
file_put_contents($this->remoteCmdDir . '/' . time() . '-downtimes', $remoteCommands, FILE_APPEND);
}
}
/**
* @param $downtimeStartTime
* @param $now
* @param $delay
*
* @throws Exception
* @return bool
*/
private function isTomorrow($downtimeStartTime, $now, $delay)
{
$tomorrow = false;
// startDelay must be between midnight - delay and midnight - 1 second
$nowTimestamp = strtotime($now->format('H:i'));
$midnightMoins1SecondDate = new DateTime('midnight -1seconds');
$midnightMoins1SecondTimestamp = strtotime($midnightMoins1SecondDate->format('H:i:s'));
$midnightMoinsDelayDate = new DateTime('midnight -' . $delay . 'seconds');
$midnightMoinsDelayTimestamp = strtotime($midnightMoinsDelayDate->format('H:i'));
$downtimeStartTimeTimestamp = strtotime($downtimeStartTime);
// YYYY-MM-DD 00:00:00
$midnightDate = new DateTime('midnight');
// 00:00
$midnight = $midnightDate->format('H:i');
$midnightTimestamp = strtotime($midnight);
// YYYY-MM-DD 00:00:10 (for 600 seconds delay)
$midnightPlusDelayDate = new DateTime('midnight +' . $delay . 'seconds');
// 00:10 (for 600 seconds delay)
$midnightPlusDelay = $midnightPlusDelayDate->format('H:i');
$midnightPlusDelayTimestamp = strtotime($midnightPlusDelay);
if ($downtimeStartTimeTimestamp >= $midnightTimestamp
&& $downtimeStartTimeTimestamp <= $midnightPlusDelayTimestamp
&& $nowTimestamp <= $midnightMoins1SecondTimestamp
&& $nowTimestamp >= $midnightMoinsDelayTimestamp
) {
$tomorrow = true;
}
return $tomorrow;
}
/**
* @param $downtimeStart
* @param $delayStart
* @param $delayEnd
*
* @return bool
*/
private function isApproachingTime($downtimeStart, $delayStart, $delayEnd)
{
$approachingTime = false;
if ($downtimeStart >= $delayStart && $downtimeStart <= $delayEnd) {
$approachingTime = true;
}
return $approachingTime;
}
/**
* reset timestamp at beginning of hour if we jump forward
* example:
* - current date is 2021-03-28
* - $time is 02:30
* ==> return timestamp corresponding to 02:00 cause 02:30 does not exist (jump from 02:00 to 03:00)
*
* @param DateTime $datetime
* @param string $time time formatted as HH:mm
*
* @return int the calculated timestamp
*/
private function manageWinterToSummerTimestamp(DateTime $datetime, string $time): int
{
$hour = explode(':', $time)[0];
if ((int) $datetime->format('H') > (int) $hour) {
$datetime->setTime($hour, '00');
}
return $datetime->getTimestamp();
}
/**
* @param Datetime $dateTime
*
* @return int
*/
private function manageSummerToWinterTimestamp(DateTime $dateTime)
{
$datetimePlusOneHour = clone $dateTime;
$datetimePlusOneHour->sub(new DateInterval('PT1H'));
if ($datetimePlusOneHour->format('H:m') === $dateTime->format('H:m')) {
return $dateTime->getTimestamp() - 3600;
}
return $dateTime->getTimestamp();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonUUID.class.php | centreon/www/class/centreonUUID.class.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
*
*/
/**
* Class
*
* @class CentreonUUID
*/
class CentreonUUID
{
/** @var CentreonDB */
private $db;
/**
* CentreonUUID constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Get Centreon UUID
*
* @return string
*/
public function getUUID(): string
{
if ($uuid = $this->getUUIDFromDatabase()) {
return $uuid;
}
return $this->generateUUID();
}
/**
* Get Centreon UUID previously stored in database
*
* @throws PDOException
* @return false|string
*/
private function getUUIDFromDatabase(): bool|string
{
$query = 'SELECT value '
. 'FROM informations '
. "WHERE informations.key = 'uuid' ";
$result = $this->db->query($query);
if ($result !== false && $row = $result->fetch()) {
/** @var array<string, null|bool|int|string> $row */
return (string) $row['value'];
}
return false;
}
/**
* Generate UUID v4
*
* @throws CentreonDbException
* @return string
*/
private function generateUUID()
{
$uuid = sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
$query = "INSERT INTO informations VALUES ('uuid', ?) ";
$queryValues = [$uuid];
$stmt = $this->db->prepare($query);
$this->db->execute($stmt, $queryValues);
return $uuid;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonHost.class.php | centreon/www/class/centreonHost.class.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\LegacyContainer;
use CentreonLicense\ServiceProvider;
use Core\ActionLog\Domain\Model\ActionLog;
require_once __DIR__ . '/centreonInstance.class.php';
require_once __DIR__ . '/centreonService.class.php';
require_once __DIR__ . '/centreonCommand.class.php';
require_once __DIR__ . '/centreonLogAction.class.php';
/**
* Class
*
* @class CentreonHost
*/
class CentreonHost
{
/** @var CentreonDB */
protected $db;
/** @var CentreonInstance */
protected $instanceObj;
/** @var CentreonService */
protected $serviceObj;
/**
* Macros formatted by id
* ex:
* [
* 1 => [
* "macroName" => "KEY"
* "macroValue" => "value"
* "macroPassword" => "1"
* ],
* 2 => [
* "macroName" => "KEY_1"
* "macroValue" => "value_1"
* "macroPassword" => "1"
* "originalName" => "MACRO_1"
* ]
* ]
* @var array<int,array{
* macroName: string,
* macroValue: string,
* macroPassword: '0'|'1',
* originalName?: string
* }>
*/
private array $formattedMacros = [];
/**
* @param CentreonDB $db
* @throws PDOException
*/
public function __construct(CentreonDB $db)
{
$this->db = $db;
$this->instanceObj = CentreonInstance::getInstance($db);
$this->serviceObj = new CentreonService($db);
}
/**
* get all host templates saved in the DB
*
* @param bool $enable
* @param bool $template
* @param null|int $exclude - host id to exclude in returned result
*
* @throws Exception
* @return array
*/
public function getList($enable = false, $template = false, $exclude = null)
{
$hostType = 1;
if ($template) {
$hostType = 0;
}
$queryList = 'SELECT host_id, host_name '
. 'FROM host '
. 'WHERE host_register = :register ';
if ($enable) {
$queryList .= 'AND host_activate = "1" ';
}
if ($exclude !== null) {
$queryList .= 'AND host_id <> :exclude_id ';
}
$queryList .= 'ORDER BY host_name';
$stmt = $this->db->prepare($queryList);
$stmt->bindParam(':register', $hostType, PDO::PARAM_STR);
if ($exclude !== null) {
$stmt->bindParam(':exclude_id', $exclude, PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$listHost = [];
while ($row = $stmt->fetch()) {
$listHost[$row['host_id']] = htmlspecialchars($row['host_name'], ENT_QUOTES, 'UTF-8');
}
return $listHost;
}
/**
* get the template currently saved for this host
*
* @param string|int $hostId
*
* @throws PDOException
* @return array
*/
public function getSavedTpl($hostId): array
{
$mTp = [];
$dbResult = $this->db->prepare(
'SELECT host_tpl_id, host.host_name
FROM host_template_relation, host
WHERE host_host_id = :hostId
AND host_tpl_id = host.host_id'
);
$dbResult->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$dbResult->execute();
while ($multiTp = $dbResult->fetch()) {
$mTp[$multiTp['host_tpl_id']] = htmlspecialchars($multiTp['host_name'], ENT_QUOTES, 'UTF-8');
}
return $mTp;
}
/**
* get list of inherited templates from plugin pack
*
* @throws PDOException
* @throws Exception
* @return array
*/
public function getLimitedList(): array
{
$freePp = ['applications-databases-mysql', 'applications-monitoring-centreon-central', 'applications-monitoring-centreon-database', 'applications-monitoring-centreon-poller', 'base-generic', 'hardware-printers-standard-rfc3805-snmp', 'hardware-ups-standard-rfc1628-snmp', 'network-cisco-standard-snmp', 'operatingsystems-linux-snmp', 'operatingsystems-windows-snmp'];
$ppList = [];
$dbResult = $this->db->query('SELECT `name` FROM modules_informations WHERE `name` = "centreon-pp-manager"');
if (empty($dbResult->fetch()) || $this->isAllowed() === true) {
return $ppList;
}
$dbResult = $this->db->query(
'SELECT ph.host_id
FROM mod_ppm_pluginpack_host ph, mod_ppm_pluginpack pp
WHERE ph.pluginpack_id = pp.pluginpack_id
AND pp.slug NOT IN ("' . implode('","', $freePp) . '")'
);
while ($row = $dbResult->fetch()) {
$this->getHostChain($row['host_id'], $ppList);
}
asort($ppList);
return $ppList;
}
/**
* @param $hostId
* @param bool $withHg
*
* @throws PDOException
* @throws Exception
* @return array
*/
public function getHostChild($hostId, $withHg = false)
{
if (! is_numeric($hostId)) {
return [];
}
$queryGetChildren = 'SELECT h.host_id, h.host_name '
. 'FROM host h, host_hostparent_relation hp '
. 'WHERE hp.host_host_id = h.host_id '
. 'AND h.host_register = "1" '
. 'AND h.host_activate = "1" '
. 'AND hp.host_parent_hp_id = :hostId';
$stmt = $this->db->prepare($queryGetChildren);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$listHostChildren = [];
while ($row = $stmt->fetch()) {
$listHostChildren[$row['host_id']] = $row['host_alias'];
}
return $listHostChildren;
}
/**
* @param bool $withHg
* @throws Exception
* @return array
*/
public function getHostRelationTree($withHg = false)
{
$queryGetRelationTree = 'SELECT hp.host_parent_hp_id, h.host_id, h.host_name '
. 'FROM host h, host_hostparent_relation hp '
. 'WHERE hp.host_host_id = h.host_id '
. 'AND h.host_register = "1" '
. 'AND h.host_activate = "1"';
$dbResult = $this->db->query($queryGetRelationTree);
if (! $dbResult) {
throw new Exception('An error occured');
}
$listHostRelactionTree = [];
while ($row = $dbResult->fetch()) {
if (! isset($listHostRelactionTree[$row['host_parent_hp_id']])) {
$listHostRelactionTree[$row['host_parent_hp_id']] = [];
}
$listHostRelactionTree[$row['host_parent_hp_id']][$row['host_id']] = $row['host_alias'];
}
return $listHostRelactionTree;
}
/**
* @param $hostId
* @param bool $withHg
* @param bool $withDisabledServices
* @throws Exception
* @return array
*/
public function getServices($hostId, $withHg = false, $withDisabledServices = false)
{
// Get service for a host
$queryGetServices = 'SELECT s.service_id, s.service_description '
. 'FROM service s, host_service_relation hsr, host h '
. 'WHERE s.service_id = hsr.service_service_id '
. 'AND s.service_register = "1" '
. ($withDisabledServices ? '' : 'AND s.service_activate = "1" ')
. 'AND h.host_id = hsr.host_host_id '
. 'AND h.host_register = "1" '
. 'AND h.host_activate = "1" '
. 'AND hsr.host_host_id = :hostId';
$stmt = $this->db->prepare($queryGetServices);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$listServices = [];
while ($row = $stmt->fetch()) {
$listServices[$row['service_id']] = $row['service_description'];
}
// With hostgroup
if ($withHg) {
$queryGetServicesWithHg = 'SELECT s.service_id, s.service_description '
. 'FROM service s, host_service_relation hsr, hostgroup_relation hgr, host h, hostgroup hg '
. 'WHERE s.service_id = hsr.service_service_id '
. 'AND s.service_register = "1" '
. ($withDisabledServices ? '' : 'AND s.service_activate = "1" ')
. 'AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id '
. 'AND h.host_id = hgr.host_host_id '
. 'AND h.host_register = "1" '
. 'AND h.host_activate = "1" '
. 'AND hg.hg_id = hgr.hostgroup_hg_id '
. 'AND hg.hg_activate = "1" '
. 'AND hgr.host_host_id = :hostId';
$stmt = $this->db->prepare($queryGetServicesWithHg);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$listServices[$row['service_id']] = $row['service_description'];
}
}
return $listServices;
}
/**
* Get the relation tree for host / service
*
* @param bool $withHg With Hostgroup
*
* @throws PDOException
* @throws Exception
* @return array
*/
public function getHostServiceRelationTree($withHg = false)
{
// Get service for a host
$query = 'SELECT hsr.host_host_id, s.service_id, s.service_description '
. 'FROM service s, host_service_relation hsr, host h '
. 'WHERE s.service_id = hsr.service_service_id '
. 'AND s.service_register = "1" '
. 'AND s.service_activate = "1" '
. 'AND h.host_id = hsr.host_host_id '
. 'AND h.host_register = "1" '
. 'AND h.host_activate = "1" ';
if ($withHg) {
$query .= 'UNION '
. 'SELECT hgr.host_host_id, s.service_id, s.service_description '
. 'FROM service s, host_service_relation hsr, host h, hostgroup_relation hgr '
. 'WHERE s.service_id = hsr.service_service_id '
. 'AND s.service_register = "1" '
. 'AND s.service_activate = "1" '
. 'AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id '
. 'AND hgr.host_host_id = h.host_id '
. 'AND h.host_register = "1" '
. 'AND h.host_activate = "1"';
}
$res = $this->db->query($query);
if (! $res) {
throw new Exception('An error occured');
}
$listServices = [];
while ($row = $res->fetch()) {
if (! isset($listServices[$row['host_host_id']])) {
$listServices[$row['host_host_id']] = [];
}
$listServices[$row['host_host_id']][$row['service_id']] = $row['service_description'];
}
return $listServices;
}
/**
* Method that returns a hostname from host_id
*
* @param $hostId
*
* @throws PDOException
* @return string
*/
public function getHostName($hostId)
{
if (! isset($hostId) || ! $hostId) {
return null;
}
$statement = $this->db->prepare('SELECT host_name FROM host WHERE host_id = :host_id');
$statement->bindValue(':host_id', (int) $hostId, PDO::PARAM_INT);
$statement->execute();
if ($hostName = $statement->fetchColumn()) {
return $hostName;
}
return null;
}
/**
* @param $hostId
* @throws Exception
* @return mixed
*/
public function getOneHostName($hostId)
{
if (isset($hostId) && is_numeric($hostId)) {
$query = 'SELECT host_id, host_name FROM host where host_id = ?';
$stmt = $this->db->prepare($query);
$dbResult = $stmt->execute([(int) $hostId]);
if (! $dbResult) {
throw new Exception('An error occured');
}
$row = $stmt->fetch();
return $row['host_name'];
}
return '';
}
/**
* @param int[] $hostId
*
* @throws PDOException
* @return array $hosts [['id' => integer, 'name' => string],...]
*/
public function getHostsNames($hostId = []): array
{
$hosts = [];
if (! empty($hostId)) {
/*
* Checking here that the array provided as parameter
* is exclusively made of integers (host ids)
*/
$filteredHostIds = $this->filteredArrayId($hostId);
$hostParams = [];
if ($filteredHostIds !== []) {
/*
* Building the hostParams hash table in order to correctly
* bind ids as ints for the request.
*/
foreach ($filteredHostIds as $index => $filteredHostId) {
$hostParams[':hostId' . $index] = $filteredHostId;
}
$stmt = $this->db->prepare('SELECT host_id, host_name '
. 'FROM host where host_id IN ( ' . implode(',', array_keys($hostParams)) . ' )');
foreach ($hostParams as $index => $value) {
$stmt->bindValue($index, $value, PDO::PARAM_INT);
}
$dbResult = $stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hosts[] = [
'id' => $row['host_id'],
'name' => $row['host_name'],
];
}
}
}
return $hosts;
}
/**
* @param $hostId
*
* @throws PDOException
* @return int
*/
public function getHostCommandId($hostId)
{
if (isset($hostId) && is_numeric($hostId)) {
$query = 'SELECT host_id, command_command_id FROM host where host_id = :hostId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$row = $stmt->fetch();
return $row['command_command_id'];
}
return 0;
}
/**
* @param $hostId
* @throws Exception
* @return mixed|null
*/
public function getHostAlias($hostId)
{
static $aliasTab = [];
if (! isset($hostId) || ! $hostId) {
return null;
}
if (! isset($aliasTab[$hostId])) {
$query = 'SELECT host_alias FROM host WHERE host_id = :hostId LIMIT 1';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$row = $stmt->fetch();
$aliasTab[$hostId] = $row['host_alias'];
}
}
return $aliasTab[$hostId] ?? null;
}
/**
* @param $hostId
* @throws Exception
* @return mixed|null
*/
public function getHostAddress($hostId)
{
static $addrTab = [];
if (! isset($hostId) || ! $hostId) {
return null;
}
if (! isset($addrTab[$hostId])) {
$query = 'SELECT host_address FROM host WHERE host_id = :hostId LIMIT 1';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$row = $stmt->fetch();
$addrTab[$hostId] = $row['host_address'];
}
}
return $addrTab[$hostId] ?? null;
}
/**
* @param $address
* @param array $params
* @throws Exception
* @return array
*/
public function getHostByAddress($address, $params = [])
{
$paramsList = '';
$hostList = [];
if (count($params) > 0) {
foreach ($params as $k => $v) {
$paramsList .= "`{$v}`,";
}
$paramsList = rtrim($paramsList, ',');
} else {
$paramsList .= '*';
}
$query = 'SELECT ' . $paramsList . ' FROM host WHERE host_address = :address';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':address', $address, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$hostList[] = $row;
}
return $hostList;
}
/**
* @param $hostName
* @throws Exception
* @return mixed|null
*/
public function getHostId($hostName)
{
static $ids = [];
if (! isset($hostName) || ! $hostName) {
return null;
}
if (! isset($ids[$hostName])) {
$query = 'SELECT host_id '
. 'FROM host '
. 'WHERE host_name = :hostName '
. 'LIMIT 1';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':hostName', $hostName, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$row = $stmt->fetch();
$ids[$hostName] = $row['host_id'];
}
}
return $ids[$hostName] ?? null;
}
/**
* @param $hostName
* @param null|int $pollerId
* @throws Exception
* @return mixed
*/
public function checkIllegalChar($hostName, $pollerId = null)
{
if ($pollerId) {
$query = 'SELECT illegal_object_name_chars FROM cfg_nagios WHERE nagios_server_id = :pollerId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':pollerId', $pollerId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
} else {
$stmt = $this->db->query('SELECT illegal_object_name_chars FROM cfg_nagios ');
}
while ($data = $stmt->fetch()) {
$hostName = str_replace(str_split($data['illegal_object_name_chars']), '', $hostName);
}
$stmt->closeCursor();
return $hostName;
}
/**
* Returns the poller id of the host linked to hostId provided
* @param int $hostId
* @throws Exception
* @return int|null $pollerId
*/
public function getHostPollerId(int $hostId): ?int
{
$pollerId = null;
if ($hostId) {
$query = 'SELECT nagios_server_id FROM ns_host_relation WHERE host_host_id = :hostId LIMIT 1';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if ($stmt->rowCount()) {
$row = $stmt->fetch();
$pollerId = (int) $row['nagios_server_id'];
} else {
$hostName = $this->getHostName($hostId);
if (preg_match('/^_Module_Meta/', $hostName)) {
$query = 'SELECT id '
. 'FROM nagios_server '
. 'WHERE localhost = "1" '
. 'LIMIT 1 ';
$res = $this->db->query($query);
if ($res->rowCount()) {
$row = $res->fetch();
$pollerId = (int) $row['id'];
}
}
}
}
return $pollerId;
}
/**
* @param $hostParam
* @param $string
* @param null $antiLoop
* @throws Exception
* @return mixed
*/
public function replaceMacroInString($hostParam, $string, $antiLoop = null)
{
if (! preg_match('/\$[0-9a-zA-Z_-]+\$/', $string ?? '')) {
return $string;
}
if (is_numeric($hostParam)) {
$query = 'SELECT host_id, ns.nagios_server_id, host_register, host_address, host_name, host_alias
FROM host
LEFT JOIN ns_host_relation ns
ON ns.host_host_id = host.host_id
WHERE host_id = :hostId
LIMIT 1';
$stmt = $this->db->prepare($query);
$stmt->bindValue(':hostId', (int) $hostParam, PDO::PARAM_INT);
} elseif (is_string($hostParam)) {
$query = 'SELECT host_id, ns.nagios_server_id, host_register, host_address, host_name, host_alias
FROM host
LEFT JOIN ns_host_relation ns
ON ns.host_host_id = host.host_id
WHERE host_name = :hostName
LIMIT 1';
$stmt = $this->db->prepare($query);
$stmt->bindValue(':hostName', $hostParam);
} else {
return $string;
}
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
if (! $stmt->rowCount()) {
return $string;
}
$row = $stmt->fetch();
$hostId = (int) $row['host_id'];
// replace if not template
if ($row['host_register'] == 1) {
if (str_contains($string, '$HOSTADDRESS$')) {
$string = str_replace('$HOSTADDRESS$', $row['host_address'], $string);
}
if (str_contains($string, '$HOSTNAME$')) {
$string = str_replace('$HOSTNAME$', $row['host_name'], $string);
}
if (str_contains($string, '$HOSTALIAS$')) {
$string = str_replace('$HOSTALIAS$', $row['host_alias'], $string);
}
if (str_contains($string, '$INSTANCENAME$')) {
$pollerId = $row['nagios_server_id'] ?? $this->getHostPollerId($hostId);
$string = str_replace(
'$INSTANCENAME$',
$this->instanceObj->getParam((int) $pollerId, 'name'),
$string
);
}
if (str_contains($string, '$INSTANCEADDRESS$')) {
if (! isset($pollerId)) {
$pollerId = $row['nagios_server_id'] ?? $this->getHostPollerId($hostId);
}
$string = str_replace(
'$INSTANCEADDRESS$',
$this->instanceObj->getParam($pollerId, 'ns_ip_address'),
$string
);
}
}
unset($row);
$matches = [];
$pattern = '|(\$_HOST[0-9a-zA-Z\_\-]+\$)|';
preg_match_all($pattern, $string, $matches);
$i = 0;
while (isset($matches[1][$i])) {
$query = 'SELECT host_macro_value '
. 'FROM on_demand_macro_host '
. 'WHERE host_host_id = :hostId '
. 'AND host_macro_name LIKE :macro';
$stmt = $this->db->prepare($query);
$stmt->bindValue(':hostId', $hostId, PDO::PARAM_INT);
$stmt->bindParam(':macro', $matches[1][$i], PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$string = str_replace($matches[1][$i], $row['host_macro_value'], $string);
}
$i++;
}
if ($i) {
$query2 = 'SELECT host_tpl_id FROM host_template_relation WHERE host_host_id = :host ORDER BY `order`';
$stmt2 = $this->db->prepare($query2);
$stmt2->bindValue(':host', $hostId, PDO::PARAM_INT);
$dbResult = $stmt2->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row2 = $stmt2->fetch()) {
if (! isset($antiLoop) || ! $antiLoop) {
$string = $this->replaceMacroInString($row2['host_tpl_id'], $string, $row2['host_tpl_id']);
} elseif ($row2['host_tpl_id'] != $antiLoop) {
$string = $this->replaceMacroInString($row2['host_tpl_id'], $string);
}
}
}
return $string;
}
/**
* @param $hostId
* @param array $macroInput
* @param array $macroValue
* @param array $macroPassword
* @param array $macroDescription
* @param bool $isMassiveChange
* @param bool $cmdId
* @throws Exception
*/
public function insertMacro(
$hostId,
$macroInput = [],
$macroValue = [],
$macroPassword = [],
$macroDescription = [],
$isMassiveChange = false,
$cmdId = false,
): void {
if ($isMassiveChange === false) {
$query = 'DELETE FROM on_demand_macro_host WHERE host_host_id = :hostId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
} else {
$macroList = '';
$queryValues = [];
$queryValues[] = $hostId;
foreach ($macroInput as $v) {
$macroList .= ' ?,';
$queryValues[] = (string) '$_HOST' . strtoupper($v) . '$';
}
if ($macroList) {
$macroList = rtrim($macroList, ',');
$query = 'DELETE FROM on_demand_macro_host '
. 'WHERE host_host_id = ? '
. 'AND host_macro_name IN (' . $macroList . ')';
$stmt = $this->db->prepare($query);
$dbResult = $stmt->execute($queryValues);
if (! $dbResult) {
throw new Exception('An error occured');
}
}
}
$stored = [];
$cnt = 0;
$macros = $macroInput;
$macrovalues = $macroValue;
$this->hasMacroFromHostChanged($hostId, $macros, $macrovalues, $macroPassword, $cmdId);
foreach ($macros as $key => $value) {
if ($value != '' && ! isset($stored[strtolower($value)])) {
$queryValues = [];
$query = 'INSERT INTO on_demand_macro_host (`host_macro_name`, `host_macro_value`, `is_password`, '
. '`description`, `host_host_id`, `macro_order`) '
. 'VALUES (?, ?, ';
$queryValues[] = (string) '$_HOST' . strtoupper($value) . '$';
$queryValues[] = (string) $macrovalues[$key];
if (isset($macroPassword[$key])) {
$query .= '?, ';
$queryValues[] = (int) 1;
} else {
$query .= 'NULL, ';
}
$query .= '?, ?, ?)';
$queryValues[] = (string) $macroDescription[$key];
$queryValues[] = (int) $hostId;
$queryValues[] = (int) $cnt;
$stmt = $this->db->prepare($query);
$dbResult = $stmt->execute($queryValues);
if (! $dbResult) {
throw new Exception('An error occured');
}
$cnt++;
$stored[strtolower($value)] = true;
// Format macros to improve handling on form submit.
$dbResult = $this->db->query('SELECT MAX(host_macro_id) FROM on_demand_macro_host');
$macroId = $dbResult->fetch();
$this->formattedMacros[(int) $macroId['MAX(host_macro_id)']] = [
'macroName' => '_HOST' . strtoupper($value),
'macroValue' => $macrovalues[$key],
'macroPassword' => $macroPassword[$key] ?? '0',
];
if (isset($_REQUEST['macroOriginalName_' . $key])) {
$this->formattedMacros[(int) $macroId['MAX(host_macro_id)']]['originalName']
= '_HOST' . $_REQUEST['macroOriginalName_' . $key];
}
}
}
}
/**
* @param null $hostId
* @param null $template
* @throws Exception
* @return array
*/
public function getCustomMacroInDb($hostId = null, $template = null)
{
$arr = [];
$i = 0;
if ($hostId) {
$sSql = 'SELECT host_macro_id, host_macro_name, host_macro_value, is_password, description '
. 'FROM on_demand_macro_host '
. 'WHERE host_host_id = :hostId '
. 'ORDER BY macro_order ASC';
$stmt = $this->db->prepare($sSql);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
if (preg_match('/\$_HOST(.*)\$$/', $row['host_macro_name'], $matches)) {
$arr[$i]['macroId_#index#'] = $row['host_macro_id'];
$arr[$i]['macroInput_#index#'] = $matches[1];
$arr[$i]['macroValue_#index#'] = $row['host_macro_value'];
$arr[$i]['macroPassword_#index#'] = $row['is_password'] ? 1 : null;
$arr[$i]['macroDescription_#index#'] = $row['description'];
$arr[$i]['macroDescription'] = $row['description'];
if (! is_null($template)) {
$arr[$i]['macroTpl_#index#'] = 'Host template : ' . $template['host_name'];
}
$i++;
}
}
}
return $arr;
}
/**
* @param null $hostId
* @param bool $realKeys
* @throws Exception
* @return array
*/
public function getCustomMacro($hostId = null, $realKeys = false)
{
$arr = [];
$i = 0;
if (! isset($_REQUEST['macroInput']) && $hostId) {
$sSql = 'SELECT host_macro_id, host_macro_name, host_macro_value, is_password, description '
. 'FROM on_demand_macro_host '
. 'WHERE host_host_id = :hostId '
. 'ORDER BY macro_order ASC';
$stmt = $this->db->prepare($sSql);
$stmt->bindParam(':hostId', $hostId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
if (preg_match('/\$_HOST(.*)\$$/', $row['host_macro_name'], $matches)) {
$arr[$i]['macroId_#index#'] = $row['host_macro_id'];
$arr[$i]['macroInput_#index#'] = $matches[1];
$arr[$i]['macroValue_#index#'] = $row['host_macro_value'];
$arr[$i]['macroPassword_#index#'] = $row['is_password'] ? 1 : null;
$arr[$i]['macroDescription_#index#'] = $row['description'];
$arr[$i]['macroDescription'] = $row['description'];
$i++;
}
}
} elseif (isset($_REQUEST['macroInput'])) {
foreach ($_REQUEST['macroInput'] as $key => $val) {
$index = $i;
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonConfigEngine.php | centreon/www/class/centreonConfigEngine.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
*
*/
/**
* Class
*
* @class CentreonConfigEngine
*/
class CentreonConfigEngine
{
/** @var CentreonDB */
protected $db;
/**
* CentreonConfigEngine constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Insert one or multiple broker directives
*
* @param int $serverId | id of monitoring server
* @param array $directives | event broker directives
*
* @throws PDOException
* @return void
*/
public function insertBrokerDirectives($serverId, $directives = []): void
{
$this->db->query('DELETE FROM cfg_nagios_broker_module
WHERE cfg_nagios_id = ' . $this->db->escape($serverId));
foreach ($directives as $value) {
if ($value != '') {
$this->db->query("INSERT INTO cfg_nagios_broker_module (`broker_module`, `cfg_nagios_id`)
VALUES ('" . $this->db->escape($value) . "', " . $this->db->escape($serverId) . ')');
}
}
}
/**
* Used by form only
*
* @param null $serverId
*
* @throws PDOException
* @return array
*/
public function getBrokerDirectives($serverId = null)
{
$arr = [];
$i = 0;
if (! isset($_REQUEST['in_broker']) && $serverId) {
$res = $this->db->query('SELECT broker_module
FROM cfg_nagios_broker_module
WHERE cfg_nagios_id = ' . $this->db->escape($serverId));
while ($row = $res->fetchRow()) {
$arr[$i]['in_broker_#index#'] = $row['broker_module'];
$i++;
}
} elseif (isset($_REQUEST['in_broker'])) {
foreach ($_REQUEST['in_broker'] as $val) {
$arr[$i]['in_broker_#index#'] = $val;
$i++;
}
}
return $arr;
}
/**
* @param $engineId
*
* @throws PDOException
* @return mixed|null
*/
public function getTimezone($engineId = null)
{
$timezone = null;
if (is_null($engineId) || empty($engineId)) {
return $timezone;
}
$query = 'SELECT timezone FROM ('
. 'SELECT timezone_name as timezone '
. 'FROM cfg_nagios, timezone '
. 'WHERE nagios_id = ' . $this->db->escape($engineId) . ' '
. 'AND use_timezone = timezone_id '
. 'UNION '
. 'SELECT timezone_name as timezone '
. 'FROM options, timezone '
. "WHERE options.key = 'gmt' "
. 'AND options.value = timezone_id '
. ') as t LIMIT 1';
$result = $this->db->query($query);
if ($row = $result->fetchRow()) {
$timezone = $row['timezone'];
}
return $timezone;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonLang.class.php | centreon/www/class/centreonLang.class.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
*
*/
/**
* Class
*
* @class CentreonLang
*/
class CentreonLang
{
/** @var string */
protected $charset = 'UTF-8';
/** @var string */
protected $lang;
/** @var string */
protected $path;
/** @var array */
protected $charsetList;
/**
* CentreonLang constructor
*
* @param string $centreon_path
* @param Centreon $centreon
*/
public function __construct($centreon_path, $centreon = null)
{
if (! is_null($centreon) && isset($centreon->user->charset)) {
$this->charset = $centreon->user->charset;
}
$this->lang = $this->getBrowserDefaultLanguage() . '.' . $this->charset;
if (! is_null($centreon) && isset($centreon->user->lang)) {
if ($centreon->user->lang !== 'browser') {
$this->lang = $centreon->user->lang;
}
}
$this->path = $centreon_path;
$this->setCharsetList();
}
/**
* Binds lang to the current Centreon page
*
* @param mixed $domain
* @param mixed $path
* @return void
*/
public function bindLang($domain = 'messages', $path = 'www/locale/'): void
{
putenv("LANG={$this->lang}");
setlocale(LC_ALL, $this->lang);
bindtextdomain($domain, $this->path . $path);
bind_textdomain_codeset($domain, $this->charset);
textdomain('messages');
}
/**
* Lang setter
*
* @param string $newLang
* @return void
*/
public function setLang($newLang): void
{
$this->lang = $newLang;
}
/**
* Returns lang that is being used
*
* @return string
*/
public function getLang()
{
return $this->lang;
}
/**
* Charset Setter
*
* @param string $newCharset
* @return void
*/
public function setCharset($newCharset): void
{
$this->charset = $newCharset;
}
/**
* Returns charset that is being used
*
* @return string
*/
public function getCharset()
{
return $this->charset;
}
/**
* Returns an array with a list of charsets
*
* @return array
*/
public function getCharsetList()
{
return $this->charsetList;
}
/**
* @return int|string|null
*/
private function parseHttpAcceptHeader()
{
$langs = [];
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
// break up string into pieces (languages and q factors)
preg_match_all(
'/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i',
$_SERVER['HTTP_ACCEPT_LANGUAGE'],
$lang_parse
);
if ($lang_parse[1] !== []) {
// create a list like "en" => 0.8
$langs = array_combine($lang_parse[1], $lang_parse[4]);
// set default to 1 for any without q factor
foreach ($langs as $lang => $val) {
if ($val === '') {
$langs[$lang] = 1;
}
}
// sort list based on value
arsort($langs, SORT_NUMERIC);
}
}
$languageLocales = array_keys($langs);
$current = array_shift($languageLocales);
$favoriteLanguage = $current;
return $favoriteLanguage;
}
/**
* Used to get the language set in the browser
*
* @return string
*/
private function getBrowserDefaultLanguage()
{
$currentLocale = '';
if (version_compare(PHP_VERSION, '5.2.0') >= 0 && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$browserLocale = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$currentLocale .= Locale::acceptFromHttp($browserLocale);
} else {
$currentLocale .= $this->parseHttpAcceptHeader();
}
return $this->getFullLocale($currentLocale);
}
/**
* Used to convert the browser language's from a short string to a string
*
* @param string $shortLocale
* @return string $fullLocale
*/
private function getFullLocale($shortLocale)
{
$fullLocale = '';
$as = ['fr' => 'fr_FR', 'fr_FR' => 'fr_FR', 'en' => 'en_US', 'en_US' => 'en_US'];
if (isset($as[$shortLocale])) {
$fullLocale .= $as[$shortLocale];
} else {
$fullLocale = 'en_US';
}
return $fullLocale;
}
/**
* Sets list of charsets
*
* @return void
*/
private function setCharsetList(): void
{
$this->charsetList = ['ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9', 'UTF-80', 'UTF-83', 'UTF-84', 'UTF-85', 'UTF-86', 'ISO-2022-JP', 'ISO-2022-KR', 'ISO-2022-CN', 'WINDOWS-1251', 'CP866', 'KOI8', 'KOI8-E', 'KOI8-R', 'KOI8-U', 'KOI8-RU', 'ISO-10646-UCS-2', 'ISO-10646-UCS-4', 'UTF-7', 'UTF-8', 'UTF-16', 'UTF-16BE', 'UTF-16LE', 'UTF-32', 'UTF-32BE', 'UTF-32LE', 'EUC-CN', 'EUC-GB', 'EUC-JP', 'EUC-KR', 'EUC-TW', 'GB2312', 'ISO-10646-UCS-2', 'ISO-10646-UCS-4', 'SHIFT_JIS'];
sort($this->charsetList);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonXML.class.php | centreon/www/class/centreonXML.class.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
*
*/
/**
* Class
*
* @class CentreonXML
* @description Class that is used for writing XML in utf_8 only!
*/
class CentreonXML
{
/** @var XMLWriter */
public $buffer;
/**
* CentreonXML constructor
*
* @param bool $indent
*/
public function __construct($indent = false)
{
$this->buffer = new XMLWriter();
$this->buffer->openMemory();
if ($indent) {
$this->buffer->setIndent($indent);
}
$this->buffer->startDocument('1.0', 'UTF-8');
}
/**
* Starts an element that contains other elements
*
* @param string $element_tag
*
* @return void
*/
public function startElement($element_tag): void
{
$this->buffer->startElement($element_tag);
}
/**
* Ends an element (closes tag)
*
* @return void
*/
public function endElement(): void
{
$this->buffer->endElement();
}
/**
* Simply puts text
*
* @param string $txt
* @param bool $cdata
* @param int $encode
*
* @return void
*/
public function text($txt, $cdata = true, $encode = 0): void
{
$txt = $this->cleanStr($txt);
$txt = html_entity_decode($txt);
if ($encode || ! $this->is_utf8($txt)) {
$this->buffer->writeCData(mb_convert_encoding($txt, 'UTF-8', 'ISO-8859-1'));
} elseif ($cdata) {
$this->buffer->writeCData($txt);
} else {
$this->buffer->text($txt);
}
}
/**
* Creates a tag and writes data
*
* @param string $element_tag
* @param string $element_value
* @param int $encode
*
* @return void
*/
public function writeElement($element_tag, $element_value, $encode = 0): void
{
$this->startElement($element_tag);
$element_value = $this->cleanStr($element_value);
$element_value = html_entity_decode($element_value);
if ($encode || ! $this->is_utf8($element_value)) {
$this->buffer->writeCData(mb_convert_encoding($element_value, 'UTF-8', 'ISO-8859-1'));
} else {
$this->buffer->writeCData($element_value);
}
$this->endElement();
}
/**
* Writes attribute
*
* @param string $att_name
* @param string $att_value
* @param bool $encode
*
* @return void
*/
public function writeAttribute($att_name, $att_value, $encode = false): void
{
$att_value = $this->cleanStr($att_value);
if ($encode) {
$this->buffer->writeAttribute($att_name, mb_convert_encoding(html_entity_decode($att_value), 'UTF-8', 'ISO-8859-1'));
} else {
$this->buffer->writeAttribute($att_name, html_entity_decode($att_value));
}
}
/**
* Output the whole XML buffer
*
* @return void
*/
public function output(): void
{
$this->buffer->endDocument();
echo $this->buffer->outputMemory(true);
}
/**
* @param string|null $filename
*
* @throws RuntimeException
* @return void
*/
public function outputFile($filename = null): void
{
$this->buffer->endDocument();
$content = $this->buffer->outputMemory(true);
if ($handle = fopen($filename, 'w')) {
if (strcmp($content, '') && ! fwrite($handle, $content)) {
throw new RuntimeException('Cannot write to file "' . $filename . '"');
}
} else {
echo "Can't open file: {$filename}";
}
}
/**
* Clean string
*
* @param string $str
*
* @return string
*/
protected function cleanStr($str)
{
return preg_replace('/[\x00-\x09\x0B-\x0C\x0E-\x1F\x0D]/', '', $str);
}
/**
* Checks if string is encoded
*
* @param string $string
*
* @return int
*/
protected function is_utf8($string)
{
if (mb_detect_encoding($string, 'UTF-8', true) == 'UTF-8') {
return 1;
}
return 0;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonPerformanceService.class.php | centreon/www/class/centreonPerformanceService.class.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
*
*/
/**
* Class
*
* @class CentreonPerformanceService
* @description Description of centreonPerformanceService
*/
class CentreonPerformanceService
{
/** @var CentreonDB */
protected $dbMon;
/** @var CentreonACL */
protected $aclObj;
/**
* CentreonPerformanceService constructor
*
* @param $dbMon
* @param $aclObj
*/
public function __construct($dbMon, $aclObj)
{
$this->dbMon = $dbMon;
$this->aclObj = $aclObj;
}
/**
* @param array $filters
*
* @throws PDOException
* @throws RestBadRequestException
* @return array
*/
public function getList($filters = [])
{
$additionnalTables = '';
$additionnalCondition = '';
$serviceDescription = isset($filters['service']) === false ? '' : $filters['service'];
if (isset($filters['page_limit'], $filters['page'])) {
$limit = ($filters['page'] - 1) * $filters['page_limit'];
$range = 'LIMIT ' . $limit . ',' . $filters['page_limit'];
} else {
$range = '';
}
if (isset($filters['hostgroup'])) {
$additionnalTables .= ',hosts_hostgroups hg ';
$additionnalCondition .= 'AND (hg.host_id = i.host_id AND hg.hostgroup_id IN ('
. implode(',', $filters['hostgroup']) . ')) ';
}
if (isset($filters['servicegroup'])) {
$additionnalTables .= ',services_servicegroups sg ';
$additionnalCondition .= 'AND (sg.host_id = i.host_id AND sg.service_id = i.service_id '
. 'AND sg.servicegroup_id IN (' . implode(',', $filters['servicegroup']) . ')) ';
}
if (isset($filters['host'])) {
$additionnalCondition .= 'AND i.host_id IN (' . implode(',', $filters['host']) . ') ';
}
$virtualServicesCondition = $this->getVirtualServicesCondition($additionnalCondition);
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT fullname, host_id, service_id, index_id '
. 'FROM ( '
. '( SELECT CONCAT(i.host_name, " - ", i.service_description) as fullname, '
. 'i.host_id, i.service_id, m.index_id '
. 'FROM index_data i, metrics m ' . (! $this->aclObj->admin ? ', centreon_acl acl ' : '')
. 'WHERE i.id = m.index_id '
. 'AND i.host_name NOT LIKE "\_Module\_%" '
. (! $this->aclObj->admin
? ' AND acl.host_id = i.host_id AND acl.service_id = i.service_id AND acl.group_id IN ('
. $this->aclObj->getAccessGroupsString() . ') ' : '')
. $additionnalCondition
. ') '
. $virtualServicesCondition
. ') as t_union '
. 'WHERE fullname LIKE "%' . $serviceDescription . '%" '
. 'GROUP BY host_id, service_id '
. 'ORDER BY fullname '
. $range;
$DBRESULT = $this->dbMon->query($query);
$serviceList = [];
while ($data = $DBRESULT->fetchRow()) {
$serviceCompleteName = $data['fullname'];
$serviceCompleteId = $data['host_id'] . '-' . $data['service_id'];
$serviceList[] = ['id' => $serviceCompleteId, 'text' => $serviceCompleteName];
}
return $serviceList;
}
/**
* @param string $additionnalCondition
*
* @return string
*/
private function getVirtualServicesCondition($additionnalCondition)
{
// First, get virtual services for metaservices
$metaServiceCondition = '';
if (! $this->aclObj->admin) {
$metaServices = $this->aclObj->getMetaServices();
$virtualServices = [];
foreach ($metaServices as $metaServiceId => $metaServiceName) {
$virtualServices[] = "'meta_" . $metaServiceId . "'";
}
if ($virtualServices !== []) {
$metaServiceCondition = 'AND s.description IN (' . implode(',', $virtualServices) . ') ';
} else {
return '';
}
} else {
$metaServiceCondition = 'AND s.description LIKE "meta_%" ';
}
$virtualServicesCondition = 'UNION ALL ('
. 'SELECT CONCAT("Meta - ", s.display_name) as fullname, i.host_id, i.service_id, m.index_id '
. 'FROM index_data i, metrics m, services s '
. 'WHERE i.id = m.index_id '
. $additionnalCondition
. $metaServiceCondition
. 'AND i.service_id = s.service_id '
. ') ';
// Then, get virtual services for modules
$allVirtualServiceIds = CentreonHook::execute('Service', 'getVirtualServiceIds');
foreach ($allVirtualServiceIds as $moduleVirtualServiceIds) {
foreach ($moduleVirtualServiceIds as $hostname => $virtualServiceIds) {
if (count($virtualServiceIds)) {
$virtualServicesCondition .= 'UNION ALL ('
. 'SELECT CONCAT("' . $hostname . ' - ", s.display_name) as fullname, i.host_id, '
. 'i.service_id, m.index_id '
. 'FROM index_data i, metrics m, services s '
. 'WHERE i.id = m.index_id '
. $additionnalCondition
. 'AND s.service_id IN (' . implode(',', $virtualServiceIds) . ') '
. 'AND i.service_id = s.service_id '
. ') ';
}
}
}
return $virtualServicesCondition;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonPdo.php | centreon/www/class/centreonPdo.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
*
*/
/**
* Class
*
* @class CentreonPdo
*/
class CentreonPdo extends PDO
{
/**
* CentreonPdo constructor
*
* @param $dsn
* @param $username
* @param $password
* @param $options
*
* @throws PDOException
*/
public function __construct($dsn, $username = null, $password = null, $options = [])
{
parent::__construct($dsn, $username, $password, $options);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['CentreonPdoStatement', [$this]]);
}
/**
* @return void
*/
public function disconnect()
{
}
/**
* returns error info
*
* @return string
*/
public function toString()
{
$errString = '';
$errTab = $this->errorInfo();
if (count($errTab)) {
$errString = implode(';', $errTab);
}
return $errString;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonService.class.php | centreon/www/class/centreonService.class.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__ . '/centreonInstance.class.php';
require_once __DIR__ . '/centreonDB.class.php';
require_once __DIR__ . '/centreonHook.class.php';
require_once __DIR__ . '/centreonDBInstance.class.php';
/**
* Class
*
* @class CentreonService
* @description Class that contains various methods for managing services
*/
class CentreonService
{
private const TABLE_SERVICE_CONFIGURATION = 'service';
private const TABLE_SERVICE_REALTIME = 'services';
private const PASSWORD_REPLACEMENT_VALUE = '**********';
/** @var CentreonDB */
protected $db;
/** @var CentreonDB */
protected $dbMon;
/** @var CentreonInstance */
protected $instanceObj;
/**
* Macros formatted by id
* ex:
* [
* 1 => [
* "macroName" => "KEY"
* "macroValue" => "value"
* "macroPassword" => "1"
* ],
* 2 => [
* "macroName" => "KEY_1"
* "macroValue" => "value_1"
* "macroPassword" => "1"
* "originalName" => "MACRO_1"
* ]
* ]
*
* @var array<int,array{
* macroName: string,
* macroValue: string,
* macroPassword: '0'|'1',
* originalName?: string
* }>
*/
private array $formattedMacros = [];
/**
* CentreonService constructor
*
* @param CentreonDB $db
* @param null|mixed $dbMon
* @throws PDOException
*/
public function __construct($db, $dbMon = null)
{
$this->db = $db;
$this->dbMon = is_null($dbMon) ? CentreonDBInstance::getDbCentreonStorageInstance() : $dbMon;
$this->instanceObj = CentreonInstance::getInstance($db, $dbMon);
}
/**
* filteredArrayId takes an array of combined ID (HOSTID_SVCID) as parameter.
* It will check for each combined ID if:
* - HOSTID is defined and > 0
* - SVCID is defined and > 0
*
* @param int[] $ids
* @return int[] filtered
*/
public function filteredArrayId(array $ids): array
{
/* Slight difference here. Array parameter is made
* of combined ids HOSTID_SERVICEID
*/
$combinedIds = [];
return array_filter($ids, function ($combinedId) {
// Only valid combined ID are authorized (HOSTID_SVCID)
if (preg_match('/([0-9]+)_([0-9]+)/', $combinedId, $matches)) {
$hostId = (int) $matches[1];
$serviceId = (int) $matches[2];
return $hostId > 0 && $serviceId > 0;
}
return false;
});
}
/**
* Method that returns service description from serviceId
*
* @param int $serviceId
*
* @throws PDOException
* @return string|null
*/
public function getServiceDesc(int $serviceId): ?string
{
static $svcTab = null;
if ($serviceId) {
if (is_null($svcTab)) {
$svcTab = [];
$rq = 'SELECT service_id, service_description
FROM service';
$res = $this->db->query($rq);
while ($row = $res->fetchRow()) {
$svcTab[$row['service_id']] = $row['service_description'];
}
}
if (isset($svcTab[$serviceId])) {
return $svcTab[$serviceId];
}
}
return null;
}
/**
* Get Service Template ID
*
* @param string|null $templateName
*
* @throws PDOException
* @return int
*/
public function getServiceTemplateId($templateName = null)
{
if (is_null($templateName)) {
return null;
}
$res = $this->db->query(
"SELECT service_id
FROM service
WHERE service_description = '" . $this->db->escape($templateName) . "'
AND service_register = '0'"
);
if (! $res->rowCount()) {
return null;
}
$row = $res->fetchRow();
return $row['service_id'];
}
/**
* Method that returns the id of a service
*
* @param string|null $svc_desc
* @param string|null $host_name
*
* @throws PDOException
* @return int
*/
public function getServiceId($svc_desc = null, $host_name = null)
{
static $hostSvcTab = [];
if (! isset($hostSvcTab[$host_name])) {
$rq = 'SELECT s.service_id, s.service_description '
. ' FROM service s'
. ' JOIN (SELECT hsr.service_service_id FROM host_service_relation hsr'
. ' JOIN host h'
. ' ON hsr.host_host_id = h.host_id'
. " WHERE h.host_name = '" . $this->db->escape($host_name) . "'"
. ' UNION'
. ' SELECT hsr.service_service_id FROM hostgroup_relation hgr'
. ' JOIN host h'
. ' ON hgr.host_host_id = h.host_id'
. ' JOIN host_service_relation hsr'
. ' ON hgr.hostgroup_hg_id = hsr.hostgroup_hg_id'
. " WHERE h.host_name = '" . $this->db->escape($host_name) . "' ) ghsrv"
. ' ON s.service_id = ghsrv.service_service_id';
$DBRES = $this->db->query($rq);
$hostSvcTab[$host_name] = [];
while ($row = $DBRES->fetchRow()) {
$hostSvcTab[$host_name][$row['service_description']] = $row['service_id'];
}
}
if (! isset($svc_desc) && isset($hostSvcTab[$host_name])) {
return $hostSvcTab[$host_name];
}
if (isset($hostSvcTab[$host_name], $hostSvcTab[$host_name][$svc_desc])) {
return $hostSvcTab[$host_name][$svc_desc];
}
return null;
}
/**
* Get Service Id From Hostgroup Name
*
* @param string $service_desc
* @param string $hgName
*
* @throws PDOException
* @return int
*/
public function getServiceIdFromHgName($service_desc, $hgName)
{
static $hgSvcTab = [];
if (! isset($hgSvcTab[$hgName])) {
$rq = "SELECT hsr.service_service_id, s.service_description
FROM host_service_relation hsr, hostgroup hg, service s
WHERE hsr.hostgroup_hg_id = hg.hg_id
AND hsr.service_service_id = s.service_id
AND hg.hg_name LIKE '" . $this->db->escape($hgName) . "' ";
$res = $this->db->query($rq);
while ($row = $res->fetchRow()) {
$hgSvcTab[$hgName][$row['service_description']] = $row['service_service_id'];
}
}
if (isset($hgSvcTab[$hgName], $hgSvcTab[$hgName][$service_desc])) {
return $hgSvcTab[$hgName][$service_desc];
}
return null;
}
/**
* Get Service alias
*
* @param int $sid
*
* @throws PDOException
* @return string
*/
public function getServiceName($sid)
{
static $svcTab = [];
if (! isset($svcTab[$sid])) {
$query = 'SELECT service_alias
FROM service
WHERE service_id = ' . $this->db->escape($sid);
$res = $this->db->query($query);
if ($res->rowCount()) {
$row = $res->fetchRow();
$svcTab[$sid] = $row['service_alias'];
}
}
return $svcTab[$sid] ?? null;
}
/**
* Gets the service description of a service
*
* @param int[] $serviceIds
*
* @throws PDOException
* @return array serviceDescriptions
* ['service_id' => integer, 'description' => string, 'host_name' => string, 'host_id' => integer],...]
*/
public function getServicesDescr($serviceIds = []): array
{
$serviceDescriptions = [];
if (! empty($serviceIds)) {
$where = '';
/* checking here that the array provided as parameter
* is exclusively made of integers (service ids)
*/
$filteredSvcIds = $this->filteredArrayId($serviceIds);
if ($filteredSvcIds !== []) {
foreach ($filteredSvcIds as $hostAndServiceId) {
[$hostId, $serviceId] = explode('_', $hostAndServiceId);
$where .= empty($where) ? ' ( ' : ' OR ';
$where .= " (h.host_id = {$hostId} AND s.service_id = {$serviceId}) ";
}
if ($where !== '') {
$where .= ' ) ';
$query = 'SELECT s.service_description, s.service_id, h.host_name, h.host_id
FROM service s
INNER JOIN host_service_relation hsr ON hsr.service_service_id = s.service_id
INNER JOIN host h ON hsr.host_host_id = h.host_id
WHERE ' . $where;
$res = $this->db->query($query);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
$serviceDescriptions[] = [
'service_id' => $row['service_id'],
'description' => $row['service_description'],
'host_name' => $row['host_name'],
'host_id' => $row['host_id'],
];
}
}
}
}
return $serviceDescriptions;
}
/**
* Check illegal char defined into nagios.cfg file
*
* @param string $name
*
* @throws PDOException
* @return string
*/
public function checkIllegalChar($name)
{
$DBRESULT = $this->db->query('SELECT illegal_object_name_chars FROM cfg_nagios');
while ($data = $DBRESULT->fetchRow()) {
$name = str_replace(str_split($data['illegal_object_name_chars']), '', $name);
}
$DBRESULT->closeCursor();
return $name;
}
/**
* Returns a string that replaces on demand macros by their values
*
* @param int $svc_id
* @param string $string
* @param int|null $antiLoop
* @param int|null $instanceId
*
* @throws PDOException
* @return string
*/
public function replaceMacroInString($svc_id, $string, $antiLoop = null, $instanceId = null)
{
if (! preg_match('/\$[0-9a-zA-Z_-]+\$/', $string)) {
return $string;
}
$query = <<<'SQL'
SELECT service_register, service_description
FROM service
WHERE service_id = :service_id LIMIT 1
SQL;
$statement = $this->db->prepare($query);
$statement->bindValue(':service_id', (int) $svc_id, PDO::PARAM_INT);
$statement->execute();
if (! $statement->rowCount()) {
return $string;
}
$row = $statement->fetchRow();
// replace if not template
if ($row['service_register'] == 1) {
if (preg_match('/\$SERVICEDESC\$/', $string)) {
$string = str_replace('$SERVICEDESC$', $row['service_description'], $string);
}
if (! is_null($instanceId) && preg_match('$INSTANCENAME$', $string)) {
$string = str_replace('$INSTANCENAME$', $this->instanceObj->getParam($instanceId, 'name'), $string);
}
if (! is_null($instanceId) && preg_match('$INSTANCEADDRESS$', $string)) {
$string = str_replace(
'$INSTANCEADDRESS$',
$this->instanceObj->getParam($instanceId, 'ns_ip_address'),
$string
);
}
}
$matches = [];
$pattern = '|(\$_SERVICE[0-9a-zA-Z\_\-]+\$)|';
preg_match_all($pattern, $string, $matches);
$i = 0;
while (isset($matches[1][$i])) {
$rq = "SELECT svc_macro_value
FROM on_demand_macro_service
WHERE svc_svc_id = '" . $svc_id . "' AND svc_macro_name LIKE '" . $matches[1][$i] . "'";
$DBRES = $this->db->query($rq);
while ($row = $DBRES->fetchRow()) {
$string = str_replace($matches[1][$i], $row['svc_macro_value'], $string);
}
$i++;
}
if ($i) {
$rq2 = "SELECT service_template_model_stm_id FROM service WHERE service_id = '" . $svc_id . "'";
$DBRES2 = $this->db->query($rq2);
while ($row2 = $DBRES2->fetchRow()) {
if (! isset($antiLoop) || ! $antiLoop) {
$string = $this->replaceMacroInString(
$row2['service_template_model_stm_id'],
$string,
$row2['service_template_model_stm_id']
);
} elseif ($row2['service_template_model_stm_id'] != $antiLoop) {
$string = $this->replaceMacroInString($row2['service_template_model_stm_id'], $string, $antiLoop);
}
}
}
return $string;
}
/**
* Get list of service templates
*
* @throws PDOException
* @return array
*/
public function getServiceTemplateList()
{
$res = $this->db->query("SELECT service_id, service_description
FROM service
WHERE service_register = '0'
ORDER BY service_description");
$list = [];
while ($row = $res->fetchRow()) {
$list[$row['service_id']] = $row['service_description'];
}
return $list;
}
/**
* Insert macro
*
* @param int $serviceId
* @param array $macroInput
* @param array $macroValue
* @param array $macroPassword
* @param array $macroDescription
* @param bool $isMassiveChange
* @param bool $cmdId
* @param bool $macroFrom
*
* @throws PDOException
* @return void
*/
public function insertMacro(
$serviceId,
$macroInput = [],
$macroValue = [],
$macroPassword = [],
$macroDescription = [],
$isMassiveChange = false,
$cmdId = false,
$macroFrom = false,
): void {
if ($isMassiveChange === false) {
$this->db->query('DELETE FROM on_demand_macro_service
WHERE svc_svc_id = ' . $this->db->escape($serviceId));
} else {
$macroList = '';
foreach ($macroInput as $v) {
$macroList .= "'\$_SERVICE" . strtoupper($this->db->escape($v)) . "\$',";
}
if ($macroList) {
$macroList = rtrim($macroList, ',');
$this->db->query('DELETE FROM on_demand_macro_service
WHERE svc_svc_id = ' . $this->db->escape($serviceId) . "
AND svc_macro_name IN ({$macroList})");
}
}
$stored = [];
$cnt = 0;
$macros = $macroInput;
$macrovalues = $macroValue;
$this->hasMacroFromServiceChanged(
$this->db,
$serviceId,
$macros,
$macrovalues,
$cmdId,
$isMassiveChange,
$macroFrom
);
foreach ($macros as $key => $value) {
if (
$value != ''
&& ! isset($stored[strtolower($value)])
) {
$this->db->query(
"INSERT INTO on_demand_macro_service
(`svc_macro_name`, `svc_macro_value`, `is_password`, `description`,
`svc_svc_id`, `macro_order`)
VALUES ('\$_SERVICE" . strtoupper($this->db->escape($value)) . "\$', '"
. $this->db->escape($macrovalues[$key]) . "', " . (isset($macroPassword[$key]) ? 1 : 'NULL')
. ", '" . $this->db->escape($macroDescription[$key]) . "', " . $this->db->escape($serviceId)
. ', ' . $cnt . ' )'
);
$stored[strtolower($value)] = true;
$cnt++;
// Format macros to improve handling on form submit.
$dbResult = $this->db->query('SELECT MAX(svc_macro_id) FROM on_demand_macro_service');
$macroId = $dbResult->fetch();
$this->formattedMacros[(int) $macroId['MAX(svc_macro_id)']] = [
'macroName' => '_SERVICE' . strtoupper($value),
'macroValue' => $macrovalues[$key],
'macroPassword' => $macroPassword[$key] ?? '0',
];
if (isset($_REQUEST['macroOriginalName_' . $key])) {
$this->formattedMacros[(int) $macroId['MAX(svc_macro_id)']]['originalName']
= '_SERVICE' . $_REQUEST['macroOriginalName_' . $key];
}
}
}
}
/**
* @param int|null $serviceId
* @param array|null $template
*
* @throws PDOException
* @return array
*/
public function getCustomMacroInDb($serviceId = null, $template = null)
{
$arr = [];
$i = 0;
if ($serviceId) {
$res = $this->db->query('SELECT svc_macro_name, svc_macro_value, is_password, description
FROM on_demand_macro_service
WHERE svc_svc_id = '
. $this->db->escape($serviceId) . '
ORDER BY macro_order ASC');
while ($row = $res->fetchRow()) {
if (preg_match('/\$_SERVICE(.*)\$$/', $row['svc_macro_name'], $matches)) {
$arr[$i]['macroInput_#index#'] = $matches[1];
$arr[$i]['macroValue_#index#'] = $row['svc_macro_value'];
$arr[$i]['macroPassword_#index#'] = $row['is_password'] ? 1 : null;
$arr[$i]['macroDescription_#index#'] = $row['description'];
$arr[$i]['macroDescription'] = $row['description'];
if (! is_null($template)) {
$arr[$i]['macroTpl_#index#'] = 'Service template : ' . $template['service_description'];
}
$i++;
}
}
}
return $arr;
}
/**
* Get service custom macro
*
* @param int|null $serviceId
* @param bool $realKeys
*
* @throws PDOException
* @return array
*/
public function getCustomMacro($serviceId = null, $realKeys = false)
{
$arr = [];
$i = 0;
if (! isset($_REQUEST['macroInput']) && $serviceId) {
$res = $this->db->query('SELECT svc_macro_name, svc_macro_value, is_password, description
FROM on_demand_macro_service
WHERE svc_svc_id = '
. $this->db->escape($serviceId) . '
ORDER BY macro_order ASC');
while ($row = $res->fetchRow()) {
if (preg_match('/\$_SERVICE(.*)\$$/', $row['svc_macro_name'], $matches)) {
$arr[$i]['macroInput_#index#'] = $matches[1];
$arr[$i]['macroValue_#index#'] = $row['svc_macro_value'];
$valPassword = null;
if (isset($row['is_password'])) {
$valPassword = $row['is_password'] === 1 ? '1' : null;
}
$arr[$i]['macroPassword_#index#'] = $valPassword;
$arr[$i]['macroDescription_#index#'] = $row['description'];
$arr[$i]['macroDescription'] = $row['description'];
$i++;
}
}
} elseif (isset($_REQUEST['macroInput'])) {
foreach ($_REQUEST['macroInput'] as $key => $val) {
$index = $i;
if ($realKeys) {
$index = $key;
}
$arr[$index]['macroInput_#index#'] = $val;
$arr[$index]['macroValue_#index#'] = $_REQUEST['macroValue'][$key];
$valPassword = null;
if (isset($_REQUEST['is_password'][$key])) {
$valPassword = $_REQUEST['is_password'][$key] === '1' ? '1' : null;
} elseif ($_REQUEST['macroValue'][$key]) {
$valPassword = $_REQUEST['macroValue'][$key] === self::PASSWORD_REPLACEMENT_VALUE ? '1' : null;
}
$arr[$i]['macroPassword_#index#'] = $valPassword;
$arr[$index]['macroDescription_#index#'] = $_REQUEST['description'][$key] ?? null;
$arr[$index]['macroDescription'] = $_REQUEST['description'][$key] ?? null;
$i++;
}
}
return $arr;
}
/**
* Returns array of locked templates
*
* @throws PDOException
* @return array
*/
public function getLockedServiceTemplates()
{
static $arr = null;
if (is_null($arr)) {
$arr = [];
$res = $this->db->query('SELECT service_id
FROM service
WHERE service_locked = 1');
while ($row = $res->fetchRow()) {
$arr[$row['service_id']] = true;
}
}
return $arr;
}
/**
* Clean up service relations (services by hostgroup)
*
* @param string $table
* @param string $host_id_field
* @param string $service_id_field
*
* @throws PDOException
* @return void
*/
public function cleanServiceRelations($table = '', $host_id_field = '', $service_id_field = ''): void
{
$sql = "DELETE FROM {$table}
WHERE NOT EXISTS (
SELECT hsr1.host_host_id
FROM host_service_relation hsr1
WHERE hsr1.host_host_id = {$table}.{$host_id_field}
AND hsr1.service_service_id = {$table}.{$service_id_field}
)
AND NOT EXISTS (
SELECT hsr2.host_host_id
FROM host_service_relation hsr2, hostgroup_relation hgr
WHERE hsr2.host_host_id = hgr.host_host_id
AND hgr.host_host_id = {$table}.{$host_id_field}
AND hsr2.service_service_id = {$table}.{$service_id_field}
)";
$this->db->query($sql);
}
/**
* @param array $service
* @param int $type | 0 = contact, 1 = contactgroup
* @param array $cgSCache
* @param array $cctSCache
*
* @throws PDOException
* @return bool
*/
public function serviceHasContact($service, $type = 0, $cgSCache = [], $cctSCache = [])
{
static $serviceTemplateHasContactGroup = [];
static $serviceTemplateHasContact = [];
if ($type == 0) {
$staticArr = &$serviceTemplateHasContact;
$cache = $cctSCache;
} else {
$staticArr = &$serviceTemplateHasContactGroup;
$cache = $cgSCache;
}
if (isset($cache[$service['service_id']])) {
return true;
}
while (isset($service['service_template_model_stm_id']) && $service['service_template_model_stm_id']) {
$serviceId = $service['service_template_model_stm_id'];
if (isset($cache[$serviceId]) || isset($staticArr[$serviceId])) {
$staticArr[$serviceId] = true;
return true;
}
$res = $this->db->query("SELECT service_template_model_stm_id
FROM service
WHERE service_id = {$serviceId}");
$service = $res->fetchRow();
}
return false;
}
/**
* @param CentreonDB $pearDB
* @param int $serviceId
* @param string $macroInput
* @param string $macroValue
* @param bool $cmdId
* @param bool $isMassiveChange
* @param bool $macroFrom
*/
public function hasMacroFromServiceChanged(
$pearDB,
$serviceId,
&$macroInput,
&$macroValue,
$cmdId = false,
$isMassiveChange = false,
$macroFrom = false,
): void {
$aListTemplate = getListTemplates($pearDB, $serviceId);
if (! isset($cmdId)) {
$cmdId = '';
}
$aMacros = $this->getMacros($serviceId, $aListTemplate, $cmdId);
foreach ($aMacros as $macro) {
foreach ($macroInput as $ind => $input) {
if (isset($macro['macroInput_#index#'], $macro['macroValue_#index#'])) {
// Don't override macros on massive change if there is not direct inheritance
if (
($input == $macro['macroInput_#index#'] && $macroValue[$ind] == $macro['macroValue_#index#'])
|| ($isMassiveChange
&& $input == $macro['macroInput_#index#']
&& isset($macroFrom[$ind])
&& $macroFrom[$ind] != 'direct')
) {
unset($macroInput[$ind], $macroValue[$ind]);
}
}
}
}
}
/**
* @param array $form
* @param string $fromKey
*
* @return array
*/
public function getMacroFromForm($form, $fromKey)
{
$Macros = [];
if (! empty($form['macroInput'])) {
foreach ($form['macroInput'] as $key => $macroInput) {
if ($form['macroFrom'][$key] == $fromKey) {
$macroTmp = [];
$macroTmp['macroInput_#index#'] = $macroInput;
$macroTmp['macroValue_#index#'] = $form['macroValue'][$key];
$macroTmp['macroPassword_#index#'] = isset($form['is_password'][$key]) ? 1 : null;
$macroTmp['macroDescription_#index#'] = $form['description'][$key] ?? null;
$macroTmp['macroDescription'] = $form['description'][$key] ?? null;
$Macros[] = $macroTmp;
}
}
}
return $Macros;
}
/**
* This method get the macro attached to the service
*
* @param int $iServiceId
* @param array $aListTemplate
* @param int $iIdCommande
* @param array $form
*
* @throws PDOException
* @return array
*/
public function getMacros($iServiceId, $aListTemplate, $iIdCommande, $form = [])
{
$macroArray = $this->getCustomMacroInDb($iServiceId);
$macroArray = array_merge($macroArray, $this->getMacroFromForm($form, 'direct'));
$aMacroInService = $this->getMacroFromForm($form, 'fromService');
// Get macro attached to the host
// clear current template/service from the list.
unset($aListTemplate[count($aListTemplate) - 1]);
foreach ($aListTemplate as $template) {
if (! empty($template)) {
$aMacroTemplate[] = $this->getCustomMacroInDb($template['service_id'], $template);
}
}
$aMacroTemplate[] = $this->getMacroFromForm($form, 'fromTpl');
$templateName = '';
if (empty($iIdCommande)) {
foreach ($aListTemplate as $template) {
if (! empty($template['command_command_id'])) {
$iIdCommande = $template['command_command_id'];
$templateName = 'Service template : ' . $template['service_description'] . ' | ';
}
}
}
// Get macro attached to the command
if (! empty($iIdCommande)) {
$oCommand = new CentreonCommand($this->db);
$macroTmp = $oCommand->getMacroByIdAndType($iIdCommande, 'service');
foreach ($macroTmp as $tmpmacro) {
$tmpmacro['macroTpl_#index#'] = $templateName . ' Commande : ' . $tmpmacro['macroCommandFrom'];
$aMacroInService[] = $tmpmacro;
}
}
// filter a macro
$aTempMacro = [];
if (count($aMacroInService) > 0) {
$counter = count($aMacroInService);
for ($i = 0; $i < $counter; $i++) {
$aMacroInService[$i]['macroOldValue_#index#'] = $aMacroInService[$i]['macroValue_#index#'];
$aMacroInService[$i]['macroFrom_#index#'] = 'fromService';
$aMacroInService[$i]['source'] = 'fromService';
$aTempMacro[] = $aMacroInService[$i];
}
}
if ($aMacroTemplate !== []) {
foreach ($aMacroTemplate as $key => $macr) {
foreach ($macr as $mm) {
$mm['macroOldValue_#index#'] = $mm['macroValue_#index#'];
$mm['macroFrom_#index#'] = 'fromTpl';
$mm['source'] = 'fromTpl';
$aTempMacro[] = $mm;
}
}
}
if ($macroArray !== []) {
foreach ($macroArray as $directMacro) {
$directMacro['macroOldValue_#index#'] = $directMacro['macroValue_#index#'];
$directMacro['macroFrom_#index#'] = 'direct';
$directMacro['source'] = 'direct';
$aTempMacro[] = $directMacro;
}
}
return $this->macroUnique($aTempMacro);
}
/**
* @param array $form
*
* @throws PDOException
* @return array
*/
public function ajaxMacroControl($form)
{
$aMacroInService = [];
$macroArray = $this->getCustomMacro(null, true);
$this->purgeOldMacroToForm($macroArray, $form, 'fromTpl');
$aListTemplate = [];
if (isset($form['service_template_model_stm_id']) && ! empty($form['service_template_model_stm_id'])) {
$aListTemplate = getListTemplates($this->db, $form['service_template_model_stm_id']);
}
// Get macro attached to the template
$aMacroTemplate = [];
foreach ($aListTemplate as $template) {
if (! empty($template)) {
$aMacroTemplate[] = $this->getCustomMacroInDb($template['service_id'], $template);
}
}
$iIdCommande = $form['command_command_id'] ?? [];
$templateName = '';
if (empty($iIdCommande)) {
foreach ($aListTemplate as $template) {
if (! empty($template['command_command_id'])) {
$iIdCommande = $template['command_command_id'];
$templateName = 'Service template : ' . $template['service_description'] . ' | ';
}
}
}
// Get macro attached to the command
if (! empty($iIdCommande)) {
$oCommand = new CentreonCommand($this->db);
$macroTmp = $oCommand->getMacroByIdAndType($iIdCommande, 'service');
foreach ($macroTmp as $tmpmacro) {
$tmpmacro['macroTpl_#index#'] = $templateName . ' Commande : ' . $tmpmacro['macroCommandFrom'];
$aMacroInService[] = $tmpmacro;
}
}
$this->purgeOldMacroToForm($macroArray, $form, 'fromService');
// filter a macro
$aTempMacro = [];
if ($aMacroInService !== []) {
$counter = count($aMacroInService);
for ($i = 0; $i < $counter; $i++) {
$aMacroInService[$i]['macroOldValue_#index#'] = $aMacroInService[$i]['macroValue_#index#'];
$aMacroInService[$i]['macroFrom_#index#'] = 'fromService';
$aMacroInService[$i]['source'] = 'fromService';
$aTempMacro[] = $aMacroInService[$i];
}
}
if ($aMacroTemplate !== []) {
foreach ($aMacroTemplate as $key => $macr) {
foreach ($macr as $mm) {
$mm['macroOldValue_#index#'] = $mm['macroValue_#index#'];
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonXMLBGRequest.class.php | centreon/www/class/centreonXMLBGRequest.class.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 Pimple\Container;
require_once realpath(__DIR__ . '/../../config/centreon.config.php');
require_once realpath(__DIR__ . '/../../bootstrap.php');
/**
* Class
*
* @class CentreonXMLBGRequest
* @description Class for XML/Ajax request
*/
class CentreonXMLBGRequest
{
/** @var string */
public $classLine;
// Objects
/** @var CentreonDB */
public CentreonDB $DB;
/** @var CentreonDB */
public CentreonDB $DBC;
/** @var CentreonXML */
public $XML;
/** @var CentreonGMT */
public $GMT;
/** @var CentreonHost */
public $hostObj;
/** @var CentreonService */
public $serviceObj;
/** @var CentreonMonitoring */
public $monObj;
/** @var CentreonACL */
public $access;
/** @var string */
public $session_id;
/** @var */
public $broker;
// Variables
/** @var */
public $buffer;
/** @var int */
public $debug;
/** @var int|mixed */
public $compress;
/** @var int */
public $header;
/** @var */
public $is_admin;
/** @var */
public $user_id;
/** @var array */
public $grouplist;
/** @var string */
public $grouplistStr;
/** @var */
public $general_opt;
/** @var */
public $class;
/** @var string[] */
public $stateType;
/** @var string[] */
public $statusHost;
/** @var string[] */
public $statusService;
/** @var string[] */
public $colorHost;
/** @var string[] */
public $colorHostInService;
/** @var string[] */
public $colorService;
/** @var array */
public $en;
/** @var string[] */
public $stateTypeFull;
/** @var string[] */
public $backgroundHost;
/** @var string[] */
public $backgroundService;
// Filters
/** @var */
public $defaultPoller;
/** @var */
public $defaultHostgroups;
/** @var */
public $defaultServicegroups;
/** @var int */
public $defaultCriticality = 0;
/**
* CentreonXMLBGRequest constructor
*
* <code>
* $obj = new CentreonBGRequest($_GET["session_id"], 1, 1, 0, 1);
* </code>
*
* @param Container $dependencyInjector
* @param string $session_id
* @param bool $dbNeeds
* @param bool $headerType
* @param bool $debug
* @param bool $compress
* @param $fullVersion
*
* @throws PDOException
*/
public function __construct(
Container $dependencyInjector,
$session_id,
$dbNeeds,
$headerType,
$debug,
$compress = null,
$fullVersion = 1,
) {
if (! isset($debug)) {
$this->debug = 0;
}
(! isset($headerType)) ? $this->header = 1 : $this->header = $headerType;
(! isset($compress)) ? $this->compress = 1 : $this->compress = $compress;
if (! isset($session_id)) {
echo 'Your might check your session id';
exit(1);
}
$this->session_id = htmlentities($session_id, ENT_QUOTES, 'UTF-8');
// Enable Database Connexions
$this->DB = $dependencyInjector['configuration_db'];
$this->DBC = $dependencyInjector['realtime_db'];
// Init Objects
$this->hostObj = new CentreonHost($this->DB);
$this->serviceObj = new CentreonService($this->DB, $this->DBC);
// Init Object Monitoring
$this->monObj = new CentreonMonitoring($this->DB);
if ($fullVersion) {
// Timezone management
$this->GMT = new CentreonGMT();
$this->GMT->getMyGMTFromSession($this->session_id);
}
// XML class
$this->XML = new CentreonXML();
// ACL init
$this->getUserIdFromSID();
$this->isUserAdmin();
$this->access = new CentreonACL($this->user_id, $this->is_admin);
$this->grouplist = $this->access->getAccessGroups();
$this->grouplistStr = $this->access->getAccessGroupsString();
// Init Color table
$this->getStatusColor();
// Init class
$this->classLine = 'list_one';
// Init Tables
$this->en = ['0' => _('No'), '1' => _('Yes')];
$this->stateType = ['1' => 'H', '0' => 'S'];
$this->stateTypeFull = ['1' => 'HARD', '0' => 'SOFT'];
$this->statusHost = ['0' => 'UP', '1' => 'DOWN', '2' => 'UNREACHABLE', '4' => 'PENDING'];
$this->statusService = ['0' => 'OK', '1' => 'WARNING', '2' => 'CRITICAL', '3' => 'UNKNOWN', '4' => 'PENDING'];
$this->colorHost = [0 => 'host_up', 1 => 'host_down', 2 => 'host_unreachable', 4 => 'pending'];
$this->colorService = [0 => 'service_ok', 1 => 'service_warning', 2 => 'service_critical', 3 => 'service_unknown', 4 => 'pending'];
$this->backgroundHost = [0 => '#88b917', 1 => '#e00b3d', 2 => '#818185', 4 => '#2ad1d4'];
$this->backgroundService = [0 => '#88b917', 1 => '#ff9a13', 2 => '#e00b3d', 3 => '#bcbdc0', 4 => '#2ad1d4'];
$this->colorHostInService = [0 => 'normal', 1 => '#FD8B46', 2 => 'normal', 4 => 'normal'];
}
/**
* Send headers information for web server
*
* @return void
*/
public function header(): void
{
// Force no encoding compress
$encoding = false;
header('Content-Type: text/xml');
header('Pragma: no-cache');
header('Expires: 0');
header('Cache-Control: no-cache, must-revalidate');
if ($this->compress && $encoding) {
header('Content-Encoding: ' . $encoding);
}
}
/**
* @return string
*/
public function getNextLineClass()
{
$this->classLine = $this->classLine == 'list_one' ? 'list_two' : 'list_one';
return $this->classLine;
}
/**
* @return void
*/
public function getDefaultFilters(): void
{
$this->defaultPoller = -1;
$this->defaultHostgroups = null;
$this->defaultServicegroups = null;
if (isset($_SESSION['monitoring_default_hostgroups'])) {
$this->defaultHostgroups = $_SESSION['monitoring_default_hostgroups'];
}
if (isset($_SESSION['monitoring_default_servicegroups'])) {
$this->defaultServicegroups = $_SESSION['monitoring_default_servicegroups'];
}
if (isset($_SESSION['monitoring_default_poller'])) {
$this->defaultPoller = $_SESSION['monitoring_default_poller'];
}
if (isset($_SESSION['criticality_id'])) {
$this->defaultCriticality = $_SESSION['criticality_id'];
}
}
/**
* @param $instance
*
* @return void
*/
public function setInstanceHistory($instance): void
{
$_SESSION['monitoring_default_poller'] = $instance;
}
/**
* @param $hg
*
* @return void
*/
public function setHostGroupsHistory($hg): void
{
$_SESSION['monitoring_default_hostgroups'] = $hg;
}
/**
* @param $sg
*
* @return void
*/
public function setServiceGroupsHistory($sg): void
{
$_SESSION['monitoring_default_servicegroups'] = $sg;
}
/**
* @param $criticality
*
* @return void
*/
public function setCriticality($criticality): void
{
$_SESSION['criticality_id'] = $criticality;
}
/**
* @param $name
* @param $tab
* @param $defaultValue
*
* @return string
*/
public function checkArgument($name, $tab, $defaultValue)
{
if (isset($name, $tab)) {
if (isset($tab[$name])) {
if ($name == 'num' && $tab[$name] < 0) {
$tab[$name] = 0;
}
$value = htmlspecialchars($tab[$name], ENT_QUOTES, 'utf-8');
return CentreonDB::escape($value);
}
return CentreonDB::escape($defaultValue);
}
return '';
}
/**
* @param string $name
*
* @return array|string|string[]
*/
public function prepareObjectName($name)
{
$name = str_replace('/', '#S#', $name);
return str_replace('\\', '#BS#', $name);
}
/**
* Get user id from session_id
*
* @throws PDOException
* @return void
*/
protected function getUserIdFromSID()
{
$query = 'SELECT user_id FROM session '
. "WHERE session_id = '" . CentreonDB::escape($this->session_id) . "' LIMIT 1";
$dbResult = $this->DB->query($query);
$admin = $dbResult->fetchRow();
unset($dbResult);
if (isset($admin['user_id'])) {
$this->user_id = $admin['user_id'];
}
}
/**
* Get Status Color
*
* @throws PDOException
* @return void
*/
protected function getStatusColor()
{
$this->general_opt = [];
$DBRESULT = $this->DB->query("SELECT * FROM `options` WHERE `key` LIKE 'color%'");
while ($c = $DBRESULT->fetchRow()) {
$this->general_opt[$c['key']] = $this->myDecode($c['value']);
}
$DBRESULT->closeCursor();
unset($c);
}
/**
* @return void
*/
private function isUserAdmin(): void
{
$statement = $this->DB->prepare('SELECT contact_admin, contact_id FROM contact '
. 'WHERE contact.contact_id = :userId LIMIT 1');
$statement->bindValue(':userId', (int) $this->user_id, PDO::PARAM_INT);
$statement->execute();
$admin = $statement->fetchRow();
$statement->closeCursor();
$this->is_admin = $admin !== false && $admin['contact_admin'] ? 1 : 0;
}
/**
* Decode Function
*
* @param string $arg
*
* @return string
*/
private function myDecode($arg)
{
return html_entity_decode($arg ?? '', ENT_QUOTES, 'UTF-8');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonCustomView.class.php | centreon/www/class/centreonCustomView.class.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 _CENTREON_PATH_ . 'www/class/centreonLDAP.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonContactgroup.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;
/**
* Class
*
* @class CentreonCustomViewException
* @description Centreon Custom View Exception
*/
class CentreonCustomViewException extends Exception
{
}
/**
* Class
*
* @class CentreonCustomView
* @description Class for managing widgets
*/
class CentreonCustomView
{
public const TOPOLOGY_PAGE_EDIT_VIEW = 10301;
public const TOPOLOGY_PAGE_SHARE_VIEW = 10302;
public const TOPOLOGY_PAGE_SET_WIDGET_PREFERENCES = 10303;
public const TOPOLOGY_PAGE_ADD_WIDGET = 10304;
public const TOPOLOGY_PAGE_DELETE_WIDGET = 10304;
public const TOPOLOGY_PAGE_SET_ROTATE = 10305;
public const TOPOLOGY_PAGE_DELETE_VIEW = 10306;
public const TOPOLOGY_PAGE_ADD_VIEW = 10307;
public const TOPOLOGY_PAGE_SET_DEFAULT_VIEW = 10308;
/** @var CentreonContactgroup */
public $cg;
/** @var */
protected $userId;
/** @var array */
protected $userGroups = [];
/** @var CentreonDB */
protected $db;
/** @var */
protected $customViews;
/** @var */
protected $currentView;
/** @var int|mixed */
protected $defaultView;
/**
* CentreonCustomView constructor.
*
* @param $centreon
* @param CentreonDB $db
* @param null $userId
* @throws Exception
*/
public function __construct($centreon, $db, $userId = null)
{
$this->userId = is_null($userId) ? $centreon->user->user_id : $userId;
$this->db = $db;
$query = 'SELECT contactgroup_cg_id FROM contactgroup_contact_relation WHERE contact_contact_id = :userId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$this->userGroups[$row['contactgroup_cg_id']] = $row['contactgroup_cg_id'];
}
$query2 = 'SELECT custom_view_id FROM custom_view_default WHERE user_id = :userId LIMIT 1';
$stmt2 = $this->db->prepare($query2);
$stmt2->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$dbResult2 = $stmt2->execute();
if (! $dbResult2) {
throw new Exception('An error occured');
}
$this->defaultView = 0;
if ($stmt2->rowCount()) {
$row = $stmt2->fetch();
$this->defaultView = $row['custom_view_id'];
}
$this->cg = new CentreonContactgroup($db);
}
/**
* Check number of view unlocked and consume
*
* @param $userId
* @param $viewId
* @throws Exception
* @return mixed
*/
public function checkOtherShareViewUnlocked($userId, $viewId)
{
$query = 'SELECT COUNT(user_id) as "nbuser" '
. 'FROM custom_view_user_relation '
. 'WHERE locked = 0 '
. 'AND is_consumed = 1 '
. 'AND user_id <> :userId '
. 'AND custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$stmt->bindParam(':viewId', $viewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$row = $stmt->fetch();
return $row['nbuser'];
}
/**
* Check number of view unlocked
*
* @param $viewId
* @throws Exception
* @return mixed
*/
public function checkOwnerViewStatus($viewId)
{
$query = 'SELECT is_consumed '
. 'FROM custom_view_user_relation '
. 'WHERE is_owner = 1 '
. 'AND custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $viewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$row = $stmt->fetch();
return $row['is_consumed'];
}
/**
* Check Permission
* Checks if user is allowed to modify a view
* Returns true if user can, false otherwise
*
* @param int $viewId
*
* @throws Exception
* @return bool
*/
public function checkPermission(int $viewId): bool
{
$views = $this->getCustomViews();
return ! (! isset($views[$viewId]) || $views[$viewId]['locked']);
}
/**
* checkUserActions - Check wether or not the user
* can do the provided action
*
* @param string $action
* @return bool
*/
public function checkUserActions(string $action): bool
{
/* associate the called action with the toplogy page.
* Special behaviour for the deleteWidget action which does not have any possible configuration in ACL Menus.
* We do consider through that if user can create a widget then he also can delete it.
* Also "defaultEditMode" action has no link with ACL this action is authorized for all.
*/
if ($action == 'defaultEditMode') {
return true;
}
$associativeActions = [
'edit' => self::TOPOLOGY_PAGE_EDIT_VIEW,
'share' => self::TOPOLOGY_PAGE_SHARE_VIEW,
'setPreferences' => self::TOPOLOGY_PAGE_SET_WIDGET_PREFERENCES,
'addWidget' => self::TOPOLOGY_PAGE_ADD_WIDGET,
'deleteWidget' => self::TOPOLOGY_PAGE_DELETE_WIDGET,
'setRotate' => self::TOPOLOGY_PAGE_SET_ROTATE,
'deleteView' => self::TOPOLOGY_PAGE_DELETE_VIEW,
'add' => self::TOPOLOGY_PAGE_ADD_VIEW,
'setDefault' => self::TOPOLOGY_PAGE_SET_DEFAULT_VIEW,
];
// retrieving menu access rights of the current user.
$acls = new CentreonACL($this->userId);
$userCustomViewActions = $acls->getTopology();
return (bool) (array_key_exists($associativeActions[$action], $userCustomViewActions));
}
/**
* Check if user is not owner but view shared with him
*
* @param int $viewId
*
* @throws Exception
* @return bool
*/
public function checkSharedPermission($viewId)
{
$views = $this->getCustomViews();
return ! (! isset($views[$viewId]) || $views[$viewId]['is_owner'] == 1);
}
/**
* Check Ownership
* Checks if user is allowed to delete view
* Returns true if user can, false otherwise
*
* @param int $viewId
*
* @throws Exception
* @return bool
*/
public function checkOwnership($viewId)
{
$views = $this->getCustomViews();
return (bool) (isset($views[$viewId]) && $views[$viewId]['is_owner']);
}
/**
* Set Default
*
* @param $viewId
* @throws Exception
*/
public function setDefault($viewId): void
{
$query = 'DELETE FROM custom_view_default WHERE user_id = :userId ';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$query2 = 'INSERT INTO custom_view_default (custom_view_id, user_id) VALUES (:viewId, :userId)';
$stmt2 = $this->db->prepare($query2);
$stmt2->bindParam(':viewId', $viewId, PDO::PARAM_INT);
$stmt2->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$dbResult2 = $stmt2->execute();
if (! $dbResult2) {
throw new Exception('An error occured');
}
}
/**
* Get default view id
*
* @return int
*/
public function getDefaultViewId()
{
return $this->defaultView;
}
/**
* Get Current View Id
*
* @throws Exception
* @return int
*/
public function getCurrentView()
{
if (! isset($this->currentView)) {
if (isset($_REQUEST['currentView'])) {
$this->currentView = (int) $_REQUEST['currentView'];
} else {
$views = $this->getCustomViews();
$i = 0;
foreach ($views as $viewId => $view) {
if ($i == 0) {
$first = $viewId;
}
if ($this->defaultView == $viewId) {
$this->currentView = $viewId;
break;
}
}
if (! isset($this->currentView) && isset($first)) {
$this->currentView = $first;
} elseif (! isset($this->currentView)) {
$this->currentView = 0;
}
}
}
return (int) $this->currentView;
}
/**
* Get Custom Views
*
* @throws Exception
* @return array
*/
public function getCustomViews()
{
$queryValue = [];
$cglist = '';
if (! isset($this->customViews)) {
$query = 'SELECT cv.custom_view_id, name, layout, is_owner, locked, user_id, usergroup_id, public '
. 'FROM custom_views cv, custom_view_user_relation cvur '
. 'WHERE cv.custom_view_id = cvur.custom_view_id '
. 'AND (cvur.user_id = ? ';
$queryValue[] = (int) $this->userId;
if (count($this->userGroups)) {
foreach ($this->userGroups as $key => $value) {
$cglist .= '?, ';
$queryValue[] = (int) $value;
}
$query .= 'OR cvur.usergroup_id IN (' . rtrim($cglist, ', ') . ')';
}
$query .= ') AND is_consumed = 1 ORDER BY user_id, name';
$this->customViews = [];
$stmt = $this->db->prepare($query);
$dbResult = $stmt->execute($queryValue);
if (! $dbResult) {
throw new Exception('An error occured');
}
$tmp = [];
while ($row = $stmt->fetch()) {
$cvid = $row['custom_view_id'];
$tmp[$cvid]['name'] = $row['name'];
$tmp[$cvid]['public'] = $row['public'];
if (! isset($tmp[$cvid]['is_owner']) || ! $tmp[$cvid]['is_owner'] || $row['user_id']) {
$tmp[$cvid]['is_owner'] = $row['is_owner'];
}
if (! isset($tmp[$cvid]['locked']) || ! $tmp[$cvid]['locked'] || $row['user_id']) {
$tmp[$cvid]['locked'] = $row['locked'];
}
$tmp[$cvid]['layout'] = $row['layout'];
$tmp[$cvid]['custom_view_id'] = $row['custom_view_id'];
}
foreach ($tmp as $customViewId => $tab) {
foreach ($tab as $key => $val) {
$this->customViews[$customViewId][$key] = $val;
}
}
}
return $this->customViews;
}
/**
* Add Custom View
*
* @param string $viewName
* @param string $layout
* @param ?int $publicView
* @param bool $authorized
* @throws Exception
* @return int $lastId
*/
public function addCustomView(string $viewName, string $layout, ?int $publicView, bool $authorized): int
{
if (! $authorized) {
throw new CentreonCustomViewException('You are not allowed to add a custom view.');
}
$public = 1;
if (! $publicView) {
$public = 0;
}
$query = 'INSERT INTO custom_views (`name`, `layout`, `public`) '
. 'VALUES (:viewName, :layout , "' . $public . '")';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewName', $viewName, PDO::PARAM_STR);
$stmt->bindParam(':layout', $layout, PDO::PARAM_STR);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$lastId = $this->getLastViewId();
$query = 'INSERT INTO custom_view_user_relation (custom_view_id, user_id, locked, is_owner) '
. 'VALUES (:lastId, :userId, 0, 1)';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':lastId', $lastId, PDO::PARAM_INT);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
return $lastId;
}
/**
* @param $customViewId
* @param bool $authorized
* @throws Exception
*/
public function deleteCustomView($customViewId, bool $authorized): void
{
if (! $authorized) {
throw new CentreonCustomViewException('You are not allowed to delete the view');
}
// owner
if ($this->checkOwnership($customViewId)) {
// if not shared view consumed
if (! $this->checkOtherShareViewUnlocked($this->userId, $customViewId)) {
$query = 'DELETE FROM custom_views WHERE custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
} else {
$query = 'DELETE FROM custom_view_user_relation '
. 'WHERE custom_view_id = :viewId '
. 'AND (is_consumed = 0 OR is_owner = 1)';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
}
// other
} elseif ($this->checkOwnerViewStatus($customViewId) == 0) {
// if owner consumed = 0 -> delete
// if not other shared view consumed, delete all
if (! $this->checkOtherShareViewUnlocked($customViewId, $this->userId)) {
$query = 'DELETE FROM custom_views WHERE custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$stmt->execute();
// if shared view consumed, delete for me
} else {
$query = 'DELETE FROM custom_view_user_relation '
. 'WHERE user_id = :userId '
. 'AND custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$stmt->execute();
}
// if owner not delete
} else {
// reset relation by setting is_consumed flag to 0
try {
$stmt = $this->db->prepare(
'UPDATE custom_view_user_relation SET is_consumed = 0 '
. 'WHERE custom_view_id = :viewId AND user_id = :userId '
);
$stmt->bindParam(':userId', $this->userId, PDO::PARAM_INT);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
throw new Exception(
'Cannot reset widget preferences, ' . $e->getMessage() . "\n"
);
}
}
}
/**
* Update Custom View
*
* @param int $viewId
* @param string $viewName
* @param string $layout
* @param int|null $public
* @param bool $permission
* @param bool $authorized
*
* @throws CentreonCustomViewException
* @throws PDOException
* @return int $customViewId
*/
public function updateCustomView(
int $viewId,
string $viewName,
string $layout,
?int $public,
bool $permission,
bool $authorized,
): int {
if (! $authorized || ! $permission) {
throw new CentreonCustomViewException('You are not allowed to edit the custom view');
}
$typeView = 0;
if (! empty($public)) {
$typeView = $public;
}
$query = 'UPDATE custom_views SET `name` = :viewName, `layout` = :layout, `public` = :typeView '
. 'WHERE `custom_view_id` = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewName', $viewName, PDO::PARAM_STR);
$stmt->bindParam(':layout', $layout, PDO::PARAM_STR);
$stmt->bindParam(':typeView', $typeView, PDO::PARAM_INT);
$stmt->bindParam(':viewId', $viewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
return $viewId;
}
/**
* @param $customViewId
* @param null $userId
* @throws Exception
* @return null
*/
public function syncCustomView($customViewId, $userId = null)
{
if (! $this->checkOwnership($customViewId)) {
return null;
}
if (! is_null($userId)) {
$this->copyPreferences($customViewId, $userId);
} else {
$query = 'SELECT user_id, usergroup_id FROM custom_view_user_relation '
. 'WHERE custom_view_id = :viewId '
. 'AND locked = 1';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
while ($row = $stmt->fetch()) {
$this->copyPreferences(
$customViewId,
$row['user_id'],
$row['usergroup_id']
);
}
}
}
/**
* Loads the Custom View attached to the viewLoadId
*
* @param int $viewLoadId
* @param bool $authorized
*
* @throws CentreonCustomViewException
* @throws PDOException
* @return int $viewLoad
*/
public function loadCustomView(int $viewLoadId, bool $authorized): int
{
if (! $authorized) {
throw new CentreonCustomViewException('You are not allowed to add a custom view');
}
$isLocked = 1;
$update = false;
try {
$query = <<<'SQL'
SELECT custom_view_id, locked, user_id, usergroup_id
FROM custom_view_user_relation
WHERE custom_view_id = :viewLoad
AND (
user_id = :userId
OR usergroup_id IN (
SELECT contactgroup_cg_id
FROM contactgroup_contact_relation
WHERE contact_contact_id = :userId
)
)
ORDER BY user_id DESC
SQL;
$params = [
QueryParameter::int('viewLoad', $viewLoadId),
QueryParameter::int('userId', $this->userId),
];
$queryParams = QueryParameters::create($params);
$row = $this->db->fetchAssociative($query, $queryParams);
if ($row) {
if ($row['locked'] == '0') {
$isLocked = $row['locked'];
}
if (! is_null($row['user_id']) && $row['user_id'] > 0 && is_null($row['usergroup_id'])) {
$update = true;
}
}
if ($update) {
$query = <<<'SQL'
UPDATE custom_view_user_relation SET is_consumed=1
WHERE custom_view_id = :viewLoad AND user_id = :userId
SQL;
$this->db->update($query, $queryParams);
} else {
$query = <<<'SQL'
SELECT 1
FROM custom_views cv
INNER JOIN custom_view_user_relation cvur
ON cv.custom_view_id = cvur.custom_view_id
WHERE cv.custom_view_id = :viewLoad
AND (
public = 1
OR (
usergroup_id IN (
SELECT contactgroup_cg_id
FROM contactgroup_contact_relation
WHERE contact_contact_id = :userId
)
)
)
SQL;
$row = $this->db->fetchAssociative($query, $queryParams);
if (! $row) {
throw new CentreonCustomViewException('Access denied: View not found or not accessible to current user');
}
$query = <<<'SQL'
INSERT INTO custom_view_user_relation (custom_view_id,user_id,is_owner,locked,is_share)
VALUES (:viewLoad, :userId, 0, :isLocked, 1)
SQL;
$params[] = QueryParameter::int('isLocked', $isLocked);
$queryParams = QueryParameters::create($params);
$this->db->insert($query, $queryParams);
}
// if the view is being added for the first time, we make sure that the widget parameters are going to be set
if (! $update) {
$this->addPublicViewWidgetParams($viewLoadId, $this->userId);
}
return $viewLoadId;
} catch (ValueObjectException|ConnectionException|CollectionException $e) {
throw new CentreonCustomViewException(
'An error occurred while loading the custom view: ' . $e->getMessage(),
previous: $e
);
}
}
/**
* @param $viewId
* @param $userId
* @throws Exception
*/
public function addPublicViewWidgetParams($viewId, $userId): void
{
// get all widget parameters from the view that is being added
if (! empty($userId)) {
$stmt = $this->db->prepare(
'SELECT * FROM widget_views wv '
. 'LEFT JOIN widget_preferences wp ON wp.widget_view_id = wv.widget_view_id '
. 'LEFT JOIN custom_view_user_relation cvur ON cvur.custom_view_id = wv.custom_view_id '
. 'WHERE cvur.custom_view_id = :viewId AND cvur.is_owner = 1 AND cvur.user_id = wp.user_id'
);
$stmt->bindParam(':viewId', $viewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception(
"An error occurred when retrieving user's Id : " . $userId
. ' parameters of the widgets from the view: Id = ' . $viewId
);
}
// add every widget parameters for the current user
while ($row = $stmt->fetch()) {
$stmt2 = $this->db->prepare(
'INSERT INTO widget_preferences '
. 'VALUES (:widgetViewId, :parameterId, :preferenceValue, :userId)'
);
$stmt2->bindParam(':widgetViewId', $row['widget_view_id'], PDO::PARAM_INT);
$stmt2->bindParam(':parameterId', $row['parameter_id'], PDO::PARAM_INT);
$stmt2->bindParam(':preferenceValue', $row['preference_value'], PDO::PARAM_STR);
$stmt2->bindParam(':userId', $userId, PDO::PARAM_INT);
$dbResult2 = $stmt2->execute();
if (! $dbResult2) {
throw new Exception(
"An error occurred when adding user's Id : " . $userId
. ' parameters to the widgets from the view: Id = ' . $viewId
);
}
}
}
}
/**
* @param int $customViewId
* @param int[] $lockedUsers
* @param int[] $unlockedUsers
* @param int[] $lockedUsergroups
* @param int[] $unlockedUsergroups
* @param int $userId
* @param bool $permission
* @param bool $authorized
*
* @throws CentreonCustomViewException
* @throws PDOException
*/
public function shareCustomView(
int $customViewId,
array $lockedUsers,
array $unlockedUsers,
array $lockedUsergroups,
array $unlockedUsergroups,
int $userId,
bool $permission,
bool $authorized,
): void {
if (! $authorized || ! $permission) {
throw new CentreonCustomViewException('You are not allowed to share the view');
}
global $centreon;
$queryValue = [];
if ($this->checkPermission($customViewId)) {
// ////////////////////
// share with users //
// ////////////////////
$sharedUsers = [];
$alwaysSharedUsers = [];
if ($lockedUsers !== []) {
foreach ($lockedUsers as $lockedUser) {
if ($lockedUser != $centreon->user->user_id) {
$sharedUsers[$lockedUser] = 1;
}
}
}
if ($unlockedUsers !== []) {
foreach ($unlockedUsers as $unlockedUser) {
if ($unlockedUser != $centreon->user->user_id) {
$sharedUsers[$unlockedUser] = 0;
}
}
}
// select user already share
$stmt = $this->db->prepare(
'SELECT user_id FROM custom_view_user_relation '
. 'WHERE custom_view_id = :viewId '
. 'AND user_id <> :userId '
. 'AND usergroup_id IS NULL '
);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$oldSharedUsers = [];
while ($row = $stmt->fetch()) {
$oldSharedUsers[$row['user_id']] = 1;
}
// check if the view is share at a new user
foreach ($sharedUsers as $sharedUserId => $locked) {
if (isset($oldSharedUsers[$sharedUserId])) {
$stmt = $this->db->prepare(
'UPDATE custom_view_user_relation SET is_share = 1, locked = :isLocked '
. 'WHERE user_id = :userId '
. 'AND custom_view_id = :viewId'
);
$stmt->bindParam(':isLocked', $locked, PDO::PARAM_INT);
$stmt->bindParam(':userId', $sharedUserId, PDO::PARAM_INT);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
unset($oldSharedUsers[$sharedUserId]);
} else {
$stmt = $this->db->prepare(
'INSERT INTO custom_view_user_relation '
. '(custom_view_id, user_id, locked, is_consumed, is_share ) '
. 'VALUES ( :viewId, :sharedUser, :isLocked, 0, 1) '
);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$stmt->bindParam(':sharedUser', $sharedUserId, PDO::PARAM_INT);
$stmt->bindParam(':isLocked', $locked, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
}
$alwaysSharedUsers[] = $sharedUserId;
$this->copyPreferences($customViewId, $sharedUserId);
}
$queryValue[] = (int) $customViewId;
$userIdKey = '';
// prepare old user entries
if ($oldSharedUsers !== []) {
foreach ($oldSharedUsers as $k => $v) {
$userIdKey .= '?,';
$queryValue[] = (int) $k;
}
$userIdKey = rtrim($userIdKey, ',');
} else {
$userIdKey .= '""';
}
// delete widget preferences for old user
$stmt = $this->db->prepare(
'DELETE FROM widget_preferences '
. 'WHERE widget_view_id IN (SELECT wv.widget_view_id FROM widget_views wv '
. 'WHERE wv.custom_view_id = ? ) '
. 'AND user_id IN (' . $userIdKey . ') '
);
$dbResult = $stmt->execute($queryValue);
if (! $dbResult) {
throw new Exception($stmt->errorInfo());
}
// delete view / user relation
$stmt = $this->db->prepare(
'DELETE FROM custom_view_user_relation '
. 'WHERE custom_view_id = ? '
. 'AND user_id IN (' . $userIdKey . ') '
);
$dbResult = $stmt->execute($queryValue);
if (! $dbResult) {
throw new Exception('An error occurred');
}
// //////////////////////////
// share with user groups //
// //////////////////////////
$sharedUsergroups = [];
if ($lockedUsergroups !== []) {
foreach ($lockedUsergroups as $lockedUsergroup) {
$sharedUsergroups[$lockedUsergroup] = 1;
}
}
if ($unlockedUsergroups !== []) {
foreach ($unlockedUsergroups as $unlockedUsergroup) {
$sharedUsergroups[$unlockedUsergroup] = 0;
}
}
$query = 'SELECT usergroup_id FROM custom_view_user_relation '
. 'WHERE custom_view_id = :viewId '
. 'AND user_id IS NULL ';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
throw new Exception('An error occured');
}
$oldSharedUsergroups = [];
while ($row = $stmt->fetch()) {
$oldSharedUsergroups[$row['usergroup_id']] = 1;
}
foreach ($sharedUsergroups as $sharedUsergroupId => $locked) {
if (isset($oldSharedUsergroups[$sharedUsergroupId])) {
$query = 'UPDATE custom_view_user_relation SET is_share = 1, locked = :isLocked '
. 'WHERE usergroup_id = :sharedUser '
. 'AND custom_view_id = :viewId';
$stmt = $this->db->prepare($query);
$stmt->bindParam(':isLocked', $locked, PDO::PARAM_INT);
$stmt->bindParam(':sharedUser', $sharedUsergroupId, PDO::PARAM_INT);
$stmt->bindParam(':viewId', $customViewId, PDO::PARAM_INT);
$dbResult = $stmt->execute();
if (! $dbResult) {
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonGraphTemplate.class.php | centreon/www/class/centreonGraphTemplate.class.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
*
*/
/**
* Class
*
* @class CentreonGraphTemplate
*/
class CentreonGraphTemplate
{
/** @var CentreonDB */
protected $db;
/** @var CentreonInstance */
protected $instanceObj;
/**
* CentreonGraphTemplate constructor
*
* @param CentreonDB $db
*/
public function __construct($db)
{
$this->db = $db;
$this->instanceObj = new CentreonInstance($db);
}
/**
* @param array $values
* @param array $options
* @param string $register
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [], $register = '1')
{
$items = [];
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':graph' . $v . ',';
$queryValues['graph' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
$query = 'SELECT graph_id, name FROM giv_graphs_template
WHERE graph_id IN (' . $listValues . ') ORDER BY name';
$stmt = $this->db->prepare($query);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($row = $stmt->fetchRow()) {
$items[] = ['id' => $row['graph_id'], 'text' => $row['name']];
}
return $items;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonMsg.class.php | centreon/www/class/centreonMsg.class.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
*
*/
/**
* Class
*
* @class CentreonMsg
* @description Class that displays any kind of information between the html header containing logo
* and the horizontal menu
*/
class CentreonMsg
{
/** @var string */
public $color = '#FFFFFF';
/** @var string */
public $div;
/**
* CentreonMsg constructor
*
* @param string|null $divId
*/
public function __construct($divId = null)
{
$this->div = empty($divId) ? 'centreonMsg' : $divId;
}
/**
* Display an information message.
*
* @param string $message
*
* @return void
*/
public function info(string $message): void
{
$this->setTextStyle('bold');
$this->setText($message);
$this->setTimeOut('3');
}
/**
* Display an error message.
*
* @param string $message
*
* @return void
*/
public function error(string $message): void
{
$this->setTextColor('rgb(255, 102, 102)');
$this->setTextStyle('bold');
$this->setText($message);
$this->setTimeOut('3');
}
/**
* Sets style of text inside Div
*
* @param string $style
*
* @return void
*/
public function setTextStyle($style): void
{
echo "<script type=\"text/javascript\">_setTextStyle(\"{$this->div}\", \"{$style}\")</script>";
}
/**
* @param string $color
*
* @return void
*/
public function setTextColor($color): void
{
echo "<script type=\"text/javascript\">_setTextColor(\"{$this->div}\", \"{$color}\")</script>";
}
/**
* @param string $align
*
* @return void
*/
public function setAlign($align): void
{
echo "<script type=\"text/javascript\">_setAlign(\"{$this->div}\", \"{$align}\")</script>";
}
/**
* @param string $align
*
* @return void
*/
public function setValign($align): void
{
echo "<script type=\"text/javascript\">_setValign(\"{$this->div}\", \"{$align}\")</script>";
}
/**
* @param string $color
*
* @return void
*/
public function setBackgroundColor($color): void
{
echo "<script type=\"text/javascript\">_setBackgroundColor(\"{$this->div}\", \"{$color}\")</script>";
}
/**
* @param string $str
*
* @return void
*/
public function setText($str): void
{
echo "<script type=\"text/javascript\">_setText(\"{$this->div}\", \"{$str}\")</script>";
}
/**
* @param string $img_url
*
* @return void
*/
public function setImage($img_url): void
{
echo "<script type=\"text/javascript\">_setImage(\"{$this->div}\", \"{$img_url}\")</script>";
}
/**
* If you want to display your message for a limited time period, just call this function
*
* @param int $sec
*
* @return void
*/
public function setTimeOut($sec): void
{
echo '<script type="text/javascript">'
. 'setTimeout(() => { jQuery("#' . $this->div . '").toggle(); }, ' . ($sec * 1000) . ');'
. '</script>';
}
/**
* Clear message box
*
* @return void
*/
public function clear(): void
{
echo "<script type=\"text/javascript\">_clear(\"{$this->div}\")</script>";
}
/**
* @return void
*/
public function nextLine(): void
{
echo "<script type=\"text/javascript\">_nextLine(\"{$this->div}\")</script>";
}
}
?>
<script type="text/javascript">
var __image_lock = 0;
function _setBackgroundColor(div_str, color) {
document.getElementById(div_str).style.backgroundColor = color;
}
function _setText(div_str, str) {
var my_text = document.createTextNode(str);
var my_div = document.getElementById(div_str);
my_div.appendChild(my_text);
}
function _setImage(div_str, url) {
var _image = document.createElement("img");
_image.src = url;
_image.id = "centreonMsg_img";
var my_div = document.getElementById(div_str);
my_div.appendChild(_image);
}
function _clear(div_str) {
document.getElementById(div_str).innerHTML = "";
}
function _setAlign(div_str, align) {
var my_div = document.getElementById(div_str);
my_div.style.textAlign = align;
}
function _setValign(div_str, align) {
var my_div = document.getElementById(div_str);
my_div.style.verticalAlign = align;
}
function _setTextStyle(div_str, style) {
var my_div = document.getElementById(div_str);
my_div.style.fontWeight = style;
}
function _setTextColor(div_str, color) {
var my_div = document.getElementById(div_str);
my_div.style.color = color;
}
function _nextLine(div_str) {
var my_br = document.createElement("br");
var my_div = document.getElementById(div_str);
my_div.appendChild(my_br);
}
function _setTimeout(div_str, sec) {
sec *= 1000;
setTimeout(function () {
jQuery(`#${div_str}`).toggle()
}, sec)
}
</script>
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreon.class.php | centreon/www/class/centreon.class.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__ . '/centreonUser.class.php';
require_once __DIR__ . '/centreonGMT.class.php';
require_once __DIR__ . '/centreonLogAction.class.php';
require_once __DIR__ . '/centreonExternalCommand.class.php';
require_once __DIR__ . '/centreonBroker.class.php';
require_once __DIR__ . '/centreonHostgroups.class.php';
require_once __DIR__ . '/centreonDBInstance.class.php';
/**
* Class
*
* @class Centreon
* @description Class for load application Centreon
*/
class Centreon
{
/** @var */
public $Nagioscfg;
/** @var */
public $optGen;
/** @var */
public $informations;
/** @var */
public $redirectTo;
/** @var */
public $modules;
/** @var */
public $hooks;
// @var array : saved user's pagination filter value
/** @var */
public $historyPage;
// @var string : saved last page's file name
/** @var */
public $historyLastUrl;
// @var array : saved user's filters
/** @var */
public $historySearch;
/** @var */
public $historySearchService;
/** @var */
public $historySearchOutput;
/** @var */
public $historyLimit;
/** @var */
public $search_type_service;
/** @var */
public $search_type_host;
/** @var int */
public $poller = 0;
/** @var */
public $template;
/** @var */
public $hostgroup;
/** @var */
public $host_id;
/** @var */
public $host_group_search;
/** @var */
public $host_list_search;
/** @var CentreonUser */
public $user;
/** @var CentreonGMT */
public $CentreonGMT;
/** @var CentreonLogAction */
public $CentreonLogAction;
/** @var CentreonExternalCommand */
public $extCmd;
/**
* Centreon constructor
*
* @param array $userInfos User objects
*
* @throws PDOException
*/
public function __construct($userInfos)
{
global $pearDB;
// Get User informations
$this->user = new CentreonUser($userInfos);
// Get Local nagios.cfg file
$this->initNagiosCFG();
// Get general options
$this->initOptGen();
// Get general informations
$this->initInformations();
// Grab Modules
$this->creatModuleList();
// Grab Hooks
$this->initHooks();
// Create GMT object
$this->CentreonGMT = new CentreonGMT();
// Create LogAction object
$this->CentreonLogAction = new CentreonLogAction($this->user);
// Init External CMD object
$this->extCmd = new CentreonExternalCommand();
}
/**
* Create a list of all module installed into Centreon
*
* @throws PDOException
*/
public function creatModuleList(): void
{
$this->modules = [];
$query = 'SELECT `name` FROM `modules_informations`';
$dbResult = CentreonDBInstance::getDbCentreonInstance()->query($query);
while ($result = $dbResult->fetch()) {
$this->modules[$result['name']] = ['name' => $result['name'], 'gen' => false, 'license' => false];
if (is_dir('./modules/' . $result['name'] . '/generate_files/')) {
$this->modules[$result['name']]['gen'] = true;
}
}
$dbResult = null;
}
/**
* @return void
*/
public function initHooks(): void
{
$this->hooks = [];
foreach ($this->modules as $name => $parameters) {
$hookPaths = glob(_CENTREON_PATH_ . '/www/modules/' . $name . '/hooks/*.class.php');
foreach ($hookPaths as $hookPath) {
if (preg_match('/\/([^\/]+?)\.class\.php$/', $hookPath, $matches)) {
require_once $hookPath;
$explodedClassName = explode('_', $matches[1]);
$className = '';
foreach ($explodedClassName as $partClassName) {
$className .= ucfirst(strtolower($partClassName));
}
if (class_exists($className)) {
$hookName = '';
$counter = count($explodedClassName);
for ($i = 1; $i < $counter; $i++) {
$hookName .= ucfirst(strtolower($explodedClassName[$i]));
}
$hookMethods = get_class_methods($className);
foreach ($hookMethods as $hookMethod) {
$this->hooks[$hookName][$hookMethod][] = ['path' => $hookPath, 'class' => $className];
}
}
}
}
}
}
/**
* Create history list
*/
public function createHistory(): void
{
$this->historyPage = [];
$this->historyLastUrl = '';
$this->historySearch = [];
$this->historySearchService = [];
$this->historySearchOutput = [];
$this->historyLimit = [];
$this->search_type_service = 1;
$this->search_type_host = 1;
}
/**
* Initiate nagios option list
*
* @throws PDOException
*/
public function initNagiosCFG(): void
{
$this->Nagioscfg = [];
/*
* We don't check activate because we can a server without a engine on localhost running
* (but we order to get if we have one)
*/
$DBRESULT = CentreonDBInstance::getDbCentreonInstance()->query(
"SELECT illegal_object_name_chars, cfg_dir FROM cfg_nagios, nagios_server
WHERE nagios_server.id = cfg_nagios.nagios_server_id
AND nagios_server.localhost = '1'
ORDER BY cfg_nagios.nagios_activate
DESC LIMIT 1"
);
$this->Nagioscfg = $DBRESULT->fetch();
$DBRESULT = null;
}
/**
* Initiate general option list
*
* @throws PDOException
*/
public function initOptGen(): void
{
$this->optGen = [];
$DBRESULT = CentreonDBInstance::getDbCentreonInstance()->query('SELECT * FROM `options`');
while ($opt = $DBRESULT->fetch()) {
$this->optGen[$opt['key']] = $opt['value'];
}
$DBRESULT = null;
unset($opt);
}
/**
* Store centreon informations in session
*
* @throws PDOException
* @return void
*/
public function initInformations(): void
{
$this->informations = [];
$result = CentreonDBInstance::getDbCentreonInstance()->query('SELECT * FROM `informations`');
while ($row = $result->fetch()) {
$this->informations[$row['key']] = $row['value'];
}
}
/**
* Check illegal char defined into nagios.cfg file
*
* @param string $name The string to sanitize
*
* @throws PDOException
* @return string The string sanitized
*/
public function checkIllegalChar($name)
{
$DBRESULT = CentreonDBInstance::getDbCentreonInstance()->query('SELECT illegal_object_name_chars FROM cfg_nagios');
while ($data = $DBRESULT->fetchColumn()) {
$name = str_replace(str_split($data), '', $name);
}
$DBRESULT = null;
return $name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonVersion.class.php | centreon/www/class/centreonVersion.class.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
*
*/
/**
* Class
*
* @class CentreonVersion
*/
class CentreonVersion
{
/** @var CentreonDB */
private $db;
/** @var CentreonDB|null */
private $dbStorage;
/**
* CentreonVersion constructor
*
* @param CentreonDB $db
* @param CentreonDB|null $dbStorage
*/
public function __construct($db, $dbStorage = null)
{
$this->db = $db;
if (! is_null($dbStorage)) {
$this->dbStorage = $dbStorage;
}
}
/**
* Get Centreon core version
*
* @throws PDOException
* @return array
*/
public function getCore()
{
$data = [];
// Get version of the centreon-web
$query = 'SELECT i.value FROM informations i '
. 'WHERE i.key = "version"';
$result = $this->db->query($query);
if ($row = $result->fetch()) {
$data['centreon-web'] = $row['value'];
}
// Get version of the centreon-broker
$cmd = shell_exec('/usr/sbin/cbd -v');
if (preg_match('/^.*(\d+\.\d+\.\d+)$/m', $cmd, $matches)) {
$data['centreon-broker'] = $matches[1];
}
// Get version of the centreon-engine
$queryProgram = 'SELECT DISTINCT instance_id, version AS program_version, engine AS program_name, '
. '`name` AS instance_name FROM instances WHERE deleted = 0 ';
$result = $this->dbStorage->query($queryProgram);
while ($info = $result->fetch()) {
$data['centreon-engine'] = $info['program_version'];
}
return $data;
}
/**
* Get all Centreon modules
*
* @throws PDOException
* @return array
*/
public function getModules()
{
$data = [];
$query = 'SELECT name, mod_release FROM modules_informations';
$result = $this->db->query($query);
while ($row = $result->fetch()) {
$data[$row['name']] = $row['mod_release'];
}
return $data;
}
/**
* Get all Centreon widgets
*
* @throws PDOException
* @return array
*/
public function getWidgets()
{
$data = [];
$query = 'SELECT title, version FROM widget_models';
$result = $this->db->query($query);
while ($row = $result->fetch()) {
$data[$row['title']] = $row['version'];
}
return $data;
}
/**
* Get versions of the system processus
*
* @throws PDOException
* @return array
*/
public function getSystem()
{
$data = ['OS' => php_uname()];
$query = 'SHOW VARIABLES LIKE "version"';
$result = $this->db->query($query);
if ($row = $result->fetch()) {
$data['mysql'] = $row['Value'];
}
return array_merge($data, $this->getVersionSystem());
}
/**
* get system information
*
* @return array $data An array composed with the name and version of the OS
*/
public function getVersionSystem()
{
$data = [];
if (is_readable('/etc/os-release')) {
$osRelease = parse_ini_file('/etc/os-release', false, INI_SCANNER_RAW) ?: [];
if (isset($osRelease['NAME'])) {
$data['OS_name'] = $osRelease['NAME'];
}
if (isset($osRelease['VERSION_ID'])) {
$data['OS_version'] = $osRelease['VERSION_ID'];
}
}
return $data;
}
/**
* Get all Centreon widgets
*
* @throws PDOException
* @return array $data Widgets statistics
*/
public function getWidgetsUsage()
{
$data = [];
$query = 'SELECT wm.title AS name, version, COUNT(widget_id) AS count
FROM widgets AS w
INNER JOIN widget_models AS wm ON (w.widget_model_id = wm.widget_model_id)
GROUP BY name, version';
$result = $this->db->query($query);
while ($row = $result->fetch()) {
$data[] = ['name' => $row['name'], 'version' => $row['version'], 'used' => $row['count']];
}
return $data;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonCfgWriter.class.php | centreon/www/class/centreonCfgWriter.class.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
*
*/
/**
* Class
*
* @class CentreonCfgWriter
* @description Class that allows to write Nagios configuration files
*/
class CentreonCfgWriter
{
/** @var string */
private $buffer = '';
/** @var CentreonXML */
private $xmlBuffer;
/** @var Centreon */
private $centreon;
/** @var string */
private $file_path;
/**
* CentreonCfgWriter constructor
*
* @param Centreon $centreon
* @param string $file_full_path
* @return void
*/
public function __construct($centreon, $file_full_path)
{
$this->centreon = $centreon;
$this->xmlBuffer = new CentreonXML();
$this->file_path = $file_full_path;
}
/**
* Defines cfg type
*
* @param string $type
* @return void
*/
public function startCfg($type): void
{
$this->writeText('define ' . $type . "{\n");
$this->xmlBuffer->startElement($type);
}
/**
* Ends cfg
*
* @return void
*/
public function endCfg(): void
{
$this->writeText("\t}\n\n");
$this->xmlBuffer->endElement();
}
/**
* Sets attributes
*
* @param string $key
* @param string $value
* @return void
*/
public function attribute($key, $value): void
{
$len = strlen($key);
if ($len <= 9) {
$this->writeText("\t" . $key . "\t\t\t\t" . $value . "\n");
} elseif ($len > 9 && $len <= 18) {
$this->writeText("\t" . $key . "\t\t\t" . $value . "\n");
} elseif ($len >= 19 && $len <= 27) {
$this->writeText("\t" . $key . "\t\t" . $value . "\n");
} elseif ($len > 27) {
$this->writeText("\t" . $key . "\t" . $value . "\n");
}
$this->xmlBuffer->writeElement($key, $value);
}
/**
* Writes in file
*
* @return void
*/
public function createCfgFile(): void
{
file_put_contents($this->file_path, $this->buffer);
}
/**
* Returns XML format
*
* @return CentreonXML
*/
public function getXML()
{
return $this->xmlBuffer;
}
/**
* Creates the file
*
* @return void
*/
protected function createFile()
{
$this->createFileHeader();
}
/**
* Writes basic text line to buffer
* Returns the length of written text
*
* @param string $text
*
* @return int
*/
protected function writeText($text)
{
$this->buffer .= $text;
return strlen($text);
}
/**
* Inserts Header of the file
*
* @return void
*/
protected function createFileHeader()
{
$time = date('F j, Y, g:i a');
$by = $this->centreon->user->get_name();
$len = $this->writeText("###################################################################\n");
$this->writeText("# #\n");
$this->writeText("# GENERATED BY CENTREON #\n");
$this->writeText("# #\n");
$this->writeText("# Developped by : #\n");
$this->writeText("# - Julien Mathis #\n");
$this->writeText("# - Romain Le Merlus #\n");
$this->writeText("# #\n");
$this->writeText("# www.centreon.com #\n");
$this->writeText("# For information : contact@centreon.com #\n");
$this->writeText("###################################################################\n");
$this->writeText("# #\n");
$this->writeText('# Last modification ' . $time);
$margin = strlen($time);
$margin = $len - 28 - $margin - 2;
for ($i = 0; $i != $margin; $i++) {
$this->writeText(' ');
}
$this->writeText("#\n");
$this->writeText('# By ' . $by);
$margin = $len - 13 - strlen($by) - 2;
for ($i = 0; $i != $margin; $i++) {
$this->writeText(' ');
}
$this->writeText("#\n");
$this->writeText("# #\n");
$this->writeText("###################################################################\n\n");
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonAuth.class.php | centreon/www/class/centreonAuth.class.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 Pimple\Container;
require_once __DIR__ . '/centreonContact.class.php';
require_once __DIR__ . '/centreonAuth.LDAP.class.php';
/**
* Class
*
* @class CentreonAuth
*/
class CentreonAuth
{
/**
* The default page has to be Resources status
*/
public const DEFAULT_PAGE = 200;
public const PWS_OCCULTATION = '******';
public const AUTOLOGIN_ENABLE = 1;
public const AUTOLOGIN_DISABLE = 0;
public const PASSWORD_HASH_ALGORITHM = PASSWORD_BCRYPT;
public const PASSWORD_VALID = 1;
public const PASSWORD_INVALID = 0;
public const PASSWORD_CANNOT_BE_VERIFIED = -1;
public const ENCRYPT_MD5 = 1;
public const ENCRYPT_SHA1 = 2;
public const AUTH_TYPE_LOCAL = 'local';
public const AUTH_TYPE_LDAP = 'ldap';
// Declare Values
/** @var array */
public $userInfos;
// Flags
/** @var */
public $passwdOk;
/** @var string */
protected $login;
/** @var string */
protected $password;
/** @var */
protected $enable;
/** @var */
protected $userExists;
/** @var int */
protected $cryptEngine;
/** @var int */
protected $autologin;
/** @var string[] */
protected $cryptPossibilities = ['MD5', 'SHA1'];
/** @var CentreonDB */
protected $pearDB;
/** @var int */
protected $debug;
/** @var Container */
protected $dependencyInjector;
/** @var */
protected $authType;
/** @var array */
protected $ldap_auto_import = [];
/** @var array */
protected $ldap_store_password = [];
/** @var int */
protected $default_page = self::DEFAULT_PAGE;
// keep log class
/** @var CentreonUserLog */
protected $CentreonLog;
// Error Message
/** @var */
protected $error;
/**
* CentreonAuth constructor
*
* @param Container $dependencyInjector
* @param string $username
* @param string $password
* @param int $autologin
* @param CentreonDB $pearDB
* @param CentreonUserLog $CentreonLog
* @param int $encryptType
* @param string $token | for autologin
*
* @throws PDOException
*/
public function __construct(
$dependencyInjector,
$username,
$password,
$autologin,
$pearDB,
$CentreonLog,
$encryptType = self::ENCRYPT_MD5,
$token = '',
) {
$this->dependencyInjector = $dependencyInjector;
$this->CentreonLog = $CentreonLog;
$this->login = $username;
$this->password = $password;
$this->pearDB = $pearDB;
$this->autologin = $autologin;
$this->cryptEngine = $encryptType;
$this->debug = $this->getLogFlag();
$res = $pearDB->query(
'SELECT ar.ar_id, ari.ari_value, ari.ari_name '
. 'FROM auth_ressource_info ari, auth_ressource ar '
. "WHERE ari_name IN ('ldap_auto_import', 'ldap_store_password') "
. 'AND ari.ar_id = ar.ar_id '
. "AND ar.ar_enable = '1'"
);
while ($row = $res->fetch()) {
if ($row['ari_name'] == 'ldap_auto_import' && $row['ari_value']) {
$this->ldap_auto_import[$row['ar_id']] = $row['ari_value'];
} elseif ($row['ari_name'] == 'ldap_store_password') {
$this->ldap_store_password[$row['ar_id']] = $row['ari_value'];
}
}
$this->checkUser($username, $password, $token);
}
/**
* Log enabled
*
* @throws PDOException
* @return int
*/
protected function getLogFlag()
{
$res = $this->pearDB->query("SELECT value FROM options WHERE `key` = 'debug_auth'");
$data = $res->fetch();
return $data['value'] ?? 0;
}
/**
* Check if password is ok
*
* @param string $password
* @param string $token
* @param bool $autoImport
*
* @throws PDOException
* @return void
*/
protected function checkPassword($password, $token = '', $autoImport = false)
{
if (empty($password) && empty($token)) {
$this->passwdOk = self::PASSWORD_INVALID;
return;
}
if ($this->autologin) {
$this->checkAutologinKey($password, $token);
return;
}
if ($this->userInfos['contact_auth_type'] === self::AUTH_TYPE_LDAP) {
$this->checkLdapPassword($password, $autoImport);
return;
}
if (
empty($this->userInfos['contact_auth_type'])
|| $this->userInfos['contact_auth_type'] === self::AUTH_TYPE_LOCAL
) {
$this->checkLocalPassword($password);
return;
}
$this->passwdOk = self::PASSWORD_INVALID;
}
/**
* Check user password
*
* @param string $username
* @param string $password
* @param string $token
*
* @throws PDOException
* @return void
*/
protected function checkUser($username, $password, $token)
{
if ($this->autologin == 0 || ($this->autologin && $token != '')) {
$dbResult = $this->pearDB->prepare(
"SELECT `contact`.*, `contact_password`.`password` AS `contact_passwd` FROM `contact`
LEFT JOIN `contact_password` ON `contact_password`.`contact_id` = `contact`.`contact_id`
WHERE `contact_alias` = :contactAlias
AND `contact_activate` = '1' AND `contact_register` = '1'
ORDER BY contact_password.creation_date DESC LIMIT 1"
);
$dbResult->bindValue(':contactAlias', $username, PDO::PARAM_STR);
$dbResult->execute();
} else {
$dbResult = $this->pearDB->query(
'SELECT * FROM `contact` '
. "WHERE MD5(contact_alias) = '" . $this->pearDB->escape($username, true) . "'"
. "AND `contact_activate` = '1' AND `contact_register` = '1' LIMIT 1"
);
}
if ($dbResult->rowCount()) {
$this->userInfos = $dbResult->fetch();
if ($this->userInfos['default_page']) {
$statement = $this->pearDB->prepare(
'SELECT topology_url_opt FROM topology WHERE topology_page = :topology_page'
);
$statement->bindValue(':topology_page', (int) $this->userInfos['default_page'], PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount()) {
$data = $statement->fetch(PDO::FETCH_ASSOC);
$this->userInfos['default_page'] .= $data['topology_url_opt'];
}
}
// Check password matching
$this->checkPassword($password, $token);
if ($this->passwdOk == self::PASSWORD_VALID) {
$this->CentreonLog->setUID($this->userInfos['contact_id']);
$this->CentreonLog->insertLog(
CentreonUserLog::TYPE_LOGIN,
'[' . self::AUTH_TYPE_LOCAL . '] [' . $_SERVER['REMOTE_ADDR'] . '] '
. "Authentication succeeded for '" . $username . "'"
);
} else {
$this->setAuthenticationError(
$this->userInfos['contact_auth_type'],
$username,
'invalid credentials'
);
}
} elseif (count($this->ldap_auto_import)) {
// Add temporary userinfo auth_type
$this->userInfos['contact_alias'] = $username;
$this->userInfos['contact_auth_type'] = self::AUTH_TYPE_LDAP;
$this->userInfos['contact_email'] = '';
$this->userInfos['contact_pager'] = '';
$this->checkPassword($password, '', true);
// Reset userInfos with imported information
$statement = $this->pearDB->prepare(
'SELECT * FROM `contact` '
. 'WHERE `contact_alias` = :contact_alias '
. "AND `contact_activate` = '1' AND `contact_register` = '1' LIMIT 1"
);
$statement->bindValue(':contact_alias', $this->pearDB->escape($username, true), PDO::PARAM_STR);
$statement->execute();
if ($statement->rowCount()) {
$this->userInfos = $statement->fetch(PDO::FETCH_ASSOC);
if ($this->userInfos['default_page']) {
$statement = $this->pearDB->prepare(
'SELECT topology_url_opt FROM topology WHERE topology_page = :topology_page'
);
$statement->bindValue(':topology_page', (int) $this->userInfos['default_page'], PDO::PARAM_INT);
$statement->execute();
if ($statement->rowCount()) {
$data = $statement->fetch(PDO::FETCH_ASSOC);
$this->userInfos['default_page'] .= $data['topology_url_opt'];
}
}
} else {
$this->setAuthenticationError(self::AUTH_TYPE_LDAP, $username, 'not found');
}
} else {
$this->setAuthenticationError(self::AUTH_TYPE_LOCAL, $username, 'not found');
}
}
/**
* Crypt String
* @param $str
*
* @return mixed
*/
protected function myCrypt($str)
{
$algo = $this->dependencyInjector['utils']->detectPassPattern($str);
if (! $algo) {
switch ($this->cryptEngine) {
case 1:
return $this->dependencyInjector['utils']->encodePass($str, 'md5');
case 2:
return $this->dependencyInjector['utils']->encodePass($str, 'sha1');
default:
return $this->dependencyInjector['utils']->encodePass($str, 'md5');
}
} else {
return $str;
}
}
/**
* @return int
*/
protected function getCryptEngine()
{
return $this->cryptEngine;
}
/**
* @return mixed
*/
protected function userExists()
{
return $this->userExists;
}
/**
* @return mixed
*/
protected function userIsEnable()
{
return $this->enable;
}
/**
* @return mixed
*/
protected function passwordIsOk()
{
return $this->passwdOk;
}
/**
* @return mixed
*/
protected function getAuthType()
{
return $this->authType;
}
/**
* Check autologin key
*
* @param string $password
* @param string $token
*/
private function checkAutologinKey($password, $token): void
{
if (
array_key_exists('contact_oreon', $this->userInfos)
&& $this->userInfos['contact_oreon'] !== '1'
) {
$this->passwdOk = self::PASSWORD_INVALID;
return;
}
if (
! empty($this->userInfos['contact_autologin_key'])
&& $this->userInfos['contact_autologin_key'] === $token
) {
$this->passwdOk = self::PASSWORD_VALID;
} elseif (
! empty($password)
&& $this->userInfos['contact_passwd'] === $password
) {
$this->passwdOk = self::PASSWORD_VALID;
} else {
$this->passwdOk = self::PASSWORD_INVALID;
}
}
/**
* Check ldap user password
*
* @param string $password
* @param bool $autoImport
*
* @throws PDOException
*/
private function checkLdapPassword($password, $autoImport): void
{
$res = $this->pearDB->query("SELECT ar_id FROM auth_ressource WHERE ar_enable = '1'");
$authResources = [];
while ($row = $res->fetch()) {
$index = $row['ar_id'];
if (isset($this->userInfos['ar_id']) && $this->userInfos['ar_id'] == $row['ar_id']) {
$index = 0;
}
$authResources[$index] = $row['ar_id'];
}
foreach ($authResources as $arId) {
if ($autoImport && ! isset($this->ldap_auto_import[$arId])) {
break;
}
if ($this->passwdOk == self::PASSWORD_VALID) {
break;
}
$authLDAP = new CentreonAuthLDAP(
$this->pearDB,
$this->CentreonLog,
$this->login,
$this->password,
$this->userInfos,
$arId
);
$this->passwdOk = $authLDAP->checkPassword();
if ($this->passwdOk == self::PASSWORD_VALID) {
if (isset($this->ldap_store_password[$arId]) && $this->ldap_store_password[$arId]) {
if (! isset($this->userInfos['contact_passwd'])) {
$hashedPassword = password_hash($this->password, self::PASSWORD_HASH_ALGORITHM);
$contact = new CentreonContact($this->pearDB);
$contactId = $contact->findContactIdByAlias($this->login);
if ($contactId !== null) {
$contact->addPasswordByContactId($contactId, $hashedPassword);
}
// Update password if LDAP authentication is valid but password not up to date in Centreon.
} elseif (! password_verify($this->password, $this->userInfos['contact_passwd'])) {
$hashedPassword = password_hash($this->password, self::PASSWORD_HASH_ALGORITHM);
$contact = new CentreonContact($this->pearDB);
$contactId = $contact->findContactIdByAlias($this->login);
if ($contactId !== null) {
$contact->replacePasswordByContactId(
$contactId,
$this->userInfos['contact_passwd'],
$hashedPassword
);
}
}
}
break;
}
}
if ($this->passwdOk == self::PASSWORD_CANNOT_BE_VERIFIED) {
if (
! empty($password)
&& ! empty($this->userInfos['contact_passwd'])
&& password_verify($password, $this->userInfos['contact_passwd'])
) {
$this->passwdOk = self::PASSWORD_VALID;
} else {
$this->passwdOk = self::PASSWORD_INVALID;
}
}
}
/**
* Check local user password
*
* @param string $password
*
* @throws PDOException
*/
private function checkLocalPassword($password): void
{
if (empty($password)) {
$this->passwdOk = self::PASSWORD_INVALID;
return;
}
if (password_verify($password, $this->userInfos['contact_passwd'])) {
$this->passwdOk = self::PASSWORD_VALID;
return;
}
if (
(
str_starts_with($this->userInfos['contact_passwd'], 'md5__')
&& $this->userInfos['contact_passwd'] === $this->myCrypt($password)
)
|| 'md5__' . $this->userInfos['contact_passwd'] === $this->myCrypt($password)
) {
$newPassword = password_hash($password, self::PASSWORD_HASH_ALGORITHM);
$statement = $this->pearDB->prepare(
'UPDATE `contact_password` SET password = :newPassword
WHERE password = :oldPassword AND contact_id = :contactId'
);
$statement->bindValue(':newPassword', $newPassword, PDO::PARAM_STR);
$statement->bindValue(':oldPassword', $this->userInfos['contact_passwd'], PDO::PARAM_STR);
$statement->bindValue(':contactId', $this->userInfos['contact_id'], PDO::PARAM_INT);
$statement->execute();
$this->passwdOk = self::PASSWORD_VALID;
return;
}
$this->passwdOk = self::PASSWORD_INVALID;
}
/**
* Set authentication error and log it
*
* @param string $authenticationType
* @param string|bool $username
* @param string $reason
*
* @return void
*/
private function setAuthenticationError(string $authenticationType, $username, string $reason): void
{
if (is_string($username) && strlen($username) > 0) {
// Take care before modifying this message pattern as it may break tools such as fail2ban
$this->CentreonLog->insertLog(
CentreonUserLog::TYPE_LOGIN,
'[' . $authenticationType . '] [' . $_SERVER['REMOTE_ADDR'] . '] '
. "Authentication failed for '" . $username . "' : " . $reason
);
}
$this->error = _('Your credentials are incorrect.');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonDuration.class.php | centreon/www/class/centreonDuration.class.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
*
*/
/**
* Class
*
* @class CentreonDuration
*/
class CentreonDuration
{
/**
* @param $duration
* @param $periods
*
* @return false|string
*/
public static function toString($duration, $periods = null)
{
if (! is_array($duration)) {
$duration = CentreonDuration::int2array($duration, $periods);
}
return CentreonDuration::array2string($duration);
}
/**
* @param $seconds
* @param $periods
*
* @return array|null
*/
public static function int2array($seconds, $periods = null)
{
// Define time periods
if (! is_array($periods)) {
$periods = ['y' => 31556926, 'M' => 2629743, 'w' => 604800, 'd' => 86400, 'h' => 3600, 'm' => 60, 's' => 1];
}
// Loop
$seconds = (int) $seconds;
foreach ($periods as $period => $value) {
$count = floor($seconds / $value);
if ($count == 0) {
continue;
}
$values[$period] = $count;
$seconds = $seconds % $value;
}
// Return
if ($values === []) {
$values = null;
}
return $values;
}
/**
* @param $duration
*
* @return false|string
*/
public static function array2string($duration)
{
if (! is_array($duration)) {
return false;
}
$i = 0;
foreach ($duration as $key => $value) {
if ($i < 2) {
$segment = $value . '' . $key;
$array[] = $segment;
$i++;
}
}
return implode(' ', $array);
}
}
/**
* Class
*
* @class DurationHoursMinutes
*/
class DurationHoursMinutes
{
/**
* @param $duration
* @param $periods
*
* @return false|string
*/
public static function toString($duration, $periods = null)
{
if (! is_array($duration)) {
$duration = DurationHoursMinutes::int2array($duration, $periods);
}
return DurationHoursMinutes::array2string($duration);
}
/**
* @param $seconds
* @param $periods
*
* @return array|null
*/
public static function int2array($seconds, $periods = null)
{
// Define time periods
if (! is_array($periods)) {
$periods = ['h' => 3600, 'm' => 60, 's' => 1];
}
// Loop
$seconds = (int) $seconds;
foreach ($periods as $period => $value) {
$count = floor($seconds / $value);
if ($count == 0) {
continue;
}
$values[$period] = $count;
$seconds = $seconds % $value;
}
// Return
if ($values === []) {
$values = null;
}
return $values;
}
/**
* @param $duration
*
* @return false|string
*/
public static function array2string($duration)
{
if (! is_array($duration)) {
return false;
}
foreach ($duration as $key => $value) {
$array[] = $value . '' . $key;
}
unset($segment);
return implode(' ', $array);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonLogAction.class.php | centreon/www/class/centreonLogAction.class.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__ . '/centreonAuth.class.php';
/**
* Class
*
* @class CentreonLogAction
*/
class CentreonLogAction
{
/**
* Const use to keep the changelog mechanism with hidden password values
*/
public const PASSWORD_BEFORE = '*******';
public const PASSWORD_AFTER = CentreonAuth::PWS_OCCULTATION;
/** @var CentreonUser */
protected $logUser;
/** @var array */
protected $uselessKey = [];
/**
* CentreonLogAction constructor
*
* @param CentreonUser $usr
*/
public function __construct($usr)
{
$this->logUser = $usr;
$this->uselessKey['submitA'] = 1;
$this->uselessKey['submitC'] = 1;
$this->uselessKey['o'] = 1;
$this->uselessKey['initialValues'] = 1;
$this->uselessKey['centreon_token'] = 1;
$this->uselessKey['resource'] = 1;
$this->uselessKey['plugins'] = 1;
}
/**
* @param string|int $logId
* @param array $fields
*
* @throws PDOException
* @return void
*/
public function insertFieldsNameValue($logId, $fields): void
{
global $pearDBO;
$query = 'INSERT INTO `log_action_modification` (field_name, field_value, action_log_id) VALUES ';
$values = [];
$index = 0;
foreach ($fields as $field_key => $field_value) {
$values[] = '(:field_key_' . $index . ', :field_value_' . $index . ', :logId)';
$index++;
}
$query .= implode(', ', $values);
$statement = $pearDBO->prepare($query);
$index = 0;
foreach ($fields as $field_key => $field_value) {
$key = CentreonDB::escape($field_key);
$value = CentreonDB::escape($field_value);
$statement->bindValue(':field_key_' . $index, $key);
$statement->bindValue(':field_value_' . $index, $value);
$statement->bindValue(':logId', $logId, PDO::PARAM_INT);
$index++;
}
$statement->execute();
}
/**
* Inserts logs : add, delete or modification of an object
*
* @param $object_type
* @param $object_id
* @param $object_name
* @param $action_type
* @param $fields
*
* @throws PDOException
* @return void
*/
public function insertLog($object_type, $object_id, $object_name, $action_type, $fields = null): void
{
global $pearDBO;
// Check if audit log option is activated
$optLogs = $pearDBO->query('SELECT 1 AS REALTIME, audit_log_option FROM `config`');
$auditLog = $optLogs->fetchRow();
if (($auditLog) && ($auditLog['audit_log_option'] == '1')) {
$str_query = "INSERT INTO `log_action`
(action_log_date, object_type, object_id, object_name, action_type, log_contact_id)
VALUES ('" . time() . "', :object_type, :object_id, :object_name, :action_type, :user_id)";
$statement1 = $pearDBO->prepare($str_query);
$statement1->bindValue(':object_type', $object_type);
$statement1->bindValue(':object_id', $object_id, PDO::PARAM_INT);
$statement1->bindValue(':object_name', $object_name);
$statement1->bindValue(':action_type', $action_type);
$statement1->bindValue(':user_id', $this->logUser->user_id, PDO::PARAM_INT);
$statement1->execute();
$statement2 = $pearDBO->prepare('SELECT MAX(action_log_id) FROM `log_action`');
$statement2->execute();
$logId = $statement2->fetch(PDO::FETCH_ASSOC);
if ($fields) {
$this->insertFieldsNameValue($logId['MAX(action_log_id)'], $fields);
}
}
}
/**
* @param $id
*
* @throws PDOException
* @return mixed
*/
public function getContactname($id): mixed
{
global $pearDB;
$DBRESULT = $pearDB->prepare(
'SELECT contact_name FROM `contact` WHERE contact_id = :contact_id LIMIT 1'
);
$DBRESULT->bindValue(':contact_id', $id, PDO::PARAM_INT);
$DBRESULT->execute();
/** @var $name */
while ($data = $DBRESULT->fetch(PDO::FETCH_ASSOC)) {
$name = $data['contact_name'];
}
$DBRESULT->closeCursor();
return $name;
}
/**
* returns the list of actions ("create","delete","change","mass change", "enable", "disable")
*
* @param $id
* @param $object_type
*
* @throws PDOException
* @return array
*/
public function listAction($id, $object_type): array
{
global $pearDBO;
$list_actions = [];
$i = 0;
$statement = $pearDBO->prepare(
'SELECT *
FROM log_action
WHERE object_id =:id
AND object_type = :object_type ORDER BY action_log_date DESC'
);
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->bindValue(':object_type', $object_type);
$statement->execute();
while ($data = $statement->fetch(PDO::FETCH_ASSOC)) {
$list_actions[$i]['action_log_id'] = $data['action_log_id'];
$list_actions[$i]['action_log_date'] = date('Y/m/d H:i', $data['action_log_date']);
$list_actions[$i]['object_type'] = $data['object_type'];
$list_actions[$i]['object_id'] = $data['object_id'];
$list_actions[$i]['object_name'] = HtmlSanitizer::createFromString($data['object_name'])->sanitize()->getString();
$list_actions[$i]['action_type'] = $this->replaceActiontype($data['action_type']);
if ($data['log_contact_id'] != 0) {
$list_actions[$i]['log_contact_id'] = $this->getContactname($data['log_contact_id']);
} else {
$list_actions[$i]['log_contact_id'] = 'System';
}
$i++;
}
$statement->closeCursor();
unset($data);
return $list_actions;
}
/**
* returns list of host for this service
*
* @param $service_id
*
* @throws PDOException
* @return array|int
*/
public function getHostId($service_id): array|int
{
global $pearDBO;
// Get Hosts
$query = <<<'SQL'
SELECT a.action_log_id,
m.field_value
FROM log_action a
INNER JOIN log_action_modification m
ON m.action_log_id = a.action_log_id
WHERE object_id = :service_id
AND object_type = 'service'
AND (field_name = 'service_hPars' OR field_name = 'hostId')
AND field_value <> ''
ORDER BY action_log_date DESC
LIMIT 1
SQL;
$statement = $pearDBO->prepare($query);
$statement->bindValue(':service_id', $service_id, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetch(PDO::FETCH_ASSOC);
if (isset($info['field_value']) && $info['field_value'] != '') {
return ['h' => $info['field_value']];
}
// Get hostgroups
$query = "SELECT a.action_log_id, field_value
FROM log_action a, log_action_modification m
WHERE m.action_log_id = a.action_log_id
AND field_name LIKE 'service_hgPars'
AND object_id = :service_id
AND object_type = 'service'
AND field_value <> ''
ORDER BY action_log_date DESC
LIMIT 1";
$statement = $pearDBO->prepare($query);
$statement->bindValue(':service_id', $service_id, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetch(PDO::FETCH_ASSOC);
if (isset($info['field_value']) && $info['field_value'] != '') {
return ['hg' => $info['field_value']];
}
return -1;
}
/**
* @param $host_id
*
* @throws PDOException
* @return mixed
*/
public function getHostName($host_id): mixed
{
global $pearDB, $pearDBO;
$statement = $pearDB->prepare("SELECT host_name FROM host WHERE host_register = '1' AND host_id = :host_id");
$statement->bindValue(':host_id', $host_id, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetch(PDO::FETCH_ASSOC);
if (isset($info['host_name'])) {
return $info['host_name'];
}
$statement = $pearDBO->prepare(
<<<'SQL'
SELECT object_id,
object_name
FROM log_action
WHERE object_type = 'host'
AND object_id = :host_id
SQL
);
$statement->bindValue(':host_id', $host_id, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetch(PDO::FETCH_ASSOC);
if (isset($info['object_name'])) {
return $info['object_name'];
}
$statement = $pearDBO->prepare('SELECT name FROM hosts WHERE host_id = :host_id');
$statement->bindValue(':host_id', $host_id, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetch(PDO::FETCH_ASSOC);
return $info['name'] ?? -1;
}
/**
* @param $hg_id
*
* @throws PDOException
* @return mixed
*/
public function getHostGroupName($hg_id): mixed
{
global $pearDB, $pearDBO;
$query = 'SELECT hg_name FROM hostgroup WHERE hg_id = :hg_id';
$DBRESULT2 = $pearDB->prepare($query);
$DBRESULT2->bindValue(':hg_id', $hg_id, PDO::PARAM_INT);
$DBRESULT2->execute();
$info = $DBRESULT2->fetch(PDO::FETCH_ASSOC);
if (isset($info['hg_name'])) {
return $info['hg_name'];
}
$query = "SELECT object_id, object_name FROM log_action WHERE object_type = 'service' AND object_id = :hg_id";
$DBRESULT2 = $pearDBO->prepare($query);
$DBRESULT2->bindValue(':hg_id', $hg_id, PDO::PARAM_INT);
$DBRESULT2->execute();
$info = $DBRESULT2->fetch(PDO::FETCH_ASSOC);
return $info['object_name'] ?? -1;
}
/**
* returns list of modifications
*
* @param int $id
* @param string $objectType
*
* @throws PDOException
* @return array
*/
public function listModification(int $id, string $objectType): array
{
global $pearDBO;
$list_modifications = [];
$ref = [];
$i = 0;
$objectType = HtmlAnalyzer::sanitizeAndRemoveTags($objectType);
$statement1 = $pearDBO->prepare('
SELECT action_log_id, action_log_date, action_type FROM log_action
WHERE object_id = :object_id
AND object_type = :object_type ORDER BY action_log_date ASC
');
$statement1->bindValue(':object_id', $id, PDO::PARAM_INT);
$statement1->bindValue(':object_type', $objectType);
$statement1->execute();
while ($row = $statement1->fetch(PDO::FETCH_ASSOC)) {
$DBRESULT2 = $pearDBO->prepare(
'SELECT action_log_id,field_name,field_value
FROM `log_action_modification`
WHERE action_log_id = :action_log_id'
);
$DBRESULT2->bindValue(':action_log_id', $row['action_log_id'], PDO::PARAM_INT);
$DBRESULT2->execute();
$macroPasswordStatement = $pearDBO->prepare(
"SELECT field_value
FROM `log_action_modification`
WHERE action_log_id = :action_log_id
AND field_name = 'refMacroPassword'"
);
$macroPasswordStatement->bindValue(':action_log_id', $row['action_log_id'], PDO::PARAM_INT);
$macroPasswordStatement->execute();
$macroPasswordRef = [];
if ($result = $macroPasswordStatement->fetch(PDO::FETCH_ASSOC)) {
$macroPasswordRef = explode(',', $result['field_value']);
}
while ($field = $DBRESULT2->fetch(PDO::FETCH_ASSOC)) {
switch ($field['field_name']) {
case 'macroValue':
/*
* explode the macroValue string to easily change any password to ****** on the "After" part
* of the changeLog
*/
$macroValueArray = explode(',', $field['field_value']);
foreach ($macroPasswordRef as $macroIdPassword) {
if (! empty($macroValueArray[$macroIdPassword])) {
$macroValueArray[$macroIdPassword] = self::PASSWORD_AFTER;
}
}
$field['field_value'] = implode(',', $macroValueArray);
/*
* change any password to ****** on the "Before" part of the changeLog
* and don't change anything if the 'macroValue' string only contains commas
*/
if (
isset($ref[$field['field_name']])
&& ! empty(str_replace(',', '', $ref[$field['field_name']]))
) {
foreach ($macroPasswordRef as $macroIdPassword) {
$macroValueArray[$macroIdPassword] = self::PASSWORD_BEFORE;
}
$ref[$field['field_name']] = implode(',', $macroValueArray);
}
break;
case 'contact_passwd':
case 'contact_passwd2':
$field['field_value'] = self::PASSWORD_AFTER;
if (isset($ref[$field['field_name']])) {
$ref[$field['field_name']] = self::PASSWORD_BEFORE;
}
}
if (! isset($ref[$field['field_name']]) && $field['field_value'] != '') {
$list_modifications[$i]['action_log_id'] = $field['action_log_id'];
$list_modifications[$i]['field_name'] = $field['field_name'];
$list_modifications[$i]['field_value_before'] = '';
$list_modifications[$i]['field_value_after'] = $field['field_value'];
foreach ($macroPasswordRef as $macroPasswordId) {
// handle the display modification for the fields macroOldValue_n while nothing was set before
if (str_contains($field['field_name'], 'macroOldValue_' . $macroPasswordId)) {
$list_modifications[$i]['field_value_after'] = self::PASSWORD_AFTER;
}
}
} elseif (isset($ref[$field['field_name']]) && $ref[$field['field_name']] != $field['field_value']) {
$list_modifications[$i]['action_log_id'] = $field['action_log_id'];
$list_modifications[$i]['field_name'] = $field['field_name'];
$list_modifications[$i]['field_value_before'] = $ref[$field['field_name']];
$list_modifications[$i]['field_value_after'] = $field['field_value'];
foreach ($macroPasswordRef as $macroPasswordId) {
// handle the display modification for the fields macroOldValue_n for "Before" and "After" value
if (str_contains($field['field_name'], 'macroOldValue_' . $macroPasswordId)) {
$list_modifications[$i]['field_value_before'] = self::PASSWORD_BEFORE;
$list_modifications[$i]['field_value_after'] = self::PASSWORD_AFTER;
}
}
}
$ref[$field['field_name']] = $field['field_value'];
$i++;
}
}
return $list_modifications;
}
/**
* Display clear action labels
*
* @param string $action
*
* @return mixed
*/
public function replaceActiontype($action): mixed
{
$actionList = [];
$actionList['d'] = 'Delete';
$actionList['c'] = 'Change';
$actionList['a'] = 'Create';
$actionList['disable'] = 'Disable';
$actionList['enable'] = 'Enable';
$actionList['mc'] = 'Mass change';
foreach ($actionList as $key => $value) {
if ($action == $key) {
$action = $value;
}
}
return $action;
}
/**
* @return array
*/
public function listObjecttype(): array
{
return [
0 => _('All'),
1 => 'command',
2 => 'timeperiod',
3 => 'contact',
4 => 'contactgroup',
5 => 'host',
6 => 'hostgroup',
7 => 'service',
8 => 'servicegroup',
9 => 'traps',
10 => 'escalation',
11 => 'host dependency',
12 => 'hostgroup dependency',
13 => 'service dependency',
14 => 'servicegroup dependency',
15 => 'poller',
16 => 'engine',
17 => 'broker',
18 => 'resources',
19 => 'meta',
20 => 'access group',
21 => 'menu access',
22 => 'resource access',
23 => 'action access',
24 => 'manufacturer',
25 => 'hostcategories',
];
}
/**
* @param array $ret
*
* @return array
*/
public static function prepareChanges($ret): array
{
global $pearDB;
$uselessKey = [];
$uselessKey['submitA'] = 1;
$uselessKey['o'] = 1;
$uselessKey['initialValues'] = 1;
$uselessKey['centreon_token'] = 1;
if (! isset($ret)) {
return [];
}
$info = [];
$oldMacroPassword = [];
foreach ($ret as $key => $value) {
if (! isset($uselessKey[trim($key)])) {
if (is_array($value)) {
/*
* Set a new refMacroPassword value to be able to find which macro index is a password
* in the listModification method and hash password in log_action_modification table
*/
if ($key === 'macroValue' && isset($ret['macroPassword'])) {
foreach ($value as $macroId => $macroValue) {
if (array_key_exists($macroId, $ret['macroPassword'])) {
$info['refMacroPassword'] = implode(',', array_keys($ret['macroPassword']));
$value[$macroId] = md5($macroValue);
if (! empty($ret['macroOldValue_' . $macroId])) {
$oldMacroPassword['macroOldValue_' . $macroId] = md5(
$ret['macroOldValue_' . $macroId]
);
}
}
}
}
$info[$key] = $value[$key] ?? implode(',', $value);
} else {
$info[$key] = CentreonDB::escape($value);
}
}
}
foreach ($oldMacroPassword as $oldMacroPasswordName => $oldMacroPasswordValue) {
$info[$oldMacroPasswordName] = $oldMacroPasswordValue;
}
return $info;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonServicetemplates.class.php | centreon/www/class/centreonServicetemplates.class.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 _CENTREON_PATH_ . 'www/class/centreonService.class.php';
require_once _CENTREON_PATH_ . 'www/class/centreonInstance.class.php';
/**
* Class
*
* @class CentreonServicetemplates
* @description Class that contains various methods for managing services
*/
class CentreonServicetemplates extends CentreonService
{
/**
* Constructor
*
* @param CentreonDB $db
*
* @throws PDOException
*/
public function __construct($db)
{
parent::__construct($db);
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'service';
$parameters['currentObject']['id'] = 'service_id';
$parameters['currentObject']['name'] = 'service_description';
$parameters['currentObject']['comparator'] = 'service_id';
switch ($field) {
case 'service_hPars':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonHosttemplates';
$parameters['externalObject']['table'] = 'host';
$parameters['externalObject']['id'] = 'host_id';
$parameters['externalObject']['name'] = 'host_name';
$parameters['externalObject']['comparator'] = 'host_id';
$parameters['relationObject']['table'] = 'host_service_relation';
$parameters['relationObject']['field'] = 'host_host_id';
$parameters['relationObject']['comparator'] = 'service_service_id';
break;
default:
$parameters = parent::getDefaultValuesParameters($field);
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
* @param string $register
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [], $register = '1')
{
$serviceList = [];
if (isset($options['withHosttemplate']) && $options['withHosttemplate'] === true) {
$serviceList = parent::getObjectForSelect2($values, $options, '0');
} else {
$selectedServices = '';
$listValues = '';
$queryValues = [];
if (! empty($values)) {
foreach ($values as $k => $v) {
$listValues .= ':service' . $v . ',';
$queryValues['service' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
$selectedServices .= "AND s.service_id IN ({$listValues}) ";
}
$queryService = 'SELECT DISTINCT s.service_id, s.service_description FROM service s '
. 'WHERE s.service_register = "0" ' . $selectedServices . 'ORDER BY s.service_description ';
$stmt = $this->db->prepare($queryService);
if ($queryValues !== []) {
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
}
$stmt->execute();
while ($data = $stmt->fetch()) {
$serviceList[] = ['id' => $data['service_id'], 'text' => $data['service_description']];
}
}
return $serviceList;
}
/**
* @param $serviceTemplateName
* @param bool $checkTemplates
* @throws Exception
* @return array
*/
public function getLinkedServicesByName($serviceTemplateName, $checkTemplates = true)
{
$register = $checkTemplates ? 0 : 1;
$linkedServices = [];
$query = 'SELECT DISTINCT s.service_description '
. 'FROM service s, service st '
. 'WHERE s.service_template_model_stm_id = st.service_id '
. 'AND st.service_register = "0" '
. 'AND s.service_register = "' . $register . '" '
. 'AND st.service_description = "' . $this->db->escape($serviceTemplateName) . '" ';
try {
$result = $this->db->query($query);
} catch (PDOException $e) {
throw new Exception('Error while getting linked services of ' . $serviceTemplateName);
}
while ($row = $result->fetchRow()) {
$linkedServices[] = $row['service_description'];
}
return $linkedServices;
}
/**
* @param string $serviceTemplateName linked service template
* @param string $hostTemplateName linked host template
*
* @throws PDOException
* @return array service ids
*/
public function getServiceIdsLinkedToSTAndCreatedByHT($serviceTemplateName, $hostTemplateName)
{
$serviceIds = [];
$query = 'SELECT DISTINCT(s.service_id) '
. 'FROM service s, service st, host h, host ht, host_service_relation hsr, host_service_relation hsrt,'
. ' host_template_relation htr '
. 'WHERE st.service_description = "' . $this->db->escape($serviceTemplateName) . '" '
. 'AND s.service_template_model_stm_id = st.service_id '
. 'AND st.service_id = hsrt.service_service_id '
. 'AND hsrt.host_host_id = ht.host_id '
. 'AND ht.host_name = "' . $this->db->escape($hostTemplateName) . '" '
. 'AND ht.host_id = htr.host_tpl_id '
. 'AND htr.host_host_id = h.host_id '
. 'AND h.host_id = hsr.host_host_id '
. 'AND hsr.service_service_id = s.service_id '
. 'AND s.service_register = "1" ';
$result = $this->db->query($query);
while ($row = $result->fetchRow()) {
$serviceIds[] = $row['service_id'];
}
return $serviceIds;
}
/**
* @param bool $enable
*
* @return array
*/
public function getList($enable = false)
{
$serviceTemplates = [];
$query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT service_id, service_description '
. 'FROM service '
. "WHERE service_register = '0' ";
if ($enable) {
$query .= "AND service_activate = '1' ";
}
$query .= 'ORDER BY service_description ';
try {
$res = $this->db->query($query);
} catch (PDOException $e) {
return [];
}
$serviceTemplates = [];
while ($row = $res->fetchRow()) {
$serviceTemplates[$row['service_id']] = $row['service_description'];
}
return $serviceTemplates;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonPdoStatement.php | centreon/www/class/centreonPdoStatement.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
*
*/
/**
* Class
*
* @class CentreonPdoStatement
*/
class CentreonPdoStatement extends PDOStatement
{
/** @var CentreonDB */
public $dbh;
/**
* CentreonPdoStatement constructor
*
* @param CentreonDB $dbh
*/
protected function __construct($dbh)
{
$this->dbh = $dbh;
}
/**
* @return mixed
*/
public function fetchRow()
{
return $this->fetch();
}
/**
* @return int
*/
public function numRows()
{
return $this->rowCount();
}
/**
* @return void
*/
public function free()
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonContactgroup.class.php | centreon/www/class/centreonContactgroup.class.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__ . '/centreonLDAP.class.php');
require_once realpath(__DIR__ . '/centreonACL.class.php');
/**
* Class
*
* @class CentreonContactgroup
*/
class CentreonContactgroup
{
/** @var CentreonDB */
private $db;
/**
* CentreonContactgroup constructor
*
* @param CentreonDB $pearDB
*/
public function __construct($pearDB)
{
$this->db = $pearDB;
}
/**
* Get the list of contactgroups with its id, or its name for a ldap groups if isn't sync in database
*
* @param bool $withLdap if include LDAP group
* @param bool $dbOnly | will not return ldap groups that are not stored in db
*
* @throws PDOException
* @return array
*/
public function getListContactgroup($withLdap = false, $dbOnly = false)
{
// Contactgroup from database
$contactgroups = [];
$query = 'SELECT a.cg_id, a.cg_name, a.cg_ldap_dn, b.ar_name FROM contactgroup a ';
$query .= ' LEFT JOIN auth_ressource b ON a.ar_id = b.ar_id';
if ($withLdap === false) {
$query .= " WHERE a.cg_type != 'ldap'";
}
$query .= ' ORDER BY a.cg_name';
$res = $this->db->query($query);
while ($contactgroup = $res->fetch()) {
$contactgroups[$contactgroup['cg_id']] = $contactgroup['cg_name'];
if ($withLdap && isset($contactgroup['cg_ldap_dn']) && $contactgroup['cg_ldap_dn'] != '') {
$contactgroups[$contactgroup['cg_id']] = $this->formatLdapContactgroupName(
$contactgroup['cg_name'],
$contactgroup['ar_name']
);
}
}
$res->closeCursor();
// Get ldap contactgroups
if ($withLdap && $dbOnly === false) {
$ldapContactgroups = $this->getLdapContactgroups();
$contactgroupNames = array_values($contactgroups);
foreach ($ldapContactgroups as $id => $name) {
if (! in_array($name, $contactgroupNames)) {
$contactgroups[$id] = $name;
}
}
}
return $contactgroups;
}
/**
* Get the list of ldap contactgroups
*
* @param string $filter
*
* @throws PDOException
* @return array
*/
public function getLdapContactgroups($filter = '')
{
$cgs = [];
$query = "SELECT `value` FROM `options` WHERE `key` = 'ldap_auth_enable'";
$res = $this->db->query($query);
$row = $res->fetch();
if ($row['value'] == 1) {
$query = "SELECT ar_id, ar_name FROM auth_ressource WHERE ar_enable = '1'";
$ldapRes = $this->db->query($query);
while ($ldapRow = $ldapRes->fetch()) {
$ldap = new CentreonLDAP($this->db, null, $ldapRow['ar_id']);
$ldap->connect();
$ldapGroups = $ldap->listOfGroups();
foreach ($ldapGroups as $ldapGroup) {
$ldapGroupName = $ldapGroup['name'];
if (
array_search($ldapGroupName . ' (LDAP : ' . $ldapRow['ar_name'] . ')', $cgs) === false
&& preg_match('/' . $filter . '/i', $ldapGroupName)
) {
$cgs['[' . $ldapRow['ar_id'] . ']' . $ldapGroupName] = $this->formatLdapContactgroupName(
$ldapGroupName,
$ldapRow['ar_name']
);
}
}
}
}
return $cgs;
}
/**
* format ldap contactgroup name
*
* @param string $cg_name : name of the ldap group name
* @param string $ldap_name : name of the ldap
*
* @return string
*/
public function formatLdapContactgroupName($cg_name, $ldap_name)
{
return $cg_name . ' (LDAP : ' . $ldap_name . ')';
}
/**
* Insert ldap group if does not exist
*
* @param int $ldapId
* @param string $name
* @param string $dn
*
* @throws PDOException
* @return int|null
*/
public function insertLdapGroupByNameAndDn(int $ldapId, string $name, string $dn): ?int
{
// Check if contactgroup is not in the database
$ldapGroupId = $this->findLdapGroupIdByName($ldapId, $name);
if ($ldapGroupId !== null) {
return $ldapGroupId;
}
$query = 'INSERT INTO contactgroup (cg_name, cg_alias, cg_activate, cg_type, cg_ldap_dn, ar_id) '
. "VALUES (:name, :name, '1', 'ldap', :dn, :ldapId)";
$statement = $this->db->prepare($query);
$statement->bindValue(':name', $name, PDO::PARAM_STR);
$statement->bindValue(':dn', $dn, PDO::PARAM_STR);
$statement->bindValue(':ldapId', $ldapId, PDO::PARAM_INT);
$statement->execute();
return $this->findLdapGroupIdByName($ldapId, $name);
}
/**
* Insert the ldap groups in table contactgroups
*
* @param string $cgName The ldap group name
*
* @throws PDOException
* @return int|null The contactgroup id or null if not found
*/
public function insertLdapGroup(string $cgName): ?int
{
// Parse contactgroup name
if (preg_match('/\[(\d+)\](.*)/', $cgName, $matches) === false) {
return 0;
}
$arId = (int) $matches[1];
$cgName = $matches[2];
// Check if contactgroup is not in the database
$ldapGroupId = $this->findLdapGroupIdByName($arId, $cgName);
if ($ldapGroupId !== null) {
return $ldapGroupId;
}
$ldap = new CentreonLDAP($this->db, null, $arId);
$ldap->connect();
$ldapDn = $ldap->findGroupDn($cgName);
// Reset ldap build cache time
$this->db->query('UPDATE options SET `value` = 0 WHERE `key` = "ldap_last_acl_update"');
if ($ldapDn !== false) {
$this->insertLdapGroupByNameAndDn($arId, $cgName, $ldapDn);
return $this->findLdapGroupIdByDn($arId, $ldapDn);
}
return null;
}
/**
* Optimized method to get better performance at config generation when LDAP have groups
* Useful to avoid calculating and refreshing configuration from LDAP when nothing has changed
*
* @throws PDOException
* @return array $msg array of error messages
*/
public function syncWithLdapConfigGen()
{
$msg = [];
$ldapServerConnError = [];
$cgRes = $this->db->query(
"SELECT cg.cg_id, cg.cg_name, cg.cg_ldap_dn, cg.ar_id, ar.ar_name
FROM contactgroup as cg, auth_ressource as ar
WHERE cg.cg_type = 'ldap'
AND cg.ar_id = ar.ar_id
AND ar.ar_enable = '1'
AND (
EXISTS (
SELECT 1 FROM contactgroup_host_relation chr WHERE chr.contactgroup_cg_id = cg.cg_id LIMIT 1
) OR EXISTS (
SELECT 1 FROM contactgroup_service_relation csr WHERE csr.contactgroup_cg_id = cg.cg_id LIMIT 1
) OR EXISTS (
SELECT 1 FROM contactgroup_hostgroup_relation chr WHERE chr.contactgroup_cg_id = cg.cg_id LIMIT 1
) OR EXISTS (
SELECT 1 FROM contactgroup_servicegroup_relation csr WHERE csr.contactgroup_cg_id = cg.cg_id LIMIT 1
) OR EXISTS (
SELECT 1 FROM escalation_contactgroup_relation ecr WHERE ecr.contactgroup_cg_id = cg.cg_id LIMIT 1
)
)
ORDER BY cg.ar_id"
);
$currentLdapId = 0; // the chosen LDAP configuration which should never stay to 0 if the LDAP is found
$ldapConn = null;
while ($cgRow = $cgRes->fetch()) {
if (isset($ldapServerConnError[$cgRow['ar_id']])) {
continue;
}
// if $currentLdapId == cgRow['ar_id'], then nothing has changed and we can skip the next operations
if ($currentLdapId != $cgRow['ar_id']) {
$currentLdapId = $cgRow['ar_id'];
if (! is_null($ldapConn)) {
$ldapConn->close();
}
$ldapConn = new CentreonLDAP($this->db, null, (int) $cgRow['ar_id']);
$connectionResult = $ldapConn->connect();
if ($connectionResult == false) {
$ldapServerConnError[$cgRow['ar_id']] = 1;
$msg[] = 'Unable to connect to LDAP server : ' . $cgRow['ar_name'] . '.';
continue;
}
}
// Refresh Users Groups by deleting old relations and inserting new ones if needed.
$this->db->query('DELETE FROM contactgroup_contact_relation '
. 'WHERE contactgroup_cg_id = ' . (int) $cgRow['cg_id']);
$members = $ldapConn->listUserForGroup($cgRow['cg_ldap_dn']);
$contact = '';
foreach ($members as $member) {
$contact .= $this->db->quote($member) . ',';
}
$contact = rtrim($contact, ',');
if (! $contact) {
// no need to continue. If there's no contact, there's no relation to insert.
$msg[] = "Error : there's no contact to update for LDAP : " . $cgRow['ar_name'] . '.';
return $msg;
}
try {
$resContact = $this->db->query('SELECT contact_id FROM contact '
. 'WHERE contact_ldap_dn IN (' . $contact . ')');
while ($rowContact = $resContact->fetch()) {
try {
// inserting the LDAP contactgroups relation between the cg and the user
$this->db->query('INSERT INTO contactgroup_contact_relation '
. '(contactgroup_cg_id, contact_contact_id) '
. 'VALUES (' . (int) $cgRow['cg_id'] . ', ' . (int) $rowContact['contact_id'] . ')');
} catch (PDOException $e) {
$stmt = $this->db->query('SELECT c.contact_name, cg_name FROM contact c '
. 'INNER JOIN contactgroup_contact_relation cgr ON cgr.contact_contact_id = c.contact_id '
. 'INNER JOIN contactgroup cg ON cg.cg_id = cgr.contactgroup_cg_id');
$res = $stmt->fetch();
$msg[] = 'Error inserting relation between contactgroup : ' . $res['cg_name']
. ' and contact : ' . $res['contact_name'] . '.';
}
}
} catch (PDOException $e) {
$msg[] = "Error in getting contact ID's list : " . $contact . ' from members.';
continue;
}
}
return $msg;
}
/**
* Synchronize with LDAP groups
*
* @throws PDOException
* @return array of error messages
*/
public function syncWithLdap()
{
$msg = [];
$ldapRes = $this->db->query(
"SELECT ar_id FROM auth_ressource WHERE ar_enable = '1'"
);
// Connect to LDAP Server
while ($ldapRow = $ldapRes->fetch()) {
$ldapConn = new CentreonLDAP($this->db, null, $ldapRow['ar_id']);
$connectionResult = $ldapConn->connect();
if ($connectionResult != false) {
$res = $this->db->prepare(
'SELECT cg_id, cg_name, cg_ldap_dn FROM contactgroup '
. "WHERE cg_type = 'ldap' AND ar_id = :arId"
);
$res->bindValue(':arId', $ldapRow['ar_id'], PDO::PARAM_INT);
$res->execute();
// insert groups from ldap into centreon
$registeredGroupsFromDB = $res->fetchAll();
$registeredGroups = [];
foreach ($registeredGroupsFromDB as $registeredGroupFromDB) {
$registeredGroups[] = $registeredGroupFromDB['cg_name'];
}
$ldapGroups = $ldapConn->listOfGroups();
foreach ($ldapGroups as $ldapGroup) {
if (! in_array($ldapGroup['name'], $registeredGroups)) {
$this->insertLdapGroupByNameAndDn(
(int) $ldapRow['ar_id'],
$ldapGroup['name'],
$ldapGroup['dn']
);
}
}
$res = $this->db->prepare(
'SELECT cg_id, cg_name, cg_ldap_dn FROM contactgroup '
. "WHERE cg_type = 'ldap' AND ar_id = :arId"
);
$res->bindValue(':arId', $ldapRow['ar_id'], PDO::PARAM_INT);
$res->execute();
$this->db->beginTransaction();
try {
while ($row = $res->fetch()) {
// Test is the group has not been moved or deleted in ldap
if ((empty($row['cg_ldap_dn']) || $ldapConn->getEntry($row['cg_ldap_dn']) === false)
&& ldap_errno($ldapConn->getDs()) != 3
) {
$dn = $ldapConn->findGroupDn($row['cg_name']);
if ($dn === false && ldap_errno($ldapConn->getDs()) != 3) {
// Delete the ldap group in contactgroup
try {
$stmt = $this->db->prepare(
'DELETE FROM contactgroup WHERE cg_id = :cgId'
);
$stmt->bindValue('cgId', $row['cg_id'], PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
$msg[] = 'Error processing delete contactgroup request of ldap group : '
. $row['cg_name'];
throw $e;
}
continue;
} // Update the ldap group dn in contactgroup
try {
$updateDnStatement = $this->db->prepare(
'UPDATE contactgroup SET cg_ldap_dn = :cg_dn WHERE cg_id = :cg_id'
);
$updateDnStatement->bindValue(':cg_dn', $dn, PDO::PARAM_STR);
$updateDnStatement->bindValue(':cg_id', $row['cg_id'], PDO::PARAM_INT);
$updateDnStatement->execute();
$row['cg_ldap_dn'] = $dn;
} catch (PDOException $e) {
$msg[] = 'Error processing update contactgroup request of ldap group : '
. $row['cg_name'];
throw $e;
}
}
$members = $ldapConn->listUserForGroup($row['cg_ldap_dn']);
// Refresh Users Groups.
$deleteStmt = $this->db->prepare(
'DELETE FROM contactgroup_contact_relation
WHERE contactgroup_cg_id = :cgId'
);
$deleteStmt->bindValue(':cgId', $row['cg_id'], PDO::PARAM_INT);
$deleteStmt->execute();
$contactDns = '';
foreach ($members as $member) {
$contactDns .= $this->db->quote($member) . ',';
}
$contactDns = rtrim($contactDns, ',');
if ($contactDns !== '') {
try {
$resContact = $this->db->query(
'SELECT contact_id FROM contact WHERE contact_ldap_dn IN (' . $contactDns . ')'
);
} catch (PDOException $e) {
$msg[] = 'Error in getting contact id from members.';
throw $e;
}
while ($rowContact = $resContact->fetch()) {
try {
$insertStmt = $this->db->prepare(
'INSERT INTO contactgroup_contact_relation
(contactgroup_cg_id, contact_contact_id)
VALUES (:cgId, :contactId)'
);
$insertStmt->bindValue(':cgId', $row['cg_id'], PDO::PARAM_INT);
$insertStmt->bindValue(':contactId', $rowContact['contact_id'], PDO::PARAM_INT);
$insertStmt->execute();
} catch (PDOException $e) {
$msg[] = 'Error insert relation between contactgroup ' . $row['cg_id']
. ' and contact ' . $rowContact['contact_id'];
throw $e;
}
}
}
}
$updateTime = $this->db->prepare(
"UPDATE `options` SET `value` = :currentTime
WHERE `key` = 'ldap_last_acl_update'"
);
$updateTime->bindValue(':currentTime', time(), PDO::PARAM_INT);
$updateTime->execute();
$this->db->commit();
} catch (PDOException $e) {
$this->db->rollBack();
}
} else {
$msg[] = 'Unable to connect to LDAP server.';
}
}
return $msg;
}
/**
* Get contact group name from contact group id
*
* @param int $cgId : The id of the contactgroup
* @throws Exception
* @return string
*/
public function getNameFromCgId($cgId)
{
$query = 'SELECT cg_name FROM contactgroup WHERE cg_id = ' . CentreonDB::escape($cgId) . ' LIMIT 1';
$res = $this->db->query($query);
if ($res->rowCount()) {
$row = $res->fetch();
return $row['cg_name'];
}
throw new Exception('No contact group name found');
}
/**
* Verify if ldap contactgroup as not the same name of a Centreon contactgroup
*
* @param array $listCgs The list of contactgroups to validate
* @return bool
*/
public static function verifiedExists($listCgs)
{
global $pearDB;
foreach ($listCgs as $cg) {
if (is_numeric($cg) === false) {
// Parse the name
if (preg_match('/\[(\d+)\](.*)/', $cg, $matches) === false) {
return false;
}
$cg_name = $matches[2];
// Query test if exists
$query = 'SELECT COUNT(*) as nb FROM contactgroup '
. "WHERE cg_name = '" . $pearDB->escape($cg_name) . "' AND cg_type != 'ldap' ";
try {
$res = $pearDB->query($query);
} catch (PDOException $e) {
return false;
}
$row = $res->fetch();
if ($row['nb'] != 0) {
return false;
}
}
}
return true;
}
/**
* @param int $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = [];
$parameters['currentObject']['table'] = 'contactgroup';
$parameters['currentObject']['id'] = 'cg_id';
$parameters['currentObject']['name'] = 'cg_name';
$parameters['currentObject']['comparator'] = 'cg_id';
switch ($field) {
case 'cg_contacts':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'contact';
$parameters['externalObject']['id'] = 'contact_id';
$parameters['externalObject']['name'] = 'contact_name';
$parameters['externalObject']['comparator'] = 'contact_id';
$parameters['relationObject']['table'] = 'contactgroup_contact_relation';
$parameters['relationObject']['field'] = 'contact_contact_id';
$parameters['relationObject']['comparator'] = 'contactgroup_cg_id';
break;
case 'cg_acl_groups':
$parameters['type'] = 'relation';
$parameters['externalObject']['table'] = 'acl_groups';
$parameters['externalObject']['id'] = 'acl_group_id';
$parameters['externalObject']['name'] = 'acl_group_name';
$parameters['externalObject']['comparator'] = 'acl_group_id';
$parameters['relationObject']['table'] = 'acl_group_contactgroups_relations';
$parameters['relationObject']['field'] = 'acl_group_id';
$parameters['relationObject']['comparator'] = 'cg_cg_id';
break;
}
return $parameters;
}
/**
* @param array $values
* @param array $options
*
* @throws PDOException
* @return array
*/
public function getObjectForSelect2($values = [], $options = [])
{
global $centreon;
$items = [];
// get list of authorized contactgroups
if (! $centreon->user->access->admin) {
$cgAcl = $centreon->user->access->getContactGroupAclConf(
['fields' => ['cg_id'], 'get_row' => 'cg_id', 'keys' => ['cg_id'], 'conditions' => ['cg_id' => ['IN', $values]]],
false
);
}
$aElement = [];
if (is_array($values)) {
foreach ($values as $value) {
if (preg_match_all('/\[(\w+)\]/', $value, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
if (! in_array($match[1], $aElement)) {
$aElement[] = $match[1];
}
}
} elseif (! in_array($value, $aElement)) {
$aElement[] = $value;
}
}
}
$listValues = '';
$queryValues = [];
if ($aElement !== []) {
foreach ($aElement as $k => $v) {
$listValues .= ':cg' . $v . ',';
$queryValues['cg' . $v] = (int) $v;
}
$listValues = rtrim($listValues, ',');
} else {
$listValues .= '""';
}
// get list of selected contactgroups
$query = 'SELECT cg.cg_id, cg.cg_name, cg.cg_ldap_dn, ar.ar_id, ar.ar_name FROM contactgroup cg '
. 'LEFT JOIN auth_ressource ar ON cg.ar_id = ar.ar_id '
. 'WHERE cg.cg_id IN (' . $listValues . ') ORDER BY cg.cg_name ';
$stmt = $this->db->prepare($query);
foreach ($queryValues as $key => $id) {
$stmt->bindValue(':' . $key, $id, PDO::PARAM_INT);
}
$stmt->execute();
while ($row = $stmt->fetch()) {
if (isset($row['cg_ldap_dn']) && $row['cg_ldap_dn'] != '') {
$cgName = $this->formatLdapContactgroupName($row['cg_name'], $row['ar_name']);
} else {
$cgName = $row['cg_name'];
}
$cgId = $row['cg_id'];
// hide unauthorized contactgroups
$hide = false;
if (! $centreon->user->access->admin && ! in_array($cgId, $cgAcl)) {
$hide = true;
}
$items[] = ['id' => $cgId, 'text' => $cgName, 'hide' => $hide];
}
return $items;
}
/**
* find LDAP group id by name
*
* @param int $ldapId
* @param string $name
*
* @throws PDOException
* @return int|null
*/
private function findLdapGroupIdByName(int $ldapId, string $name): ?int
{
$ldapGroupId = null;
$query = 'SELECT cg_id '
. 'FROM contactgroup '
. 'WHERE cg_name = :name '
. 'AND ar_id = :ldapId';
$statement = $this->db->prepare($query);
$statement->bindValue(':name', $name, PDO::PARAM_STR);
$statement->bindValue(':ldapId', $ldapId, PDO::PARAM_INT);
$statement->execute();
if ($row = $statement->fetch()) {
$ldapGroupId = (int) $row['cg_id'];
}
return $ldapGroupId;
}
/**
* find LDAP group id by dn
*
* @param int $ldapId
* @param string $dn
*
* @throws PDOException
* @return int|null
*/
private function findLdapGroupIdByDn(int $ldapId, string $dn): ?int
{
$ldapGroupId = null;
$query = 'SELECT cg_id '
. 'FROM contactgroup '
. 'WHERE cg_ldap_dn = :dn '
. 'AND ar_id = :ldapId';
$statement = $this->db->prepare($query);
$statement->bindValue(':dn', $dn, PDO::PARAM_STR);
$statement->bindValue(':ldapId', $ldapId, PDO::PARAM_INT);
$statement->execute();
if ($row = $statement->fetch()) {
$ldapGroupId = (int) $row['cg_id'];
}
return $ldapGroupId;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonLDAP.class.php | centreon/www/class/centreonLDAP.class.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 LDAP\Connection;
/**
* Class
*
* @class CentreonLDAP
*/
class CentreonLDAP
{
/** @var CentreonLog|null */
public $centreonLog;
/** @var Connection */
private $ds;
/** @var CentreonDB */
private $db;
/** @var string */
private $linkId;
/** @var array */
private $ldapHosts = [];
/** @var array|null */
private $ldap = null;
/** @var array */
private $constuctCache = [];
/** @var array|null */
private $userSearchInfo = null;
/** @var array|null */
private $groupSearchInfo = null;
/** @var bool */
private $debugImport = false;
/** @var string */
private $debugPath = '';
/**
* CentreonLDAP constructor
*
* @param CentreonDB $pearDB The database connection
* @param CentreonLog|null $centreonLog The logging object
* @param null $arId
*
* @throws PDOException
*/
public function __construct($pearDB, $centreonLog = null, $arId = null)
{
$this->centreonLog = $centreonLog;
$this->db = $pearDB;
// Check if use service form DNS
$use_dns_srv = 0;
$dbResult = $this->db->query(
"SELECT `ari_value`
FROM `auth_ressource_info`
WHERE `ari_name` = 'ldap_srv_dns' AND ar_id = " . (int) $arId
);
$row = $dbResult->fetch();
$dbResult->closeCursor();
if (isset($row['ari_value'])) {
$use_dns_srv = $row['ari_value'];
}
$dbResult = $this->db->query(
"SELECT `key`, `value`
FROM `options`
WHERE `key`
IN ('debug_ldap_import', 'debug_path')"
);
while ($row = $dbResult->fetch()) {
if ($row['key'] == 'debug_ldap_import') {
if ($row['value'] == 1) {
$this->debugImport = true;
}
} elseif ($row['key'] == 'debug_path') {
$this->debugPath = trim($row['value']);
}
}
$dbResult->closeCursor();
if ($this->debugPath == '') {
$this->debugImport = false;
}
$connectionTimeout = null;
$dbConnectionTimeout = $this->getLdapHostParameters($arId, 'ldap_connection_timeout');
if (! empty($dbConnectionTimeout['ari_value'])) {
$connectionTimeout = $dbConnectionTimeout['ari_value'];
}
$searchTimeout = 5;
$tempSearchTimeout = $this->getLdapHostParameters($arId, 'ldap_search_timeout');
if (! empty($tempSearchTimeout['ari_value'])) {
$searchTimeout = $tempSearchTimeout['ari_value'];
}
// Get the list of server ldap
if ($use_dns_srv != '0') {
$dns_query = '_ldap._tcp';
$dbResult = $this->db->query(
"SELECT `ari_value`
FROM auth_ressource_info
WHERE `ari_name` = 'ldap_dns_use_domain'
AND ar_id = " . (int) $arId
);
$row = $dbResult->fetch();
$dbResult->closeCursor();
if ($row && trim($row['ari_value']) != '') {
$dns_query .= '.' . $row['ari_value'];
}
$list = dns_get_record($dns_query, DNS_SRV);
foreach ($list as $entry) {
$ldap = [
'host' => $entry['target'],
'id' => $arId,
'connection_timeout' => $connectionTimeout,
'search_timeout' => $searchTimeout,
'info' => $this->getInfoUseDnsConnect(),
];
$ldap['info']['port'] = $entry['port'];
$ldap['info'] = array_merge($ldap['info'], $this->getBindInfo((int) $arId));
$this->ldapHosts[] = $ldap;
}
} else {
$dbResult = $this->db->query(
'SELECT ldap_host_id, host_address
FROM auth_ressource_host
WHERE auth_ressource_id = ' . (int) $arId . ' ORDER BY host_order'
);
while ($row = $dbResult->fetch()) {
$ldap = [
'host' => $row['host_address'],
'id' => $arId,
'connection_timeout' => $connectionTimeout,
'search_timeout' => $searchTimeout,
'info' => $this->getInfoUseDnsConnect(),
];
$ldap['info'] = $this->getInfoConnect($row['ldap_host_id']);
$ldap['info'] = array_merge($ldap['info'], $this->getBindInfo((int) $arId));
$this->ldapHosts[] = $ldap;
}
$dbResult->closeCursor();
}
}
/**
* @param int $arId
* @param string $filter
*
* @throws PDOException
* @return array<int, array<string, string>>
*/
public function getLdapHostParameters($arId, $filter = ''): array
{
// ldap_search_timeout
$queryLdapHostParameters = 'SELECT * FROM auth_ressource_info WHERE ar_id = ' . (int) $arId;
if (! empty($filter)) {
$queryLdapHostParameters .= ' AND `ari_name` = :filter';
}
$statement = $this->db->prepare($queryLdapHostParameters);
if (! empty($filter)) {
$statement->bindValue(':filter', $filter, PDO::PARAM_STR);
}
$statement->execute();
$finalLdapHostParameters = [];
while ($rowLdapHostParameters = $statement->fetch()) {
$finalLdapHostParameters = $rowLdapHostParameters;
}
return $finalLdapHostParameters;
}
/**
* Connect to the first LDAP server
*
* @return bool
*/
public function connect(): bool
{
foreach ($this->ldapHosts as $ldap) {
$port = '';
if (isset($ldap['info']['port'])) {
$port = ':' . $ldap['info']['port'];
}
if (isset($ldap['info']['use_ssl']) && $ldap['info']['use_ssl'] == 1) {
$url = 'ldaps://' . $ldap['host'] . $port . '/';
} else {
$url = 'ldap://' . $ldap['host'] . $port . '/';
}
$this->debug('LDAP Connect : trying url : ' . $url);
$this->setErrorHandler();
$this->ds = ldap_connect($url);
if (! empty($ldap['connection_timeout'])) {
ldap_set_option($this->ds, LDAP_OPT_NETWORK_TIMEOUT, $ldap['connection_timeout']);
}
ldap_set_option($this->ds, LDAP_OPT_REFERRALS, 0);
$protocol_version = 3;
if (isset($ldap['info']['protocol_version'])) {
$protocol_version = $ldap['info']['protocol_version'];
}
ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, $protocol_version);
if (isset($ldap['info']['use_tls']) && $ldap['info']['use_tls'] == 1) {
$this->debug('LDAP Connect : use tls');
@ldap_start_tls($this->ds);
}
restore_error_handler();
$this->ldap = $ldap;
$bindResult = $this->rebind();
if ($bindResult) {
return true;
}
$this->debug('LDAP Connect : connection error');
}
return false;
}
/**
* Close LDAP Connexion
*
* @return void
*/
public function close(): void
{
$this->setErrorHandler();
ldap_close($this->ds);
restore_error_handler();
}
/**
* Rebind with the default bind_dn
*
* @throws PDOException
* @return bool If the connection is good
*/
public function rebind(): bool
{
$this->setErrorHandler();
if (
isset($this->ldap['info']['bind_dn'])
&& $this->ldap['info']['bind_dn'] != ''
&& isset($this->ldap['info']['bind_pass'])
&& $this->ldap['info']['bind_pass'] != ''
) {
$this->debug('LDAP Connect : Credentials : ' . $this->ldap['info']['bind_dn']);
$bindResult = @ldap_bind($this->ds, $this->ldap['info']['bind_dn'], $this->ldap['info']['bind_pass']);
} else {
$this->debug('LDAP Connect : Credentials : anonymous');
$bindResult = @ldap_bind($this->ds);
}
if ($bindResult) {
$this->linkId = $this->ldap['id'];
$this->loadSearchInfo($this->ldap['id']);
restore_error_handler();
return true;
}
$this->debug('LDAP Connect : Bind : ' . ldap_error($this->ds));
restore_error_handler();
return false;
}
/**
* Send back the ldap resource
*
* @return Connection
*/
public function getDs()
{
return $this->ds;
}
/**
* Escape special characters in LDAP filter value for username and group
* @see https://datatracker.ietf.org/doc/html/rfc4515#section-3
*
* @param string $name The attribute to escape
* @return string The escaped string
*/
public function escapeLdapFilterSpecialChars($name): string
{
$specialChars = [
'\\' => '\\5C',
'*' => '\\2A',
'(' => '\\28',
')' => '\\29',
'\0' => '\\00',
];
foreach ($specialChars as $char => $replace) {
$name = str_replace($char, $replace, $name);
}
return $name;
}
/**
* Get the dn for a user
*
* @param string $username The username
* @return string|bool The dn string or false if not found
*/
public function findUserDn($username): string|false
{
if (trim($this->userSearchInfo['filter']) == '') {
return false;
}
$this->setErrorHandler();
$filter = preg_replace('/%s/', $this->escapeLdapFilterSpecialChars($username), $this->userSearchInfo['filter']);
$result = ldap_search($this->ds, $this->userSearchInfo['base_search'], $filter);
// no results were returned using this base_search
if ($result === false) {
return false;
}
$entries = ldap_get_entries($this->ds, $result);
restore_error_handler();
if ($entries['count'] === 0) {
return false;
}
return $entries[0]['dn'];
}
/**
* Get the dn for a group
*
* @param string $group The group
* @return string|bool The dn string or false if not found
*/
public function findGroupDn($group): string|false
{
if (trim($this->groupSearchInfo['filter']) == '') {
return false;
}
$this->setErrorHandler();
$filter = ldap_escape($group);
$result = ldap_search($this->ds, $this->groupSearchInfo['base_search'], $filter);
$entries = ldap_get_entries($this->ds, $result);
restore_error_handler();
if ($entries['count'] === 0) {
return false;
}
return $entries[0]['dn'];
}
/**
* Return the list of groups
*
* @param string $pattern The pattern for search
* @return array<array<string,string>> The list of groups
*/
public function listOfGroups($pattern = '*'): array
{
if (! isset($this->groupSearchInfo['filter']) || trim($this->groupSearchInfo['filter']) === '') {
return [];
}
$this->setErrorHandler();
$escapedPattern = ldap_escape($pattern, '*', LDAP_ESCAPE_FILTER);
$filter = preg_replace('/%s/', $escapedPattern, $this->groupSearchInfo['filter']);
$result = @ldap_search($this->ds, $this->groupSearchInfo['base_search'], $filter);
if ($result === false) {
restore_error_handler();
return [];
}
$entries = ldap_get_entries($this->ds, $result);
$groups = [];
for ($i = 0; $i < $entries['count']; $i++) {
$groups[] = [
'name' => $entries[$i][$this->groupSearchInfo['group_name']][0],
'dn' => $entries[$i]['dn'],
];
}
restore_error_handler();
return $groups;
}
/**
* Return the list of users
*
* @param string $pattern The pattern for search
* @return array The list of users
*/
public function listOfUsers($pattern = '*'): array
{
if (trim($this->userSearchInfo['filter']) == '') {
return [];
}
$this->setErrorHandler();
$escapedPattern = ldap_escape($pattern, '*', LDAP_ESCAPE_FILTER);
$filter = preg_replace('/%s/', $escapedPattern, $this->userSearchInfo['filter']);
$result = ldap_search($this->ds, $this->userSearchInfo['base_search'], $filter);
$entries = ldap_get_entries($this->ds, $result);
$nbEntries = $entries['count'];
$list = [];
for ($i = 0; $i < $nbEntries; $i++) {
$list[] = $entries[$i][$this->userSearchInfo['alias']][0];
}
restore_error_handler();
return $list;
}
/**
* Get a LDAP entry
*
* @param string $dn The DN
* @param array $attr The list of attribute
* @return array|bool The list of information, or false in error
*/
public function getEntry($dn, $attr = []): array|false
{
$this->setErrorHandler();
if (! is_array($attr)) {
$attr = [$attr];
}
$result = ldap_read($this->ds, $dn, '(objectClass=*)', $attr);
if ($result === false) {
restore_error_handler();
return false;
}
$entry = ldap_get_entries($this->ds, $result);
if ($entry['count'] === 0) {
restore_error_handler();
return false;
}
$infos = [];
foreach ($entry[0] as $info => $value) {
if (isset($value['count'])) {
if ($value['count'] === 1) {
$infos[$info] = $value[0];
} elseif ($value['count'] > 1) {
$infos[$info] = [];
for ($i = 0; $i < $value['count']; $i++) {
$infos[$info][$i] = $value[$i];
}
}
}
}
restore_error_handler();
return $infos;
}
/**
* Get the list of groups for a user
*
* @param string $userdn The user dn
* @return array
*/
public function listGroupsForUser($userdn): array
{
$this->setErrorHandler();
if (trim($this->groupSearchInfo['filter']) === '') {
restore_error_handler();
return [];
}
$filter = '(&' . preg_replace('/%s/', '*', $this->groupSearchInfo['filter'])
. '(' . $this->groupSearchInfo['member'] . '=' . ldap_escape($userdn, '', LDAP_ESCAPE_FILTER) . '))';
$result = @ldap_search($this->ds, $this->groupSearchInfo['base_search'], $filter);
if ($result === false) {
restore_error_handler();
return [];
}
$entries = ldap_get_entries($this->ds, $result);
$nbEntries = $entries['count'];
$list = [];
for ($i = 0; $i < $nbEntries; $i++) {
$list[] = $entries[$i][$this->groupSearchInfo['group_name']][0];
}
restore_error_handler();
return $list;
}
/**
* Return the list of member of a group
*
* @param string $groupdn The group dn
* @return array The list of member
*/
public function listUserForGroup($groupdn): array
{
$this->setErrorHandler();
if (trim($this->userSearchInfo['filter']) == '') {
restore_error_handler();
return [];
}
$list = [];
if (! empty($this->userSearchInfo['group'])) {
/**
* we have specific parameter for user to denote groups he belongs to
*/
$filter = '(&' . preg_replace('/%s/', '*', $this->userSearchInfo['filter'])
. '(' . $this->userSearchInfo['group'] . '=' . ldap_escape($groupdn) . '))';
$result = @ldap_search($this->ds, $this->userSearchInfo['base_search'], $filter);
if ($result === false) {
restore_error_handler();
return [];
}
$entries = ldap_get_entries($this->ds, $result);
$nbEntries = $entries['count'];
for ($i = 0; $i < $nbEntries; $i++) {
$list[] = $entries[$i]['dn'];
}
restore_error_handler();
} else {
/**
* we get list of members by group
*/
$filter = preg_replace('/%s/', $this->getCnFromDn($groupdn), $this->groupSearchInfo['filter']);
$result = @ldap_search($this->ds, $this->groupSearchInfo['base_search'], $filter);
if ($result === false) {
restore_error_handler();
return [];
}
$entries = ldap_get_entries($this->ds, $result);
$memberAttribute = $this->groupSearchInfo['member'];
$nbEntries = ! empty($entries[0][$memberAttribute]['count']) ? $entries[0][$memberAttribute]['count'] : 0;
for ($i = 0; $i < $nbEntries; $i++) {
$list[] = $entries[0][$memberAttribute][$i];
}
restore_error_handler();
}
return $list;
}
/**
* Return the attribute name for ldap
*
* @param string $type user or group
* @param string $info The information to get the attribute name
* @return string|null The attribute name or null if not found
*/
public function getAttrName($type, $info): ?string
{
switch ($type) {
case 'user':
if (isset($this->userSearchInfo[$info])) {
return $this->userSearchInfo[$info];
}
break;
case 'group':
if (isset($this->groupSearchInfo[$info])) {
return $this->groupSearchInfo[$info];
}
break;
default:
return null;
}
return null;
}
/**
* Search function
*
* @param string|null $filter The filter string, null for use default
* @param string $basedn The basedn, null for use default
* @param int $searchLimit The search limit, null for all
* @param int $searchTimeout The search timeout, null for default
* @return array<int, array<string, mixed>> The search result
*/
public function search($filter, $basedn, $searchLimit, $searchTimeout): array
{
$this->setErrorHandler();
$attr = [$this->userSearchInfo['alias'], $this->userSearchInfo['name'], $this->userSearchInfo['email'], $this->userSearchInfo['pager'], $this->userSearchInfo['firstname'], $this->userSearchInfo['lastname']];
// Set default
if (is_null($filter)) {
$filter = $this->userSearchInfo['filter'];
}
if (is_null($basedn)) {
$filter = $this->userSearchInfo['base_search'];
}
if (is_null($searchLimit)) {
$searchLimit = 0;
}
if (is_null($searchTimeout)) {
$searchTimeout = 0;
}
// Display debug
$this->debug('LDAP Search : Base DN : ' . $basedn);
$this->debug('LDAP Search : Filter : ' . $filter);
$this->debug('LDAP Search : Size Limit : ' . $searchLimit);
$this->debug('LDAP Search : Timeout : ' . $searchTimeout);
// Search
$filter = preg_replace('/%s/', '*', $filter);
$sr = ldap_search($this->ds, $basedn, $filter, $attr, 0, $searchLimit, $searchTimeout);
// Sort
if ($sr !== false) {
$numberReturned = ldap_count_entries($this->ds, $sr);
$this->debug('LDAP Search : ' . ($numberReturned ?? '0') . ' entries found');
} else {
$this->debug('LDAP Search : cannot retrieve entries');
return [];
}
$info = ldap_get_entries($this->ds, $sr);
$this->debug('LDAP Search : ' . $info['count']);
ldap_free_result($sr);
// Format the result
$results = [];
for ($i = 0; $i < $info['count']; $i++) {
$result = [];
$result['dn'] = $info[$i]['dn'] ?? '';
$result['alias'] = $info[$i][$this->userSearchInfo['alias']][0] ?? '';
$result['name'] = $info[$i][$this->userSearchInfo['name']][0] ?? '';
$result['email'] = $info[$i][$this->userSearchInfo['email']][0] ?? '';
$result['pager'] = $info[$i][$this->userSearchInfo['pager']][0] ?? '';
$result['firstname'] = $info[$i][$this->userSearchInfo['firstname']][0] ?? '';
$result['lastname'] = $info[$i][$this->userSearchInfo['lastname']][0] ?? '';
$results[] = $result;
}
restore_error_handler();
return $results;
}
/**
* Validate the filter string
*
* @param string $filter The filter string to validate
* @return bool
*/
public static function validateFilterPattern($filter): bool
{
return ! (! str_contains($filter, '%s'));
}
/**
* Set a relation between the LDAP's default contactgroup and the user
*
* @internal Method needed for the user's manual and auto import from the LDAP
* @since 18.10.4
*
* @param int|null $arId The Id of the chosen LDAP, from which we'll find the default contactgroup
* @param int|null $contactId The Id of the contact to be added
*
* @throws exception
* @return bool Return true to the parent if everything goes well. Needed for the method calling it
*/
public function addUserToLdapDefaultCg(?int $arId = null, ?int $contactId = null): bool
{
$ldapCg = null;
try {
// Searching the default contactgroup chosen in the ldap configuration
$resLdap = $this->db->prepare(
'SELECT ari_value FROM auth_ressource_info '
. "WHERE ari_name LIKE 'ldap_default_cg' AND ar_id = :arId"
);
$resLdap->bindValue(':arId', $arId, PDO::PARAM_INT);
$resLdap->execute();
while ($result = $resLdap->fetch()) {
$ldapCg = $result['ari_value'];
}
unset($resLdap);
if (! $ldapCg) {
// No default contactgroup was set in the LDAP parameters
return true;
}
// Checking if the user isn't already linked to this contactgroup
$resCgExist = $this->db->prepare(
'SELECT COUNT(*) AS `exist` FROM contactgroup_contact_relation '
. 'WHERE contact_contact_id = :contactId '
. 'AND contactgroup_cg_id = :ldapCg'
);
$resCgExist->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$resCgExist->bindValue(':ldapCg', $ldapCg, PDO::PARAM_INT);
$resCgExist->execute();
$row = $resCgExist->fetch();
unset($resCgExist);
if ($row['exist'] != 0) {
// User is already linked to this contactgroup
return true;
}
// Inserting the user to the chosen default contactgroup
$resCg = $this->db->prepare(
'INSERT INTO contactgroup_contact_relation '
. '(contactgroup_cg_id, contact_contact_id) '
. 'VALUES (:ldapDefaultCg, :contactId)'
);
$resCg->bindValue(':ldapDefaultCg', $ldapCg, PDO::PARAM_INT);
$resCg->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$resCg->execute();
unset($resCg);
} catch (PDOException $e) {
return false;
}
return true;
}
/**
* Update user's LDAP last sync in the contact table
*
* @param array<string, mixed> $currentUser User's alias and Id are needed
* @throws Exception
* @return void
*/
public function setUserCurrentSyncTime(array $currentUser): void
{
$stmt = $this->db->prepare(
"UPDATE contact SET
`contact_ldap_last_sync` = :currentTime,
`contact_ldap_required_sync` = '0'
WHERE contact_id = :contactId"
);
try {
$stmt->bindValue(':currentTime', time(), PDO::PARAM_INT);
$stmt->bindValue(':contactId', $currentUser['contact_id'], PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
$this->centreonLog->insertLog(
3,
"LDAP MANUAL SYNC : Failed to update ldap_last_sync's values for " . $currentUser['contact_alias']
);
}
}
/**
* If the option is disabled in the LDAP parameter's form, we don't sync the LDAP user's modifications on login
* unless it's required
* If it's enabled, we need to wait until the next synchronization
*
* @param int $arId Id of the current LDAP
* @param int $contactId Id the contact
* @return bool
* @internal Needed on user's login and when manually requesting an update of user's LDAP data
*/
public function isSyncNeededAtLogin(int $arId, int $contactId): bool
{
try {
// checking if an override was manually set on this contact
$stmtManualRequest = $this->db->prepare(
'SELECT `contact_name`, `contact_ldap_required_sync`, `contact_ldap_last_sync`
FROM contact WHERE contact_id = :contactId'
);
$stmtManualRequest->bindValue(':contactId', $contactId, PDO::PARAM_INT);
$stmtManualRequest->execute();
$contactData = $stmtManualRequest->fetch();
// check if a manual override was set for this user
if ($contactData !== false && $contactData['contact_ldap_required_sync'] === '1') {
$this->centreonLog->insertLog(
3,
'LDAP AUTH : LDAP synchronization was requested manually for ' . $contactData['contact_name']
);
return true;
}
// getting the synchronization options
$stmtSyncState = $this->db->prepare(
"SELECT ari_name, ari_value FROM auth_ressource_info
WHERE ari_name IN ('ldap_auto_sync', 'ldap_sync_interval')
AND ar_id = :arId"
);
$stmtSyncState->bindValue(':arId', $arId, PDO::PARAM_INT);
$stmtSyncState->execute();
$syncState = [];
while ($row = $stmtSyncState->fetch()) {
$syncState[$row['ari_name']] = $row['ari_value'];
}
if ($syncState['ldap_auto_sync'] || $contactData['contact_ldap_last_sync'] === 0) {
// getting the base date reference set in the LDAP parameters
$stmtLdapBaseSync = $this->db->prepare(
'SELECT ar_sync_base_date AS `referenceDate` FROM auth_ressource
WHERE ar_id = :arId'
);
$stmtLdapBaseSync->bindValue(':arId', $arId, PDO::PARAM_INT);
$stmtLdapBaseSync->execute();
$ldapBaseSync = $stmtLdapBaseSync->fetch();
// checking if the interval between two synchronizations is reached
$currentTime = time();
if (
($syncState['ldap_sync_interval'] * 3600 + $contactData['contact_ldap_last_sync']) <= $currentTime
&& $contactData['contact_ldap_last_sync'] < $ldapBaseSync['referenceDate']
) {
// synchronization is expected
$this->centreonLog->insertLog(
3,
'LDAP AUTH : Updating user DN of ' . $contactData['contact_name']
);
return true;
}
}
} catch (PDOException $e) {
$this->centreonLog->insertLog(
3,
'Error while getting automatic synchronization value for LDAP Id : ' . $arId
);
// assuming it needs to be synchronized
return true;
}
$this->centreonLog->insertLog(
3,
'LDAP AUTH : Synchronization was skipped. For more details, check your LDAP parameters in Administration'
);
return false;
}
/**
* Override the custom errorHandler to avoid false errors in the log,
*
* @param int $errno The error num
* @param string $errstr The error message
* @param string $errfile The error file
* @param int $errline The error line
* @return bool
*/
public function errorLdapHandler($errno, $errstr, $errfile, $errline): bool
{
if ($errno === 2 && ldap_errno($this->ds) === 4) {
/*
Silencing : 'size limit exceeded' warnings in the logs
As the $searchLimit value needs to be consistent with the ldap server's configuration and
as the size limit error thrown is not related with the results.
ldap_errno : 4 = LDAP_SIZELIMIT_EXCEEDED
$errno : 2 = PHP_WARNING
*/
$this->debug('LDAP Error : Size limit exceeded error. This error was not added to php log. '
. "Kindly, check your LDAP server's configuration and your Centreon's LDAP parameters.");
return true;
}
// throwing all errors
$this->debug('LDAP Error : ' . ldap_error($this->ds));
return false;
}
/**
* Load the search information
*
* @param null $ldapHostId
*
* @throws PDOException
* @return void
*/
private function loadSearchInfo($ldapHostId = null): void
{
if (is_null($ldapHostId)) {
$ldapHostId = $this->linkId;
}
$dbResult = $this->db->query(
"SELECT ari_name, ari_value
FROM auth_ressource_info ari
WHERE ari_name IN
('user_filter', 'user_base_search', 'alias', 'user_group', 'user_name', 'user_email', 'user_pager',
'user_firstname', 'user_lastname', 'group_filter', 'group_base_search', 'group_name', 'group_member')
AND ari.ar_id = " . (int) $ldapHostId
);
$user = [];
$group = [];
while ($row = $dbResult->fetch()) {
switch ($row['ari_name']) {
case 'user_filter':
$user['filter'] = $row['ari_value'];
break;
case 'user_base_search':
$user['base_search'] = $row['ari_value'];
// Fix for domino
if (trim($user['base_search']) == '') {
$user['base_search'] = '';
}
break;
case 'alias':
$user['alias'] = $row['ari_value'];
break;
case 'user_group':
$user['group'] = $row['ari_value'];
break;
case 'user_name':
$user['name'] = $row['ari_value'];
break;
case 'user_email':
$user['email'] = $row['ari_value'];
break;
case 'user_pager':
$user['pager'] = $row['ari_value'];
break;
case 'user_firstname':
$user['firstname'] = $row['ari_value'];
break;
case 'user_lastname':
$user['lastname'] = $row['ari_value'];
break;
case 'group_filter':
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | true |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/www/class/centreonMenu.class.php | centreon/www/class/centreonMenu.class.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
*
*/
/**
* Class
*
* @class CentreonMenu
*/
class CentreonMenu
{
/** @var CentreonLang */
protected $centreonLang;
/** @var CentreonDB */
protected $db;
/**
* CentreonMenu constructor
*
* @param CentreonLang $centreonLang
*/
public function __construct($centreonLang)
{
$this->centreonLang = $centreonLang;
}
/**
* translates
*
* @param int $isModule
* @param string $url
* @param string $menuName
*
* @return string
*/
public function translate($isModule, $url, $menuName)
{
$moduleName = '';
if ($isModule && $url) {
if (preg_match("/\.\/modules\/([a-zA-Z-_]+)/", $url, $matches)) {
if (isset($matches[1])) {
$moduleName = $matches[1];
}
}
}
$name = _($menuName);
if ($moduleName) {
$this->centreonLang->bindLang('messages', 'www/modules/' . $moduleName . '/locale/');
$name = _($menuName);
$this->centreonLang->bindLang();
}
return $name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.